|
1
|
|
|
<?php |
|
2
|
|
|
namespace Yoanm\JsonRpcServer\App\Serialization; |
|
3
|
|
|
|
|
4
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcExceptionInterface; |
|
5
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcResponse; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class JsonRpcResponseNormalizer |
|
9
|
|
|
*/ |
|
10
|
|
|
class JsonRpcResponseNormalizer |
|
11
|
|
|
{ |
|
12
|
|
|
const KEY_JSON_RPC = 'jsonrpc'; |
|
13
|
|
|
const KEY_ID = 'id'; |
|
14
|
|
|
const KEY_RESULT = 'result'; |
|
15
|
|
|
const KEY_ERROR = 'error'; |
|
16
|
|
|
|
|
17
|
|
|
const SUB_KEY_ERROR_CODE = 'code'; |
|
18
|
|
|
const SUB_KEY_ERROR_MESSAGE = 'message'; |
|
19
|
|
|
const SUB_KEY_ERROR_DATA = 'data'; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @param JsonRpcResponse $response |
|
23
|
|
|
* |
|
24
|
|
|
* @return array|null |
|
25
|
|
|
*/ |
|
26
|
7 |
|
public function normalize(JsonRpcResponse $response) |
|
27
|
|
|
{ |
|
28
|
|
|
// Notifications must not have a response, even if they are on error |
|
29
|
7 |
|
if ($response->isNotification()) { |
|
30
|
2 |
|
return null; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$data = [ |
|
34
|
5 |
|
self::KEY_JSON_RPC => $response->getJsonRpc(), |
|
35
|
5 |
|
self::KEY_ID => $response->getId() |
|
36
|
|
|
]; |
|
37
|
|
|
|
|
38
|
5 |
|
if ($response->getError()) { |
|
39
|
2 |
|
$data[self::KEY_ERROR] = $this->normalizeError( |
|
40
|
2 |
|
$response->getError() |
|
41
|
|
|
); |
|
42
|
|
|
} else { |
|
43
|
3 |
|
$data[self::KEY_RESULT] = $response->getResult(); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
5 |
|
return $data; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @param JsonRpcExceptionInterface $error |
|
51
|
|
|
* |
|
52
|
|
|
* @return array |
|
53
|
|
|
*/ |
|
54
|
2 |
|
private function normalizeError(JsonRpcExceptionInterface $error) |
|
55
|
|
|
{ |
|
56
|
|
|
$normalizedError = [ |
|
57
|
2 |
|
self::SUB_KEY_ERROR_CODE => $error->getErrorCode(), |
|
58
|
2 |
|
self::SUB_KEY_ERROR_MESSAGE => $error->getErrorMessage() |
|
59
|
|
|
]; |
|
60
|
|
|
|
|
61
|
2 |
|
if ($error->getErrorData()) { |
|
62
|
1 |
|
$normalizedError[self::SUB_KEY_ERROR_DATA] = $error->getErrorData(); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
2 |
|
return $normalizedError; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|