1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Happyr\MessageSerializer; |
6
|
|
|
|
7
|
|
|
use Happyr\MessageSerializer\Hydrator\ArrayToMessageInterface; |
8
|
|
|
use Happyr\MessageSerializer\Hydrator\Exception\HydratorException; |
9
|
|
|
use Happyr\MessageSerializer\Transformer\MessageToArrayInterface; |
10
|
|
|
use Symfony\Component\Messenger\Envelope; |
11
|
|
|
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface; |
12
|
|
|
use Symfony\Component\Messenger\Exception\MessageDecodingFailedException; |
13
|
|
|
use Symfony\Component\Messenger\Stamp\NonSendableStampInterface; |
14
|
|
|
|
15
|
|
|
final class Serializer implements SerializerInterface |
16
|
|
|
{ |
17
|
|
|
private $transformer; |
18
|
|
|
private $hydrator; |
19
|
|
|
|
20
|
2 |
|
public function __construct(MessageToArrayInterface $transformer, ArrayToMessageInterface $hydrator) |
21
|
|
|
{ |
22
|
2 |
|
$this->transformer = $transformer; |
23
|
2 |
|
$this->hydrator = $hydrator; |
24
|
2 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
1 |
|
public function decode(array $encodedEnvelope): Envelope |
30
|
|
|
{ |
31
|
1 |
|
if (empty($encodedEnvelope['body'])) { |
32
|
|
|
throw new MessageDecodingFailedException('Encoded envelope should have at least a "body".'); |
33
|
|
|
} |
34
|
|
|
|
35
|
1 |
|
$array = json_decode($encodedEnvelope['body'], true); |
36
|
|
|
|
37
|
|
|
try { |
38
|
1 |
|
$object = $this->hydrator->toMessage($array); |
39
|
|
|
|
40
|
1 |
|
return $object instanceof Envelope ? $object : new Envelope($object); |
41
|
|
|
} catch (HydratorException $e) { |
42
|
|
|
throw new MessageDecodingFailedException('Failed to decode message', 0, $e); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* {@inheritdoc} |
48
|
|
|
*/ |
49
|
1 |
|
public function encode(Envelope $envelope): array |
50
|
|
|
{ |
51
|
1 |
|
$envelope = $envelope->withoutStampsOfType(NonSendableStampInterface::class); |
52
|
|
|
|
53
|
|
|
return [ |
54
|
1 |
|
'headers' => ['Content-Type' => 'application/json'], |
55
|
1 |
|
'body' => json_encode($this->transformer->toArray($envelope)), |
56
|
|
|
]; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|