Passed
Pull Request — master (#214)
by Alexander
04:53 queued 02:12
created

JsonMessageSerializer::serialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
ccs 8
cts 8
cp 1
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Queue\Message;
6
7
use InvalidArgumentException;
8
use JsonException;
9
10
final class JsonMessageSerializer implements MessageSerializerInterface
11
{
12
    /**
13
     * @throws JsonException
14
     */
15 4
    public function serialize(MessageInterface $message): string
16
    {
17 4
        $payload = [
18 4
            'name' => $message->getHandlerName(),
19 4
            'data' => $message->getData(),
20 4
            'meta' => $message->getMetadata(),
21 4
            'class' => $message instanceof EnvelopeInterface ? $message->getMessage()::class : $message::class,
22 4
        ];
23
24 4
        return json_encode($payload, JSON_THROW_ON_ERROR);
25
    }
26
27
    /**
28
     * @throws JsonException
29
     * @throws InvalidArgumentException
30
     */
31 13
    public function unserialize(string $value): MessageInterface
32
    {
33 13
        $payload = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
34 13
        if (!is_array($payload)) {
35 4
            throw new InvalidArgumentException('Payload must be array. Got ' . get_debug_type($payload) . '.');
36
        }
37
38 9
        $name = $payload['name'] ?? null;
39 9
        if (!isset($name) || !is_string($name)) {
40
            throw new InvalidArgumentException('Handler name must be string. Got ' . get_debug_type($name) . '.');
41
        }
42
43 9
        $meta = $payload['meta'] ?? [];
44 9
        if (!is_array($meta)) {
45 3
            throw new InvalidArgumentException('Metadata must be array. Got ' . get_debug_type($meta) . '.');
46
        }
47
48 6
        $envelopes = [];
49 6
        if (isset($meta[EnvelopeInterface::ENVELOPE_STACK_KEY]) && is_array($meta[EnvelopeInterface::ENVELOPE_STACK_KEY])) {
50 3
            $envelopes = $meta[EnvelopeInterface::ENVELOPE_STACK_KEY];
51
        }
52 6
        $meta[EnvelopeInterface::ENVELOPE_STACK_KEY] = [];
53
54 6
        $class = $payload['class'] ?? Message::class;
55 6
        if (!is_subclass_of($class, MessageInterface::class)) {
56
            $class = Message::class;
57
        }
58
59
        /**
60
         * @var class-string<MessageInterface> $class
61
         */
62 6
        $message = $class::fromData($name, $payload['data'] ?? null, $meta);
63
64 6
        foreach ($envelopes as $envelope) {
65 3
            if (is_string($envelope) && class_exists($envelope) && is_subclass_of($envelope, EnvelopeInterface::class)) {
66 3
                $message = $envelope::fromMessage($message);
67
            }
68
        }
69
70 6
        return $message;
71
    }
72
}
73