|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Queue\AMQP; |
|
6
|
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
use JsonException; |
|
9
|
|
|
use Yiisoft\Queue\AMQP\Exception\NoKeyInPayloadException; |
|
10
|
|
|
use Yiisoft\Queue\Message\Message; |
|
11
|
|
|
use Yiisoft\Queue\Message\MessageInterface; |
|
12
|
|
|
|
|
13
|
|
|
class MessageSerializer implements MessageSerializerInterface |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @throws JsonException |
|
17
|
|
|
*/ |
|
18
|
|
|
public function serialize(MessageInterface $message): string |
|
19
|
|
|
{ |
|
20
|
|
|
$payload = [ |
|
21
|
|
|
'id' => $message->getId(), |
|
|
|
|
|
|
22
|
|
|
'name' => $message->getHandlerName(), |
|
23
|
|
|
'data' => $message->getData(), |
|
24
|
|
|
'meta' => $message->getMetadata(), |
|
25
|
|
|
]; |
|
26
|
|
|
|
|
27
|
|
|
return json_encode($payload, JSON_THROW_ON_ERROR); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @throws JsonException |
|
32
|
|
|
* @throws NoKeyInPayloadException |
|
33
|
|
|
* @throws InvalidArgumentException |
|
34
|
|
|
*/ |
|
35
|
|
|
public function unserialize(string $value): Message |
|
36
|
|
|
{ |
|
37
|
|
|
$payload = json_decode($value, true, 512, JSON_THROW_ON_ERROR); |
|
38
|
|
|
if (!is_array($payload)) { |
|
39
|
|
|
throw new InvalidArgumentException('Payload must be array. Got ' . get_debug_type($payload) . '.'); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$name = $payload['name'] ?? null; |
|
43
|
|
|
if (!is_string($name)) { |
|
44
|
|
|
throw new NoKeyInPayloadException('name', $payload); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$id = $payload['id'] ?? null; |
|
48
|
|
|
if ($id !== null && !is_string($id)) { |
|
49
|
|
|
throw new NoKeyInPayloadException('id', $payload); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$meta = $payload['meta'] ?? []; |
|
53
|
|
|
if (!is_array($meta)) { |
|
54
|
|
|
throw new NoKeyInPayloadException('meta', $payload); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return new Message( |
|
58
|
|
|
$name, |
|
59
|
|
|
$payload['data'] ?? null, |
|
60
|
|
|
$meta, |
|
61
|
|
|
$id, |
|
|
|
|
|
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|