Passed
Pull Request — master (#190)
by Dmitriy
02:42
created

JsonMessageSerializer::unserialize()   B

Complexity

Conditions 9
Paths 4

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 9

Importance

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