Completed
Push — master ( 07b379...e3da56 )
by Tobias
02:12
created

SerializerRouter   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 78.95%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 48
ccs 15
cts 19
cp 0.7895
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B decode() 0 21 7
A encode() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Happyr\MessageSerializer;
6
7
use Happyr\MessageSerializer\Transformer\Exception\TransformerNotFoundException;
8
use Symfony\Component\Messenger\Envelope;
9
use Symfony\Component\Messenger\Exception\MessageDecodingFailedException;
10
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;
11
12
/**
13
 * @author Radoje Albijanic <[email protected]>
14
 */
15
final class SerializerRouter implements SerializerInterface
16
{
17
    private $happyrSerializer;
18
    private $symfonySerializer;
19
20 8
    public function __construct(SerializerInterface $happyrSerializer, SerializerInterface $symfonySerializer)
21
    {
22 8
        $this->happyrSerializer = $happyrSerializer;
23 8
        $this->symfonySerializer = $symfonySerializer;
24 8
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 8
    public function decode(array $encodedEnvelope): Envelope
30
    {
31 8
        if (empty($encodedEnvelope['body'])) {
32 1
            throw new MessageDecodingFailedException('Encoded envelope should have at least a "body".');
33
        }
34
35 7
        if (null === $envelopeBodyArray = \json_decode($encodedEnvelope['body'], true)) {
36 1
            return $this->symfonySerializer->decode($encodedEnvelope);
37
        }
38
39
        if (
40 6
            array_key_exists('version', $envelopeBodyArray)
41 6
            && array_key_exists('identifier', $envelopeBodyArray)
42 6
            && array_key_exists('timestamp', $envelopeBodyArray)
43 6
            && array_key_exists('payload', $envelopeBodyArray)
44
        ) {
45 1
            return $this->happyrSerializer->decode($encodedEnvelope);
46
        }
47
48 5
        return $this->symfonySerializer->decode($encodedEnvelope);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function encode(Envelope $envelope): array
55
    {
56
        try {
57
            return $this->happyrSerializer->encode($envelope);
58
        } catch (TransformerNotFoundException $e) {
59
            return $this->symfonySerializer->encode($envelope);
60
        }
61
    }
62
}
63