|
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
|
|
|
|