1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Facile\CrossbarHTTPPublisherBundle\Publisher; |
4
|
|
|
|
5
|
|
|
use Facile\CrossbarHTTPPublisherBundle\Exception\PublishRequestException; |
6
|
|
|
use GuzzleHttp\Client; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class Publisher |
10
|
|
|
* @package Facile\CrossbarHTTPPublisherBundle\Publisher |
11
|
|
|
*/ |
12
|
|
|
class Publisher |
13
|
|
|
{ |
14
|
|
|
private Client $client; |
15
|
|
|
private ?string $key; |
16
|
|
|
private ?string $secret; |
17
|
|
|
|
18
|
|
|
public function __construct(Client $client, ?string $key, ?string $secret) |
19
|
|
|
{ |
20
|
|
|
$this->client = $client; |
21
|
|
|
$this->key = $key; |
22
|
|
|
$this->secret = $secret; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @return array JSON decoded response |
27
|
|
|
* @throws \Exception |
28
|
4 |
|
*/ |
29
|
|
|
public function publish(string $topic, ?array $args = null, ?array $kwargs = null): array |
30
|
4 |
|
{ |
31
|
4 |
|
$jsonBody = $this->prepareBody($topic, $args, $kwargs); |
32
|
4 |
|
|
33
|
4 |
|
try { |
34
|
|
|
$response = $this->client->post( |
35
|
|
|
'', |
36
|
|
|
[ |
37
|
|
|
'json' => $jsonBody, |
38
|
|
|
'query' => $this->prepareSignature($jsonBody) |
39
|
|
|
] |
40
|
|
|
); |
41
|
|
|
} catch (\Exception $e) { |
42
|
3 |
|
throw new PublishRequestException($e->getMessage(), 500, $e); |
43
|
|
|
} |
44
|
3 |
|
|
45
|
|
|
return json_decode($response->getBody(), true); |
46
|
|
|
} |
47
|
3 |
|
|
48
|
3 |
|
private function prepareBody(string $topic, ?array $args, ?array $kwargs): array |
49
|
|
|
{ |
50
|
3 |
|
$body = []; |
51
|
3 |
|
|
52
|
|
|
$body['topic'] = $topic; |
53
|
|
|
|
54
|
1 |
|
if (null !== $args) { |
|
|
|
|
55
|
1 |
|
$body['args'] = $args; |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
if (null !== $kwargs) { |
|
|
|
|
59
|
|
|
$body['kwargs'] = $kwargs; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $body; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private function prepareSignature(array $body): array |
66
|
|
|
{ |
67
|
3 |
|
$query = []; |
68
|
|
|
|
69
|
3 |
|
$seq = mt_rand(0, 2 ** 12); |
70
|
|
|
$now = new \DateTime('now', new \DateTimeZone('UTC')); |
71
|
3 |
|
$timestamp = $now->format("Y-m-d\TH:i:s.u\Z"); |
72
|
|
|
|
73
|
3 |
|
$query['seq'] = $seq; |
74
|
1 |
|
$query['timestamp'] = $timestamp; |
75
|
|
|
|
76
|
|
|
if (null !== $this->key && null !== $this->secret) { |
77
|
3 |
|
|
78
|
2 |
|
$nonce = mt_rand(0, 2 ** 53); |
79
|
|
|
$signature = hash_hmac( |
80
|
|
|
'sha256', |
81
|
3 |
|
$this->key . $timestamp . $seq . $nonce . json_encode($body), |
82
|
|
|
$this->secret, |
83
|
|
|
true |
84
|
|
|
); |
85
|
|
|
|
86
|
|
|
$query['key'] = $this->key; |
87
|
|
|
$query['nonce'] = $nonce; |
88
|
3 |
|
$query['signature'] = strtr(base64_encode($signature), '+/', '-_'); |
89
|
|
|
} |
90
|
3 |
|
|
91
|
|
|
return $query; |
92
|
3 |
|
} |
93
|
|
|
} |
94
|
|
|
|