1
|
|
|
<?php |
2
|
|
|
namespace Yoanm\JsonRpcServer\Infra\Serialization; |
3
|
|
|
|
4
|
|
|
use Yoanm\JsonRpcServer\App\Serialization\ResponseNormalizer; |
5
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcResponse; |
6
|
|
|
use Yoanm\JsonRpcServer\Infra\RawObject\JsonRpcRawResponse; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class RawResponseSerializer |
10
|
|
|
*/ |
11
|
|
|
class RawResponseSerializer |
12
|
|
|
{ |
13
|
|
|
const KEY_JSON_RPC = 'json-rpc'; |
14
|
|
|
const KEY_ID = 'id'; |
15
|
|
|
const KEY_RESULT = 'result'; |
16
|
|
|
const KEY_ERROR = 'error'; |
17
|
|
|
|
18
|
|
|
const SUB_KEY_ERROR_CODE = 'code'; |
19
|
|
|
const SUB_KEY_ERROR_MESSAGE = 'message'; |
20
|
|
|
const SUB_KEY_ERROR_DATA = 'data'; |
21
|
|
|
|
22
|
|
|
/** @var ResponseNormalizer */ |
23
|
|
|
private $responseNormalizer; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param ResponseNormalizer $responseNormalizer |
27
|
|
|
*/ |
28
|
|
|
public function __construct(ResponseNormalizer $responseNormalizer) |
29
|
|
|
{ |
30
|
|
|
$this->responseNormalizer = $responseNormalizer; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param JsonRpcRawResponse $rawReponse |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
|
|
public function serialize(JsonRpcRawResponse $rawReponse) : string |
39
|
|
|
{ |
40
|
|
|
return $this->encode( |
41
|
|
|
$this->normalize($rawReponse) |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param mixed $normalizedContent |
47
|
|
|
* |
48
|
|
|
* @return string |
49
|
|
|
*/ |
50
|
|
|
public function encode($normalizedContent) : string |
51
|
|
|
{ |
52
|
|
|
return json_encode($normalizedContent); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param JsonRpcRawResponse $rawResponse |
57
|
|
|
* |
58
|
|
|
* @return array|null |
59
|
|
|
*/ |
60
|
|
|
public function normalize(JsonRpcRawResponse $rawResponse) |
61
|
|
|
{ |
62
|
|
|
if ($rawResponse->isBatch()) { |
63
|
|
|
return $this->normalizeBatchResponse($rawResponse->getResponseList()); |
64
|
|
|
} else { |
65
|
|
|
return $this->responseNormalizer->normalize(array_shift($rawResponse->getResponseList())); |
|
|
|
|
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param JsonRpcResponse[] $responseList |
71
|
|
|
* |
72
|
|
|
* @return array|null |
73
|
|
|
*/ |
74
|
|
|
private function normalizeBatchResponse(array $responseList) |
75
|
|
|
{ |
76
|
|
|
$resultList = []; |
77
|
|
|
$hasResult = false; |
78
|
|
|
|
79
|
|
|
foreach ($responseList as $response) { |
80
|
|
|
if ($response->isNotification()) { |
81
|
|
|
continue; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$resultList[] = $this->responseNormalizer->normalize($response); |
85
|
|
|
$hasResult = true; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
if (!$hasResult) { // It was a batch call with only notifications => return null response |
89
|
|
|
return null; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return $resultList; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|