Passed
Pull Request — master (#188)
by Dmitriy
08:42 queued 06:05
created

JsonMessageSerializer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 9 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
            '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 4
        $message = new Message('$name', $payload['data'] ?? null, $meta);
43
44 4
        if (isset($meta[EnvelopeInterface::ENVELOPE_STACK_KEY]) && is_array($meta[EnvelopeInterface::ENVELOPE_STACK_KEY])) {
45 2
            $message = $message->withMetadata(
46 2
                array_merge($message->getMetadata(), [EnvelopeInterface::ENVELOPE_STACK_KEY => []]),
47 2
            );
48 2
            foreach ($meta[EnvelopeInterface::ENVELOPE_STACK_KEY] as $envelope) {
49 2
                if (is_string($envelope) && class_exists($envelope) && is_subclass_of($envelope, EnvelopeInterface::class)) {
50 2
                    $message = $envelope::fromMessage($message);
51
                }
52
            }
53
        }
54
55
56 4
        return $message;
57
    }
58
}
59