/
Publisher.php
88 lines (77 loc) · 2.69 KB
/
Publisher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/*
* This file is part of the Mercure Component project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Symfony\Component\Mercure;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Mercure\Internal\QueryBuilder;
use Symfony\Component\Mercure\Jwt\TokenProviderInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
trigger_deprecation('symfony/mercure', '0.5', 'Class "%s" is deprecated, use "%s" instead.', Publisher::class, Hub::class);
/**
* Publishes an update to the hub.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*
* @experimental
*
* @deprecated
*/
final class Publisher implements PublisherInterface
{
private $hubUrl;
private $jwtProvider;
private $httpClient;
/**
* @param TokenProviderInterface|callable(Update $update):string $jwtProvider
*/
public function __construct(string $hubUrl, $jwtProvider, ?HttpClientInterface $httpClient = null)
{
$this->hubUrl = $hubUrl;
$this->jwtProvider = $jwtProvider;
$this->httpClient = $httpClient ?? HttpClient::create();
}
public function __invoke(Update $update): string
{
$postData = [
'topic' => $update->getTopics(),
'data' => $update->getData(),
'private' => $update->isPrivate() ? 'on' : null,
'id' => $update->getId(),
'type' => $update->getType(),
'retry' => $update->getRetry(),
];
if ($this->jwtProvider instanceof TokenProviderInterface) {
$jwt = $this->jwtProvider->getJwt();
} else {
$jwt = ($this->jwtProvider)($update);
}
$this->validateJwt($jwt);
return $this->httpClient->request('POST', $this->hubUrl, [
'auth_bearer' => $jwt,
'body' => QueryBuilder::build($postData),
])->getContent();
}
/**
* Regex ported from Windows Azure Active Directory IdentityModel Extensions for .Net.
*
* @throws Exception\InvalidArgumentException
*
* @license MIT
* @copyright Copyright (c) Microsoft Corporation
*
* @see https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/6e7a53e241e4566998d3bf365f03acd0da699a31/src/Microsoft.IdentityModel.JsonWebTokens/JwtConstants.cs#L58
*/
private function validateJwt(string $jwt): void
{
if (!preg_match('/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/', $jwt)) {
throw new Exception\InvalidArgumentException('The provided JWT is not valid.');
}
}
}