forked from prolificinteractive/mabi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.php
378 lines (325 loc) · 11 KB
/
Controller.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<?php
namespace MABI;
include_once __DIR__ . '/App.php';
include_once __DIR__ . '/Inflector.php';
include_once __DIR__ . '/Middleware.php';
class CachedRoute {
public $path;
public $method;
public $httpMethod;
function __construct($path, $method, $httpMethod) {
$this->httpMethod = $httpMethod;
$this->method = $method;
$this->path = $path;
}
}
class CachedControllerConstructor {
public $base;
public $middlewareFiles;
public $documentationName;
function __construct($base, $middlewareFiles, $documentationName) {
$this->base = $base;
$this->documentationName = $documentationName;
$this->middlewareFiles = $middlewareFiles;
}
}
/**
* Defines a controller that serves endpoints routed based on its contained function names.
*
* The controller also allows middleware to be associated with all of the endpoints that it serves.
*/
class Controller {
/**
* The base name for the controller. This defines the first part of the endpoint url.
*
* e.g. <APP_PATH>/{BASE}/{ACTION}/...
*
* @var string
*/
protected $base = NULL;
protected $documentationName = NULL;
/**
* @endpoint ignore
* @return string
*/
public function getBase() {
return $this->base;
}
/**
* @var Extension
*/
protected $extension;
/**
* @var \MABI\Middleware[]
*/
protected $middlewares = array();
/**
* @endpoint ignore
* @return \MABI\App
*/
public function getApp() {
return $this->extension->getApp();
}
/**
* @endpoint ignore
* @return \MABI\Extension
*/
public function getExtension() {
return $this->extension;
}
/**
* @endpoint ignore
* @return array|Middleware[]
*/
public function getMiddlewares() {
return $this->middlewares;
}
public function __construct($extension) {
$this->extension = $extension;
$systemCache = $this->getApp()->getCacheRepository('system');
$cacheKey = get_called_class() . get_class() . '::__construct';
/**
* @var $cache \MABI\CachedControllerConstructor
*/
if($systemCache != null && is_object($cache = $systemCache->get($cacheKey))) {
$this->base = $cache->base;
foreach($cache->middlewareFiles as $middlewareClass => $middlewareFile) {
$this->addMiddlewareByClass($middlewareClass, $middlewareFile);
}
$this->documentationName = $cache->documentationName;
return;
}
if (empty($this->base)) {
$this->base = strtolower(ReflectionHelper::stripClassName(
ReflectionHelper::getPrefixFromControllerClass(get_called_class())));
}
$rClass = new \ReflectionClass(get_called_class());
// Load middlewares from @middleware directive
$middlewareFiles = array();
$middlewares = ReflectionHelper::getDocDirective($rClass->getDocComment(), 'middleware');
foreach ($middlewares as $middlewareClass) {
$middlewareFile = ReflectionHelper::stripClassName($middlewareClass) . '.php';
$this->addMiddlewareByClass($middlewareClass, $middlewareFile);
$middlewareFiles[$middlewareClass] = $middlewareFile;
}
if (empty($this->documentationName)) {
$this->documentationName = ucwords(ReflectionHelper::stripClassName(ReflectionHelper::getPrefixFromControllerClass(get_called_class())));
}
if($systemCache != null) {
$systemCache->forever($cacheKey, new CachedControllerConstructor($this->base, $middlewareFiles, $this->documentationName));
}
}
public function addMiddlewareByClass($middlewareClass, $middlewareFile) {
$this->extension->loadMiddleware($middlewareFile);
/**
* @var $middleware \MABI\Middleware
*/
$middleware = new $middlewareClass();
$this->addMiddleware($middleware);
}
/**
* @param $route \Slim\Route
*/
public function _runControllerMiddlewares($route) {
if (empty($this->middlewares)) {
return;
}
$middleware = reset($this->middlewares);
$middleware->call();
}
/**
* @param $middlewares \MABI\Middleware[]
*/
protected function configureMiddlewares(&$middlewares) {
/**
* @var $prevMiddleware \MABI\Middleware
*/
$prevMiddleware = NULL;
foreach ($middlewares as $currMiddleware) {
if ($prevMiddleware != NULL) {
$prevMiddleware->setNextMiddleware($currMiddleware);
}
$prevMiddleware = $currMiddleware;
$currMiddleware->setController($this);
}
}
public function addMiddleware(Middleware $newMiddleware) {
array_push($this->middlewares, $newMiddleware);
}
/**
* An overridable function that is called before a route executes middleware
*/
public function preMiddleware() {
}
/**
* An overridable function that is called before a route executes the final callable (after middleware)
*/
public function preCallable() {
}
protected function mapRoute(\Slim\Slim $slim, $path, $methodName, $httpMethod, &$cachedRoutes = NULL) {
$slim->map($path,
array($this, 'preMiddleware'),
array($this, '_runControllerMiddlewares'),
array($this, 'preCallable'),
array($this, $methodName))->via($httpMethod);
if (is_array($cachedRoutes)) {
$cachedRoutes[] = new CachedRoute($path, $methodName, $httpMethod);
}
}
/**
* @param $slim \Slim\Slim
*/
public function loadRoutes($slim) {
$this->configureMiddlewares($this->middlewares);
/**
* @var $cachedRoutes CachedRoute[]
*/
$cacheKey = get_called_class() . '.' . get_class() . '::loadRoutes';
if (($systemCache = $this->getApp()->getCacheRepository('system')) != NULL &&
is_array($cachedRoutes = $systemCache->get($cacheKey))
) {
// Get routes from cache
foreach ($cachedRoutes as $cachedRoute) {
$this->mapRoute($slim, $cachedRoute->path, $cachedRoute->method, $cachedRoute->httpMethod);
}
return;
}
else {
$cachedRoutes = array();
}
$rClass = new \ReflectionClass($this);
$rMethods = $rClass->getMethods(\ReflectionMethod::IS_PUBLIC);
$baseMethods = array();
foreach ($rMethods as $rMethod) {
// If there is a '@endpoint ignore' property, the function is not served as an endpoint
if (in_array('ignore', ReflectionHelper::getDocDirective($rMethod->getDocComment(), 'endpoint'))) {
continue;
}
$action = NULL;
$httpMethod = NULL;
$methodName = $rMethod->name;
if (strpos($methodName, 'get', 0) === 0) {
$action = strtolower(substr($methodName, 3));
$httpMethod = \Slim\Http\Request::METHOD_GET;
}
elseif (strpos($methodName, 'put', 0) === 0) {
$action = strtolower(substr($methodName, 3));
$httpMethod = \Slim\Http\Request::METHOD_PUT;
}
elseif (strpos($methodName, 'post', 0) === 0) {
$action = strtolower(substr($methodName, 4));
$httpMethod = \Slim\Http\Request::METHOD_POST;
}
elseif (strpos($methodName, 'delete', 0) === 0) {
$action = strtolower(substr($methodName, 6));
$httpMethod = \Slim\Http\Request::METHOD_DELETE;
}
if (!empty($action)) {
$this->mapRoute($slim, "/{$this->base}/{$action}(/?)", $methodName, $httpMethod, $cachedRoutes);
$this->mapRoute($slim, "/{$this->base}/{$action}(/:param+)(/?)", $methodName, $httpMethod, $cachedRoutes);
}
elseif (!empty($httpMethod)) {
array_push($baseMethods, array(
'name' => $methodName,
'method' => $httpMethod
));
}
}
foreach ($baseMethods as $httpMethod) {
$this->mapRoute($slim, "/{$this->base}(/?)", $httpMethod['name'], $httpMethod['method'], $cachedRoutes);
}
if ($systemCache != NULL) {
$systemCache->forever($cacheKey, $cachedRoutes);
}
}
/**
* Add in parameters specified using @docs-param
*
* @param $rMethod
*
* @return array
*/
protected function getDocParameters(\ReflectionMethod $rMethod) {
$parameters = array();
$docsParameters = ReflectionHelper::getDocDirective($rMethod->getDocComment(), 'docs-param');
foreach ($docsParameters as $docsParameter) {
$paramComponents = explode(' ', $docsParameter, 5);
$parameters[] = array(
'Name' => $paramComponents[0],
'Type' => $paramComponents[1],
'Location' => $paramComponents[2],
'Required' => $paramComponents[3] == 'required' ? 'Y' : 'N',
'Description' => $paramComponents[4]
);
}
return $parameters;
}
/**
* todo: docs
*
* @param Parser $parser
*
* @endpoint ignore
* @return array
*/
public function getDocJSON(Parser $parser) {
$myClass = get_called_class();
$rClass = new \ReflectionClass($myClass);
$this->configureMiddlewares($this->middlewares);
$doc = array();
$doc['name'] = $this->documentationName;
$doc['description'] = $parser->parse(ReflectionHelper::getDocText($rClass->getDocComment()));
// Adding documentation for custom controller actions
$rMethods = $rClass->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($rMethods as $rMethod) {
// If there is a '@endpoint ignore' property, the function is not served as an endpoint
if (in_array('ignore', ReflectionHelper::getDocDirective($rMethod->getDocComment(), 'endpoint'))) {
continue;
}
$methodDoc = array();
$methodDoc['InternalMethodName'] = $rMethod->name;
if (strpos($rMethod->name, 'get', 0) === 0) {
$methodDoc['MethodName'] = substr($rMethod->name, 3);
$methodDoc['HTTPMethod'] = 'GET';
}
elseif (strpos($rMethod->name, 'put', 0) === 0) {
$methodDoc['MethodName'] = substr($rMethod->name, 3);
$methodDoc['HTTPMethod'] = 'PUT';
}
elseif (strpos($rMethod->name, 'post', 0) === 0) {
$methodDoc['MethodName'] = substr($rMethod->name, 4);
$methodDoc['HTTPMethod'] = 'POST';
}
elseif (strpos($rMethod->name, 'delete', 0) === 0) {
$methodDoc['MethodName'] = substr($rMethod->name, 6);
$methodDoc['HTTPMethod'] = 'DELETE';
}
else {
continue;
}
$action = strtolower($methodDoc['MethodName']);
$methodDoc['URI'] = "/{$this->base}" . (empty($action) ? '' : "/{$action}");
$methodDoc['Synopsis'] = $parser->parse(ReflectionHelper::getDocText($rMethod->getDocComment()));
$methodDoc['parameters'] = $this->getDocParameters($rMethod);
if (empty($methodDoc['MethodName'])) {
$methodDoc['MethodName'] = ucwords($this->base);
}
// Allow controller middlewares to modify the documentation for this method
if (!empty($this->middlewares)) {
$middleware = reset($this->middlewares);
$middleware->documentMethod($rClass, $rMethod, $methodDoc);
}
if (!empty($methodDoc)) {
$doc['methods'][] = $methodDoc;
}
}
foreach(ReflectionHelper::getDocDirective($rClass->getDocComment(), 'docs-attach-model') as $includeModelClass) {
/**
* @var $model \MABI\Model
*/
$model = call_user_func($includeModelClass . '::init', $this->getApp());
$doc['models'][] = $model->getDocOutput($parser);
}
return $doc;
}
}