1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bankiru\Api\JsonRpc\Adapters\JMS; |
4
|
|
|
|
5
|
|
|
use Bankiru\Api\JsonRpc\Specification\JsonRpcResponse; |
6
|
|
|
use Bankiru\Api\Rpc\Event\ViewEvent; |
7
|
|
|
use JMS\Serializer\SerializationContext; |
8
|
|
|
use JMS\Serializer\Serializer; |
9
|
|
|
use ScayTrase\Api\JsonRpc\JsonRpcRequestInterface; |
10
|
|
|
use ScayTrase\Api\JsonRpc\JsonRpcResponseInterface; |
11
|
|
|
|
12
|
|
|
final class SerializedJsonRpcResponseListener |
13
|
|
|
{ |
14
|
|
|
/** @var Serializer */ |
15
|
|
|
private $serializer; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* SerializedJsonRpcResponseListener constructor. |
19
|
|
|
* |
20
|
|
|
* @param Serializer $serializer |
21
|
|
|
*/ |
22
|
|
|
public function __construct(Serializer $serializer) |
23
|
|
|
{ |
24
|
|
|
$this->serializer = $serializer; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function onPlainResponse(ViewEvent $event) |
28
|
|
|
{ |
29
|
|
|
$request = $event->getRequest(); |
30
|
|
|
$response = $event->getResponse(); |
31
|
|
|
|
32
|
|
|
// No need to perform JSON-RPC serialization here |
33
|
|
|
if (!$request instanceof JsonRpcRequestInterface || $request->isNotification()) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
// Response is already properly formatted |
38
|
|
|
if ($response instanceof JsonRpcResponseInterface) { |
39
|
|
|
return; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$response = new JsonRpcResponse( |
43
|
|
|
$request->getId(), |
44
|
|
|
$this->serializer->toArray( |
45
|
|
|
$event->getResponse(), |
46
|
|
|
$this->createSerializerContext($event) |
47
|
|
|
|
48
|
|
|
) |
49
|
|
|
); |
50
|
|
|
$event->setResponse($response); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param ViewEvent $event |
55
|
|
|
* |
56
|
|
|
* @return SerializationContext |
57
|
|
|
* @throws \LogicException |
58
|
|
|
*/ |
59
|
|
|
private function createSerializerContext(ViewEvent $event) |
60
|
|
|
{ |
61
|
|
|
$context = SerializationContext::create(); |
62
|
|
|
$context->setSerializeNull(true); |
63
|
|
|
$attributes = $event->getRequest()->getAttributes(); |
64
|
|
|
$defaults = $attributes->get('_with_default_context', true); |
65
|
|
|
|
66
|
|
|
if (!$defaults && (false === $attributes->get('_context', false))) { |
67
|
|
|
throw new \LogicException( |
68
|
|
|
'Could not perform object serialization as no default context allowed and no custom set' |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$groups = []; |
73
|
|
|
if ($defaults) { |
74
|
|
|
$groups[] = 'Default'; |
75
|
|
|
} |
76
|
|
|
if (false !== $attributes->get('_context', false)) { |
77
|
|
|
foreach ((array)$attributes->get('_context') as $group) { |
78
|
|
|
$groups[] = $group; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$context->setGroups($groups); |
83
|
|
|
|
84
|
|
|
return $context; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|