-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathJsonMessageSerializer.php
62 lines (51 loc) · 1.84 KB
/
JsonMessageSerializer.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
<?php
declare(strict_types=1);
namespace Yiisoft\Queue\Message;
use InvalidArgumentException;
use JsonException;
final class JsonMessageSerializer implements MessageSerializerInterface
{
/**
* @throws JsonException
*/
public function serialize(MessageInterface $message): string
{
$payload = [
'name' => $message->getHandlerName(),
'data' => $message->getData(),
'meta' => $message->getMetadata(),
];
return json_encode($payload, JSON_THROW_ON_ERROR);
}
/**
* @throws JsonException
* @throws InvalidArgumentException
*/
public function unserialize(string $value): MessageInterface
{
$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) . '.');
}
$meta = $payload['meta'] ?? [];
if (!is_array($meta)) {
throw new InvalidArgumentException('Metadata must be array. Got ' . get_debug_type($meta) . '.');
}
$envelopes = [];
if (isset($meta[EnvelopeInterface::ENVELOPE_STACK_KEY]) && is_array($meta[EnvelopeInterface::ENVELOPE_STACK_KEY])) {
$envelopes = $meta[EnvelopeInterface::ENVELOPE_STACK_KEY];
}
$meta[EnvelopeInterface::ENVELOPE_STACK_KEY] = [];
// TODO: will be removed later
$message = new Message($payload['name'] ?? '$name', $payload['data'] ?? null, $meta);
foreach ($envelopes as $envelope) {
if (is_string($envelope) && class_exists($envelope) && is_subclass_of(
$envelope,
EnvelopeInterface::class
)) {
$message = $envelope::fromMessage($message);
}
}
return $message;
}
}