-
Notifications
You must be signed in to change notification settings - Fork 1
/
Action.php
228 lines (188 loc) · 7.3 KB
/
Action.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?php
/**
* JSON-RPC controller action class file
* @author Eugene Khorev <eugene.khorev@gmail.com>
*/
namespace jsonrpc;
use Yii;
use yii\helpers\ArrayHelper;
use jsonrpc\RequestModel;
/**
* JSON-RPC controller action
*/
class Action extends \yii\base\Action
{
public $scenario = 'rpc';
/**
* @inheritdoc
*/
public function run()
{
$responseArray = [];
try {
\Yii::trace('Running JSON-RPC 2.0 request', 'jsonrpc\Action::run');
$requestArray = $this->getRequestArray();
foreach ($requestArray as $requestData) {
$responseArray[] = $this->processRequest($requestData);
}
} catch (ValidationException $ex) {
$responseArray[] = ['jsonrpc' => '2.0',
'error' => [
'code' => $ex->getCode(),
'message' => $ex->getMessage(),
'data' => $ex->getData(),
],
];
} catch (\Exception $ex) {
$responseData = ['jsonrpc' => '2.0',
'error' => [
'code' => $ex->getCode(),
'message' => $ex->getMessage(),
],
];
if ($ex instanceof ValidationException) {
$responseData['data'] = $ex->getData();
} else {
$responseData['data'] = YII_DEBUG ? $ex->getTraceAsString() : null;
}
$responseArray[] = $responseData;
}
return count($responseArray) === 1 ? reset($responseArray) : $responseArray;
}
/**
* Parses POST data into array of JSON-PRC batch requests
* @return array
* @throws \yii\web\BadRequestHttpException
*/
protected function getRequestArray()
{
$requestArray = Yii::$app->request->getBodyParams();
if (!is_array($requestArray)) {
throw new \yii\web\BadRequestHttpException('Invalid JSON-RPC request.');
}
if (!ArrayHelper::isIndexed($requestArray)) {
$requestArray = array($requestArray);
}
return $requestArray;
}
/**
* Validates JSON-RPC request, initializes controller action parameters and runs the action
* @param array $requestData
* @return array Controller action response
*/
protected function processRequest($requestData)
{
$responseData = ['jsonrpc' => '2.0'];
try {
$method = ArrayHelper::getValue($requestData, 'method', '-');
\Yii::trace('Running JSON-RPC 2.0 method: ' . $method, 'jsonrpc\Action::processRequest');
\Yii::beginProfile('jsonrpc.controller.rpc.' . $method);
$requestModel = $this->getRequestModel($requestData);
$responseData['id'] = $requestModel->id;
$reflectionMethod = $this->getControllerMethod($requestModel->method);
$methodParams = $this->getMethodParams($reflectionMethod, $requestModel->params);
$responseData['result'] = $this->runControllerAction($reflectionMethod->getName(), $methodParams);
\Yii::endProfile('jsonrpc.controller.rpc.' . ArrayHelper::getValue($requestData, 'method', '-'));
} catch (\Exception $ex) {
unset($responseData['result']);
$responseData['error'] = [
'code' => $ex->getCode(),
'message' => $ex->getMessage(),
'data' => ($ex instanceof ValidationException)
? $ex->getData()
: null,
];
}
return $responseData;
}
/**
* Creates and validates JSON-RPC request model
* @param array $requestData
* @return RequestModel
* @throws \yii\web\BadRequestHttpException
*/
protected function getRequestModel($requestData)
{
$requestModel = new RequestModel();
$requestModel->attributes = $requestData;
if (!$requestModel->validate()) {
throw new ValidationException('Invalid JSON-RPC request parameters.', 0, $requestModel->getErrors());
}
return $requestModel;
}
/**
* Returns controller action method for specified JSON-RPC request method
* @param string $requestedMethod
* @return \ReflectionMethod
* @throws \yii\web\NotFoundHttpException
*/
protected function getControllerMethod($requestedMethod)
{
$methodName = 'rpc' . str_replace(' ', '', ucwords(implode(' ', explode('-', $requestedMethod))));
if (!method_exists($this->controller, $methodName)) {
throw new \yii\web\NotFoundHttpException("Not found JSON-RPC method {$requestedMethod}.");
}
$method = new \ReflectionMethod($this->controller, $methodName);
if (!$method->isPublic() || $method->getName() !== $methodName) {
throw new \yii\web\NotFoundHttpException("Not found JSON-RPC method {$requestedMethod}.");
}
return $method;
}
/**
* Creates and initializes array of controller action method arguments
* @param \ReflectionMethod $reflectionMethod
* @param array $requestParams
* @return array
* @throws \yii\web\BadRequestHttpException
*/
protected function getMethodParams(\ReflectionMethod $reflectionMethod, $requestParams)
{
$actionParams = [];
$methodParams = $reflectionMethod->getParameters();
foreach ($methodParams as $param) {
$paramName = $param->getName();
if (!array_key_exists($paramName, $requestParams)) {
throw new \yii\web\BadRequestHttpException("Not found JSON-RPC request parameter '{$paramName}'.");
}
$paramClass = $param->getClass();
$actionParams[$paramName] = !empty($paramClass) ? $this->getParameterModel($paramName, $paramClass->name, $requestParams) : $requestParams[$paramName];
}
return $actionParams;
}
/**
* Executes controller action method
* @param string $methodName
* @param array $methodParams
* @return mixed
*/
protected function runControllerAction($methodName, $methodParams)
{
return call_user_func_array([$this->controller, $methodName], $methodParams);
}
/**
* Creates and validates model for controller action argument
* @param string $paramName
* @param string $modelClassName
* @param array $requestParams
* @return \yii\base\Model
* @throws \yii\base\InvalidParamException
* @throws \yii\web\BadRequestHttpException
*/
protected function getParameterModel($paramName, $modelClassName, $requestParams)
{
$paramModel = new $modelClassName;
if (!$paramModel instanceof \yii\base\Model) {
throw new \yii\base\InvalidParamException("Parameter '{$paramName}' must be instance of \yii\base\Model");
}
if (in_array($this->scenario, $paramModel->scenarios())) {
$paramModel->scenario = $this->scenario;
$paramModel->setAttributes($requestParams[$paramName], true);
} else {
$paramModel->setAttributes($requestParams[$paramName], false);
}
if (!$paramModel->validate()) {
throw new ValidationException('Invalid JSON-RPC request parameters.', 0, $paramModel->getErrors());
}
return $paramModel;
}
}