forked from EverexIO/JSON-RPC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON.php
More file actions
272 lines (251 loc) · 7.18 KB
/
JSON.php
File metadata and controls
272 lines (251 loc) · 7.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
<?php
/**
* @package AmiLabs/JSONRPC/RPC
*/
namespace AmiLabs\JSONRPC\RPC\Client;
use BadMethodCallException;
use InvalidArgumentException;
use RuntimeException;
use AmiLabs\JSONRPC\Core\Logger;
use AmiLabs\JSONRPC\Request;
use AmiLabs\JSONRPC\RPC\ClientInterface;
use AmiLabs\JSONRPC\RPC\ClientLayerNet;
/**
* Remote Procedure Call JSON client layer,
* see {@see AmiLabs\JSONRPC\RPC}.
*
* Based on {@see https://github.com/fguillot/JsonRPC}.<br /><br />
* Example:
* <code>
* use AmiLabs\JSONRPC\RPC;
*
* $client = RPC::getLayer('JSON', RPC::TYPE_CLIENT, $options);
* $client->open('someURL');
* $response = $oRPC->execute(
* 'command1',
* array(
* 'param1' => '...',
* // ...
* )
* );
* </code>
*
* @package AmiLabs/JSONRPC/RPC
* @author deepeloper ({@see https://github.com/deepeloper})
*/
class JSON extends ClientLayerNet implements ClientInterface
{
/**
* Version of protocol
*/
const JSON_RPC_VERSION = '2.0';
/**
* Executes remote server method.
*
* @param string $method
* @param array $params
* @param array $options {@see
* \AmiLabs\JSONRPC\Request::__construct()}
* @param bool $resetOptions Flag specifying to reset previous options
* @param string $url Cusrom URL if differs from initialized
* @return mixed
*/
public function execute(
$method,
array $params = NULL,
array $options = array(),
$resetOptions = FALSE,
$url = ''
)
{
$request = $this->prepareRequest($method, $params);
$response = $this->sendRequest($request, $options, $resetOptions, $url);
return $response;
}
/**
* Executes remote server batch.
*
* @param array $batch Array containing arrays:
* [
* 'method' => ...(,
* 'params' => array(,,,))
* ]
* @param array $options {@see
* \AmiLabs\JSONRPC\Request::__construct()}
* @param bool $resetOptions Flag specifying to reset previous options
* @param string $url Cusrom URL if differs from initialized
* @return mixed
*/
public function executeBatch(
array $batch,
array $options = array(),
$resetOptions = FALSE,
$url = ''
)
{
$request = array();
foreach ($batch as $command) {
$params = isset($command['params']) ? $command['params'] : NULL;
$request[] = $this->prepareRequest($command['method'], $params);
}
$response = $this->sendRequest($request, $options, $resetOptions, $url);
return $response;
}
protected function getDefaultOptions()
{
return
array(
CURLOPT_CUSTOMREQUEST => 'POST'
);
}
/**
* Patches response.
*
* @param string &$response
* @return void
*/
protected function patchResponse(&$response)
{
}
/**
* Validates response.
*
* @param string &$response
* @return void
*/
protected function validateResponse($response)
{
if (
isset($response['code']) &&
isset($response['message'])
) {
$this->handleError($response);
}
}
/**
* Prepares request data using calling RPC method and parameters.
*
* @param string $method
* @param array $params
* @return array
*/
protected function prepareRequest($method, array $params = NULL)
{
$request = array(
'jsonrpc' => self::JSON_RPC_VERSION,
'method' => $method,
'id' => mt_rand()
);
if (is_array($params)) {
$request['params'] = $params;
}
return $request;
}
/**
* Sends request to remote server.
*
* @param array $request
* @param array $options
* @param bool $resetOptions Flag specifying to reset previous options
* @param string $url
* @return mixed
*/
protected function sendRequest(
array $request,
array $options = array(),
$resetOptions = FALSE,
$url = ''
)
{
$options['method'] = Request::METHOD_OTHER;
$data = json_encode($request);
$options[CURLOPT_POSTFIELDS] = $data;
$options[CURLOPT_HTTPHEADER] = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
);
$this->logger->write(
sprintf(
"%s sending request to %s:\n%s",
get_class($this),
'' === $url ? $this->url : $url,
print_r($request, TRUE)
)
);
$response = $this->send('', $options, $resetOptions, $url);
$decoded = json_decode($response, TRUE);
if (!is_array($decoded)) {
$message = sprintf(
"%s: invalid response received:\n%s",
get_class($this),
var_export($response, TRUE)
);
$this->logger->write($message, Logger::WARNING);
throw new RuntimeException($message);
}
$this->logger->write(
sprintf(
"%s received response:\n%s",
get_class($this),
print_r($decoded, TRUE)
)
);
$this->validateResponse($decoded);
if (isset($decoded['error'])) {
$this->validateResponse($decoded['error']);
}
$result =
isset($decoded['result'])
? $decoded['result']
: NULL;
return $result;
}
/**
* Throw an exception according the RPC error.
*
* @param array $error
* @return void
* @throws BadMethodCallException
* @throws InvalidArgumentException
* @throws RuntimeException
*/
protected function handleError(array $error)
{
$data = '';
if(isset($error['data'])){
$data .=
'.' .
(
is_string($error['data'])
? ' ' . $error['data']
: "\n" . var_export($error['data'], TRUE)
);
}
$this->logger->write(
sprintf(
"%s: error received:\n%s",
get_class($this),
print_r($error, TRUE)
),
Logger::WARNING
);
if(isset($error['state'])){
$GLOBALS['JSONRPC/State'] = $error['state'];
}
switch ($error['code']) {
case -32601:
throw new BadMethodCallException(
$error['message'] . $data
);
case -32602:
throw new InvalidArgumentException(
$error['message'] . $data
);
default:
throw new RuntimeException(
$error['message'] . $data,
$error['code']
);
}
}
}