-
Notifications
You must be signed in to change notification settings - Fork 3
/
ExtDirectManager.php
364 lines (308 loc) · 9.74 KB
/
ExtDirectManager.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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
<?php
namespace iqria\extdirect;
use yii;
use yii\base\Component;
use yii\web\HttpException;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use iqria\extdirect\exceptions\ExtDirectValidationException;
use iqria\extdirect\exceptions\ResourceConnectionException;
use yii\web\UnauthorizedHttpException;
/**
* Class ExtDirectManager provides Yii2 implementation of Ext.Direct
*
* @author Stanislav Hudkov <[email protected]>
* @version 1.0
* @package iqria\extdirect
*/
class ExtDirectManager extends Component
{
const API_JSON = 'json';
const API_JS = 'js';
/**
* Set of classes that should be accessed directly from client side
* @var array
*/
public $directClasses = [];
/**
* @var string The unique id of the provider (defaults to an auto-assigned id).
* You should assign an id if you need to be able to access the provider later and you do not have an object reference available
*/
public $id = '';
/**
* @var string The url to connect to the Ext.direct.Manager server-side router.
*/
public $url;
/**
* @var string Namespace for the Remoting Provider (defaults to Ext.global).
* Explicitly specify the namespace Object, or specify a String to have a namespace created implicitly.
*/
public $namespace = 'API';
/**
* @var string Object literal defining the server side actions and methods.
*/
public $actions = [];
/**
* @var string API descriptor
*/
public $descriptor = 'API.desc';
/**
* @var bool debug mode
*/
public $debug = false;
/**
* @inheritdoc
*/
public function init()
{
//@todo validate public properties that set up from config before launch
parent::init();
}
/**
* @param array $classList
*/
public function setDirectClasses(array $classList)
{
$this->directClasses = $classList;
}
/**
* @return array
*/
public function getDirectClasses()
{
return $this->directClasses;
}
/**
* Get all controller's actions annotated with '@direct' + default rest actions
* @return array
* @throws \yii\web\HttpException
*/
public function getActionsList()
{
if (!$this->directClasses) {
throw new HttpException(500, 'Please provide direct classes.');
}
$actions = [];
foreach ($this->directClasses as $class) {
$reflection = new \ReflectionClass($class);
$reflectionMethods = $reflection->getMethods();
$className = $reflection->getShortName();
$actionsAnnotated = $this->getAnnotatedActions($className, $reflectionMethods);
$actionsDefault = $this->getDefaultActions($class);
$actions = array_merge($actions, ArrayHelper::merge($actionsDefault, $actionsAnnotated));
}
return $actions;
}
/**
* Get actions annotated with @direct annotation
* @param string $className
* @param array $methods
* @return array
*/
private function getAnnotatedActions($className, array $methods)
{
$annotatedActions = [];
foreach ($methods as $method) {
if (!$method->isPublic()) {
continue;
}
if ($method->isStatic()) {
continue;
}
$actionNameChunks = explode('action', $method->name);
if ($method->name === 'actions' || count($actionNameChunks) !== 2) {
continue;
}
$docBlock = $method->getDocComment();
preg_match('/@direct/', $docBlock, $annotation);
if (!empty($annotation[0])) {
$annotatedActions[$this->getControllerName($className)][] = [
'name' => lcfirst($actionNameChunks[1]),
'len' => $this->getParamsNumber($method)
];
}
}
return $annotatedActions;
}
/**
* Get rest standalone actions
* @param string $class
* @return array
*/
private function getDefaultActions($class)
{
$className = (new \ReflectionClass($class))->getShortName();
$actions = (new $class(lcfirst($className), false))->actions();
$actionsPrepared = [];
foreach ($actions as $name => $action) {
$reflection = new \ReflectionClass($action['class']);
$method = $reflection->getMethod('run');
$actionsPrepared[$this->getControllerName($className)][] = [
'name' => $name,
'len' => $this->getParamsNumber($method)
];
}
return $actionsPrepared;
}
/**
* Get number of parameters
* @param \ReflectionMethod $method
* @return int
*/
private function getParamsNumber($method)
{
return $method->getNumberOfRequiredParameters() ?
$method->getNumberOfRequiredParameters() :
$method->getNumberOfParameters();
}
/**
* Handle which api should be returned
* @param $apiType
* @return string
* @throws \yii\web\HttpException
*/
public function getApi($apiType)
{
if (strcmp($apiType, static::API_JSON) === 0) {
return $this->getApiJson();
} elseif (strcmp($apiType, static::API_JS) === 0) {
return $this->getApiJs();
} else {
throw new HttpException(500, 'Wrong API type.');
}
}
/**
* Get API as array
* @return array
*/
public function getApiArray()
{
$api = [
'url' => $this->getApiUrl(),
'type' => 'remoting',
'namespace' => $this->namespace,
'actions' => $this->getActionsList()
];
if ($this->id) {
$api['id'] = $this->id;
}
return $api;
}
/**
* Get API as javascript
*/
public function getApiJs()
{
$apiJson = $this->getApiJson();
$jsTemplate = <<<JAVASCRIPT
$this->namespace = {};
$this->descriptor = $apiJson;
JAVASCRIPT;
Yii::$app->response->headers->add('Content-Type', 'application/javascript');
return $jsTemplate;
}
/**
* Get API as JSON
* @return string
*/
public function getApiJson()
{
Yii::$app->response->headers->add('Content-Type', 'application/json');
return Json::encode($this->getApiArray());
}
/**
* Get API endpoint
* @return string
*/
public function getApiUrl()
{
return empty($this->url) ? Yii::$app->request->url : $this->url;
}
/**
* Get controller name from class name. Ex: ProductController -> product
* @param $className
* @return string
* @throws \yii\web\HttpException
*/
private function getControllerName($className)
{
$chunks = explode('Controller', $className);
if (count($chunks) === 2) {
return $chunks[0];
}
throw new HttpException(500, 'Invalid controller name.');
}
/**
* Run single action or batch and return result
* @param array $requestBody
* @return array
*/
public function processRequest($requestBody)
{
$response = [];
if (isset($requestBody[0]) && is_array($requestBody[0])) {
foreach ($requestBody as $req) {
$route = $req['action'] . '/' . $req['method'];
$response[] = $this->runAction($route, $req);
}
} else {
$response = $this->runAction($requestBody['action'] . '/' . $requestBody['method'], $requestBody);
}
return $response;
}
/**
* Run single action and return its result
* @param string $route
* @param array $params
* @return array
* @throws yii\web\UnauthorizedHttpException
*/
private function runAction($route, $params)
{
$route = substr(strtolower(preg_replace("/[A-Z]/", '-\\0', $route)), 1);
$response = [
'type' => 'rpc',
'tid' => $params['tid'],
'action' => $params['action'],
'method' => $params['method'],
];
try {
$params = is_null($params['data']) ? [] : $params['data'];
if (isset($params[0]) && is_array($params[0]) && count($params) === 1) {
$params = $params[0];
}
$routeInfo = Yii::$app->createController($route);
$response['result'] = $routeInfo[0]->runAction($routeInfo[1], $params);
} catch (\Exception $e) {
if ($e instanceof HttpException) {
Yii::$app->response->setStatusCode($e->statusCode);
}
if ($e instanceof ExtDirectValidationException) {
$header = false;
$errors = $e->getErrors();
} elseif ($e instanceof UnauthorizedHttpException) {
$errors = $e->getMessage();
$header = 'Login Error';
} elseif ($e instanceof ResourceConnectionException) {
$errors = $e->getMessage();
$header = 'Connection Error';
} else {
$errors = $e->getMessage();
$header = 'Server Error';
}
$response['result'] = [
'success' => false,
'errors' => $header ? [$header => $errors] : $errors
];
if ($this->debug) {
$response['result'] = array_merge($response['result'], [
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'type' => get_class($e),
]);
}
}
return $response;
}
}