-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathMessageSerializer.php
More file actions
64 lines (54 loc) · 1.68 KB
/
MessageSerializer.php
File metadata and controls
64 lines (54 loc) · 1.68 KB
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
<?php
declare(strict_types=1);
namespace Yiisoft\Queue\AMQP;
use InvalidArgumentException;
use JsonException;
use Yiisoft\Queue\AMQP\Exception\NoKeyInPayloadException;
use Yiisoft\Queue\Message\Message;
use Yiisoft\Queue\Message\MessageInterface;
class MessageSerializer implements MessageSerializerInterface
{
/**
* @throws JsonException
*/
public function serialize(MessageInterface $message): string
{
$payload = [
'id' => $message->getId(),
'name' => $message->getHandlerName(),
'data' => $message->getData(),
'meta' => $message->getMetadata(),
];
return json_encode($payload, JSON_THROW_ON_ERROR);
}
/**
* @throws JsonException
* @throws NoKeyInPayloadException
* @throws InvalidArgumentException
*/
public function unserialize(string $value): Message
{
$payload = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
if (!is_array($payload)) {
throw new InvalidArgumentException('Payload must be array. Got ' . get_debug_type($payload) . '.');
}
$name = $payload['name'] ?? null;
if (!is_string($name)) {
throw new NoKeyInPayloadException('name', $payload);
}
$id = $payload['id'] ?? null;
if ($id !== null && !is_string($id)) {
throw new NoKeyInPayloadException('id', $payload);
}
$meta = $payload['meta'] ?? [];
if (!is_array($meta)) {
throw new NoKeyInPayloadException('meta', $payload);
}
return new Message(
$name,
$payload['data'] ?? null,
$meta,
$id,
);
}
}