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