Passed
Push — master ( 5339df...fb5d3c )
by Alexander
03:17
created

JsonMessageSerializer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 48
ccs 23
cts 23
cp 1
rs 10
wmc 10

2 Methods

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