Passed
Pull Request — master (#190)
by Alexander
05:09 queued 02:32
created

JsonMessageSerializer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 46
ccs 22
cts 22
cp 1
rs 10
c 1
b 0
f 0
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 8 1
B unserialize() 0 27 9
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