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