1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yoanm\JsonRpcServer\App\Serialization; |
4
|
|
|
|
5
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcInvalidRequestException; |
6
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcRequest; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class RequestDenormalizer |
10
|
|
|
*/ |
11
|
|
|
class RequestDenormalizer |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
const KEY_JSON_RPC = 'json-rpc'; |
15
|
|
|
const KEY_ID = 'id'; |
16
|
|
|
const KEY_METHOD = 'method'; |
17
|
|
|
const KEY_PARAM_LIST = 'params'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param mixed $item Should be an array or an instance of \stdClass |
21
|
|
|
* |
22
|
|
|
* @return JsonRpcRequest |
23
|
|
|
* |
24
|
|
|
* @throws JsonRpcInvalidRequestException |
25
|
|
|
*/ |
26
|
|
|
public function denormalize($item) : JsonRpcRequest |
27
|
|
|
{ |
28
|
|
|
$this->validateArray($item, 'Item must be an array'); |
29
|
|
|
|
30
|
|
|
// Validate json-rpc and method keys |
31
|
|
|
$this->validateRequiredKey($item, self::KEY_JSON_RPC); |
32
|
|
|
$this->validateRequiredKey($item, self::KEY_METHOD); |
33
|
|
|
|
34
|
|
|
$request = new JsonRpcRequest($item[self::KEY_JSON_RPC], $item[self::KEY_METHOD]); |
35
|
|
|
|
36
|
|
|
/** If no id defined => request is a notification */ |
37
|
|
|
if (isset($item[self::KEY_ID])) { |
38
|
|
|
$request->setId( |
39
|
|
|
$item[self::KEY_ID] == (string) ((int) $item[self::KEY_ID]) |
40
|
|
|
? (int) $item[self::KEY_ID] // Convert it in case it's a string containing an int |
41
|
|
|
: (string) $item[self::KEY_ID] // Convert to string in all other cases |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (isset($item[self::KEY_PARAM_LIST])) { |
46
|
|
|
$paramList = $item[self::KEY_PARAM_LIST]; |
47
|
|
|
$this->validateArray($paramList, 'Parameter list must be an array'); |
48
|
|
|
$request->setParamList($paramList); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $request; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param mixed $value |
56
|
|
|
* @param string $errorDescription |
57
|
|
|
* |
58
|
|
|
* @return array |
59
|
|
|
* |
60
|
|
|
* @throws JsonRpcInvalidRequestException |
61
|
|
|
*/ |
62
|
|
|
private function validateArray($value, string $errorDescription) : array |
63
|
|
|
{ |
64
|
|
|
if (!is_array($value)) { |
65
|
|
|
throw new JsonRpcInvalidRequestException($value, $errorDescription); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $value; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param array $item |
73
|
|
|
* @param string $key |
74
|
|
|
* |
75
|
|
|
* @throws JsonRpcInvalidRequestException |
76
|
|
|
*/ |
77
|
|
|
private function validateRequiredKey(array $item, string $key) |
78
|
|
|
{ |
79
|
|
|
if (!isset($item[$key])) { |
80
|
|
|
throw new JsonRpcInvalidRequestException( |
81
|
|
|
$item, |
82
|
|
|
sprintf('"%s" is a required key', $key) |
83
|
|
|
); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|