|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace OldSound\RabbitMqBundle\Serializer; |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
use OldSound\RabbitMqBundle\RabbitMq\Exception\RpcResponseException; |
|
8
|
|
|
use OldSound\RabbitMqBundle\RabbitMq\RpcReponse; |
|
9
|
|
|
use Symfony\Component\Serializer\Serializer; |
|
10
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
|
11
|
|
|
|
|
12
|
|
|
class JsonMessageBodySerializer implements MessageBodySerializerInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** @var SerializerInterface */ |
|
15
|
|
|
private $serializer; |
|
16
|
|
|
/** @var string|null */ |
|
17
|
|
|
private $deserializeType; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(string $deserializeType = null, SerializerInterface $serializer = null) |
|
20
|
|
|
{ |
|
21
|
|
|
if ($this->deserializeType && !$this->serializer) { |
|
22
|
|
|
throw new \InvalidArgumentException('serializer is required if deserializerType specified'); |
|
23
|
|
|
} |
|
24
|
|
|
$this->deserializeType = $deserializeType; |
|
25
|
|
|
$this->serializer = $serializer; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function serialize($body): string |
|
29
|
|
|
{ |
|
30
|
|
|
if ($body instanceof RpcResponseException) { |
|
31
|
|
|
return json_encode([ |
|
32
|
|
|
'error_code' => $body->getCode(), |
|
33
|
|
|
'message' => $body->getMessage(), |
|
34
|
|
|
]); |
|
35
|
|
|
} |
|
36
|
|
|
return json_encode($body);// $this->serializer->serialize($body, 'json'); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function deserialize(string $body) |
|
40
|
|
|
{ |
|
41
|
|
|
$data = json_decode($body, true); |
|
42
|
|
|
if (isset($data['error_code'])) { |
|
43
|
|
|
return new RpcResponseException(new RpcResponseException($data['message'], $data['error_code'])); |
|
44
|
|
|
} else if ($this->deserializeType) { |
|
45
|
|
|
return $this->serializer->deserialize($body, $this->deserializeType, 'json'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
|
|
49
|
|
|
return $data; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
} |