Test Failed
Pull Request — master (#111)
by Viktor
15:25
created

MessageSerializer   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 24
dl 0
loc 51
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 10 1
B unserialize() 0 29 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Queue\AMQP;
6
7
use InvalidArgumentException;
8
use JsonException;
9
use Yiisoft\Queue\AMQP\Exception\NoKeyInPayloadException;
10
use Yiisoft\Queue\Message\IdEnvelope;
11
use Yiisoft\Queue\Message\Message;
12
use Yiisoft\Queue\Message\MessageInterface;
13
14
class MessageSerializer implements MessageSerializerInterface
15
{
16
    /**
17
     * @throws JsonException
18
     */
19
    public function serialize(MessageInterface $message): string
20
    {
21
        $payload = [
22
            'id' => IdEnvelope::fromMessage($message)->getId(),
23
            'name' => $message->getHandlerName(),
24
            'data' => $message->getData(),
25
            'meta' => $message->getMetadata(),
26
        ];
27
28
        return json_encode($payload, JSON_THROW_ON_ERROR);
29
    }
30
31
    /**
32
     * @throws JsonException
33
     * @throws NoKeyInPayloadException
34
     * @throws InvalidArgumentException
35
     */
36
    public function unserialize(string $value): MessageInterface
37
    {
38
        $payload = json_decode($value, true, 512, JSON_THROW_ON_ERROR);
39
        if (!is_array($payload)) {
40
            throw new InvalidArgumentException('Payload must be array. Got ' . get_debug_type($payload) . '.');
41
        }
42
43
        $name = $payload['name'] ?? null;
44
        if (!is_string($name)) {
45
            throw new NoKeyInPayloadException('name', $payload);
46
        }
47
48
        $id = $payload['id'] ?? null;
49
        if ($id !== null && !is_string($id) && !is_int($id)) {
50
            throw new NoKeyInPayloadException('id', $payload);
51
        }
52
53
        $meta = $payload['meta'] ?? [];
54
        if (!is_array($meta)) {
55
            throw new NoKeyInPayloadException('meta', $payload);
56
        }
57
58
        $message = new Message(
59
            $name,
60
            $payload['data'] ?? null,
61
            $meta,
62
        );
63
64
        return $id === null ? $message : new IdEnvelope($message, $id);
65
    }
66
}
67