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