-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathJsonRpcRequest.php
214 lines (188 loc) · 6.5 KB
/
JsonRpcRequest.php
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
<?php
namespace georgique\yii2\jsonrpc;
use georgique\yii2\jsonrpc\exceptions\InvalidRequestException;
use georgique\yii2\jsonrpc\exceptions\JsonRpcException;
use georgique\yii2\jsonrpc\exceptions\InternalErrorException;
use georgique\yii2\jsonrpc\exceptions\InvalidParamsException;
use georgique\yii2\jsonrpc\exceptions\MethodNotFoundException;
use yii\base\InlineAction;
use yii\base\InvalidRouteException;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\Application;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;
/**
* Class JsonRpcRequest
* @author George Shestayev george.shestayev@gmail.com
* @package georgique\yii2\jsonrpc
*/
class JsonRpcRequest extends Model
{
public $id;
public $jsonrpc;
public $method;
public $params = [];
public $paramsPassMethod;
public $parseAsArray;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['jsonrpc', 'method'], 'required'],
['jsonrpc', 'validateJsonRpc'],
['method', 'string'],
['params', 'safe'],
['id', 'validateId', 'skipOnEmpty' => false]
];
}
/**
* Validates request id
* @param $attribute
*/
public function validateId($attribute)
{
$valid = is_null($this->$attribute)
|| is_numeric($this->$attribute)
|| (is_string($this->$attribute) && $this->$attribute !== '');
if (!$valid) {
$this->addError($attribute, 'Invalid ID');
}
}
/**
* Validates "jsonrpc" request param
* @param $attribute
*/
public function validateJsonRpc($attribute)
{
if ($this->$attribute !== '2.0') {
$this->addError($attribute, 'Invalid JsonRPC version');
}
}
/**
* Validates method string and converts it into a route,
* which is going to be parsed by UrlManager before executing
* the request.
* @param $method
* @return bool|string
*/
public function parseMethod($method)
{
if (!preg_match('/^[\d\w_\-.]+$/', $method)) {
return false;
}
$parts = explode('.', $method);
foreach ($parts as $part) {
// There cannot be empty part in route
if (empty($part)) {
return false;
}
}
return implode('/', $parts);
}
/**
* @param $route
* @param array $params
* @throws \ReflectionException
* @throws \yii\base\InvalidConfigException
* @throws InvalidRouteException
*/
public function bindParamsArray($route, array $params)
{
$assocParams = [];
$parts = \Yii::$app->createController($route);
if (!is_array($parts)) {
throw new InvalidRouteException('Unable to resolve request "' . $route . '"');
}
/* @var $controller Controller */
list($controller, $actionID) = $parts;
$action = $controller->createAction($actionID);
if ($action === null) {
throw new InvalidRouteException('Unable to resolve request "' . $route . '" "'. $actionID .'"');
}
if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($controller, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (is_array($params) && !empty($params)) {
$assocParams[$name] = array_shift($params);
}
}
return $assocParams;
}
/**
* Executes JSON-RPC request by route.
* @throws \georgique\yii2\jsonrpc\exceptions\JsonRpcException
* @return mixed
*/
public function execute()
{
/* @var Application $app */
$app = \Yii::$app;
if (!$route = $this->parseMethod($this->method)) {
throw new MethodNotFoundException();
}
try {
// Replacing requested URL, path info and base url
$app->request->setUrl($route);
$app->request->setPathInfo(null);
$app->request->setBaseUrl(null);
try {
$routeWithParams = $app->request->resolve();
} catch (NotFoundHttpException $exception) {
$routeWithParams = false;
}
if (!$routeWithParams) {
throw new MethodNotFoundException();
}
list($routeParsed, $params) = $routeWithParams;
// Replacing route
$app->requestedRoute = $route;
if ($this->paramsPassMethod == Controller::JSON_RPC_PARAMS_PASS_BODY) {
$app->request->setBodyParams($this->params);
$app->request->setRawBody(Json::encode($this->params));
$result = $app->runAction($routeParsed, $params);
} else {
if (ArrayHelper::isAssociative($this->params)) {
$params += $this->params;
} else {
// allow non-named parameters
$params += $this->bindParamsArray($routeParsed, $this->params);
}
if (is_array($params) && !$this->parseAsArray) {
foreach ($params as $key => $value) {
$params[$key] = Json::decode(Json::encode($value), false);
}
}
$result = $app->runAction($routeParsed, $params);
}
} catch (UnauthorizedHttpException $e) {
throw new InvalidRequestException("Unauthorized", [], $e);
} catch (JsonRpcException $e) {
throw $e;
} catch (BadRequestHttpException $e) {
throw new InvalidParamsException('Invalid params', [], $e);
} catch (InvalidRouteException $e) {
throw new MethodNotFoundException('Method not found: ' . $route . '.', [], $e);
} catch (\Throwable $e) {
throw new InternalErrorException('Internal error', [], $e);
}
if (is_null($result)) {
// in case we don't have any response (e.g. notification request)
// we should return nothing
// without this fix json response formatter will return 'null'
\Yii::$app->response->format = Response::FORMAT_RAW;
\Yii::$app->response->data = null;
\Yii::$app->end();
}
return $result;
}
}