-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCubexKernel.php
More file actions
789 lines (714 loc) · 17.2 KB
/
CubexKernel.php
File metadata and controls
789 lines (714 loc) · 17.2 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
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
<?php
namespace Cubex\Kernel;
use Cubex\CubexAwareTrait;
use Cubex\CubexException;
use Cubex\Http\Response as CubexResponse;
use Cubex\ICubexAware;
use Cubex\Responses\Error403Response;
use Cubex\Routing\IRoutable;
use Cubex\Routing\IRoute;
use Cubex\Routing\IRouter;
use Cubex\Routing\Route;
use Illuminate\Contracts\Support\Renderable;
use Packaged\Helpers\Arrays;
use Packaged\Helpers\Objects;
use Packaged\Helpers\Path;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
abstract class CubexKernel
implements HttpKernelInterface, ICubexAware, IRoutable
{
use CubexAwareTrait;
/**
* @var int Level to which routing has automatically processed
*/
protected $_routeLevel = 0;
/**
* @var array params sent through by the constructor
*/
protected $_processParams = [];
/**
* @var bool stop re-initialise of the class
*/
protected $_initialised = false;
/**
* @var array method names which are not allowed through attemptMethod
*/
protected $_restrictedMethods;
/**
* @var string path which has already been processed by previous kernels
*/
protected $_pathProcessed;
/**
* @var Request
*/
protected $_request;
/**
* Initialise a class, stopping multiple calls to init()
*/
final public function init()
{
if(!$this->_initialised)
{
$this->_init();
$this->_initialised = true;
}
}
/**
* Initialise component
*/
protected function _init()
{
}
/**
* Shutdown component
*/
public function shutdown()
{
}
/**
* Get available routes for this object
*
* @return array|null
*/
public function getRoutes()
{
return null;
}
/**
* The default method to run if no route is found
*
* @return null
*/
public function defaultAction()
{
return null;
}
/**
* If no route can be processed, use this route
*
* @return null
*/
public function defaultRoute()
{
return 'defaultAction';
}
/**
* Authentication hook, allowing validation before the router is attempted
* To verify the process can process, return true.
* To reject the request, and return a custom response, simply return the
* desired response
* Any other response will return a standard 403 page to the user
*
* @return bool|Response
*/
public function canProcess()
{
return true;
}
/**
* Handles a Request to convert it to a Response.
* When $catch is true, the implementation must catch all exceptions
* and do its best to convert them to a Response instance.
*
* @param Request $request A Request instance
* @param integer $type The type of the request
* (one of HttpKernelInterface::MASTER_REQUEST
* or HttpKernelInterface::SUB_REQUEST)
* @param Boolean $catch Whether to catch exceptions or not
*
* @return Response A Response instance
* @throws \Exception When an Exception occurs during processing
* @api
*/
public function handle(
Request $request, $type = self::MASTER_REQUEST, $catch = true
)
{
$this->_request = $request;
$calltime = microtime(true);
//Initialise the kernel
$this->init();
try
{
//Check to see if the request is allowed to process
$authed = $this->canProcess();
//If can process returns a response, use that to send back to the user
if($authed instanceof Response)
{
return $this->_sanitizeResponse($authed);
}
else if($authed !== true)
{
return new Error403Response();
}
$response = null;
$route = $this->findRoute($request);
if($route)
{
//Process the route to get the response
$response = $this->executeRoute(
$route,
$request,
$type,
$catch
);
}
if(!($response instanceof Response))
{
throw CubexException::debugException(
"The processed route did not yield a valid response",
404,
$response
);
}
}
catch(\Exception $e)
{
//shutdown the kernel
$this->shutdown();
if($catch)
{
return $this->handleException($e);
}
else
{
throw $e;
}
}
//shutdown the kernel
$this->shutdown();
if($response instanceof CubexResponse)
{
$response->setCallStartTime($calltime);
}
return $response;
}
public function findRoute(Request $request)
{
$path = ltrim($request->getPathInfo(), '/');
if($this->_pathProcessed)
{
$path = ltrim(
preg_replace(
'/^' . preg_quote($this->_pathProcessed, '/') . '/',
'',
$path
),
'/'
);
}
$pathParts = null;
if($path)
{
$pathParts = explode('/', $path);
}
//Get the default router
$router = $this->getCubex()->makeWithCubex('\Cubex\Routing\IRouter');
if(!($router instanceof IRouter))
{
throw new \RuntimeException("No IRouter located");
}
//Tell the router who its working for
$router->setSubject($this);
$route = null;
try
{
$route = $router->process($path);
}
catch(\Exception $e)
{
}
if(!$route)
{
try
{
$route = $router->process(
Path::url($this->_pathProcessed, $path)
);
$this->_pathProcessed = null;
}
catch(\Exception $e)
{
}
}
if((!$route) && $pathParts)
{
$route = $this->autoRoute($request, $pathParts);
}
if(!$route)
{
$route = Route::create($this->defaultRoute(), $this->_processParams);
}
return $route;
}
public function autoRoute(Request $request, $pathParts)
{
// check auto-routing
$method = $this->attemptMethod(head($pathParts), $request);
if($method)
{
// remove path upto and including $method
return Route::create($method, array_slice($pathParts, 1));
}
// sub routing
$classPath = ucfirst(head($pathParts));
$classPath = ucwords(str_replace(['-', '_'], ' ', $classPath));
$classPath = str_replace(' ', '', $classPath);
$namespace = Objects::getNamespace(static::class);
$subRoutes = $this->subRouteTo();
//No subroutes available
if($subRoutes !== null && !empty($subRoutes))
{
foreach($subRoutes as $subRoute)
{
//Half sprintf style, but changed to str_replace for multiple instances
$attempt = Path::windows(
$namespace,
str_replace('%s', $classPath, $subRoute)
);
if(class_exists($attempt))
{
return Route::create(
$attempt,
array_slice($pathParts, 1),
head($pathParts)
);
}
}
}
return null;
}
/**
* Execute a route and attempt to generate a response
*
* @param IRoute $route
* @param Request $request
* @param int $type
* @param bool $catch
*
* @return CubexResponse|null|Response
* @throws \Exception
*/
public function executeRoute(
IRoute $route, Request $request, $type = self::MASTER_REQUEST,
$catch = true
)
{
$value = $route->getValue();
$this->_processParams = $params = $route->getRouteData();
//If the action has returned a valid response, lets send that back
if($value instanceof Response)
{
return $value;
}
//Attempt to see if the route is a callable
if(is_callable($value))
{
$value = $this->_getCallableResult($value, $params);
}
else if(is_scalar($value))
{
//If is fully qualified class, create class
$match = '/^(\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/';
if(stripos($value, '\\') !== false && preg_match($match, $value))
{
$class = $value;
$nsClass = Path::windows(Objects::getNamespace($this), $value);
try
{
if(class_exists($nsClass))
{
$value = $this->getCubex()->make($nsClass);
}
else
{
$value = $this->getCubex()->make($class);
}
}
catch(\Exception $e)
{
if(!$catch)
{
throw new \RuntimeException(
"Your route provides an invalid class '$class'"
);
}
else
{
return null;
}
}
}
else
{
$call = $this->attemptCallable($value);
if($call !== null)
{
$value = $this->_getCallableResult($call, $params);
}
else
{
//Attempt to see if the route is a redirect
$url = $this->attemptUrl($value, $request);
if($url !== null)
{
//Redirect to url
return new RedirectResponse($url['url'], $url['code']);
}
else
{
//look for method names
$method = $this->attemptMethod($value, $request);
if($method !== null)
{
$value = $this->_getCallableResult([$this, $method], $params);
}
}
}
}
}
if($value instanceof CubexKernel)
{
$value->_pathProcessed = Path::url(
$this->_pathProcessed,
$route->getMatchedPath()
);
$value->_processParams = $params;
}
return $this->_processResponse($value, $request, $type, $catch, $params);
}
/**
* Process the response from the route
*
* @param $value
* @param Request $request
* @param int $type
* @param bool $catch
* @param array $params
*
* @return CubexResponse|null|Response
*/
protected function _processResponse(
$value, Request $request, $type = self::MASTER_REQUEST, $catch = true,
$params = []
)
{
$value = $this->_sanitizeResponse($value);
if(!is_array($params))
{
$params = [];
}
if($value instanceof Response)
{
return $value;
}
if($value instanceof CubexKernel)
{
$value->_processParams = $params;
}
//Support for nested kernels, e.g. project > application > controller
if($value instanceof HttpKernelInterface)
{
return $value->handle($request, $type, $catch);
}
if($value instanceof Renderable)
{
return new CubexResponse($value);
}
if(is_object($value))
{
return new CubexResponse($value);
}
return null;
}
/**
* Execute a method, and convert the response or output into a response
*
* @param $method
* @param null|array $params Parameters to send into the method
*
* @return \Cubex\Http\Response|null
* @throws \Exception
*/
protected function _getCallableResult($method, $params = null)
{
ob_start();
try
{
if($params === null)
{
$response = $method();
}
else
{
$response = call_user_func_array($method, array_values($params));
}
}
catch(\Exception $e)
{
ob_get_clean();
throw $e;
}
return $this->handleResponse($response, ob_get_clean());
}
/**
* Attempt to convert a string to a callable
*
* @param $routeValue
*
* @return callable|null
*/
public function attemptCallable($routeValue)
{
if(stristr($routeValue, ','))
{
$routeValue = explode(',', $routeValue);
}
else if(stristr($routeValue, '@'))
{
$routeValue = explode('@', $routeValue);
}
if(is_callable($routeValue))
{
return $routeValue;
}
return null;
}
/**
* Search the current class for a matching method
*
* @param $routeValue
* @param Request $request
*
* @return null
*/
public function attemptMethod($routeValue, Request $request)
{
$method = trim($routeValue);
$callMethod = ucwords(str_replace(['-', '_'], ' ', $method));
$callMethod = str_replace(' ', '', $callMethod);
$attempts = [];
//If a specific underscored method has been requested, we should attempt it
if(stristr($method, '_'))
{
$attempts[] = $method;
}
//Handle Ajax Requests
if($request->isXmlHttpRequest())
{
$attempts[] = 'ajax' . $callMethod;
}
//Support all HTTP Verbs
$attempts[] = strtolower($request->getMethod()) . $callMethod;
$attempts[] = 'render' . $callMethod;
$attempts[] = 'action' . $callMethod;
$attempts[] = lcfirst($callMethod);
foreach($attempts as $attempt)
{
if($this->_isMethodRestricted($attempt))
{
continue;
}
try
{
//Ensure the method is public
$method = new \ReflectionMethod($this, $attempt);
if($method->isPublic())
{
return $attempt;
}
}
catch(\Exception $e)
{
}
}
return null;
}
/**
* Check to see if a method has been restricted for execution
*
* @param $method
*
* @return bool
*/
protected function _isMethodRestricted($method)
{
if($this->_restrictedMethods === null)
{
$this->_restrictedMethods = [
'init',
'shutdown',
'getRoutes',
'canProcess',
'handle',
'executeRoute',
'attemptCallable',
'attemptMethod',
'attemptUrl',
'handleResponse',
'autoRoute',
'attemptSubClass',
'getConfigItem',
'subRouteTo',
'bindCubex',
'setCubex',
'getCubex',
'isCubexAvailable',
];
}
//Do not allow methods listed within the restricted methods array
return in_array($method, $this->_restrictedMethods);
}
/**
* Check the route for a redirect rule
*
* @param $routeValue
* @param Request $request
*
* @return array|null
*/
public function attemptUrl($routeValue, Request $request = null)
{
//Match full urls, status code and urls, and relative urls.
if(preg_match('/^(.*tps?:\/\/|\/|#@|@[0-9]{3}\!)/', $routeValue))
{
//If specified, use the http code provided e.g. @301!http://google.com
if(substr($routeValue, 0, 1) == '@')
{
list($code, $url) = sscanf($routeValue, "@%d!%s");
return ['code' => $code, 'url' => $url];
}
else if(substr($routeValue, 0, 2) == '#@')
{
//Starting a url with #@ implies a redirect. Useful for redirecting
if($request !== null && substr($request->getPathInfo(), -1) == '/')
{
//If there is a leading slash, make sure you put them up a directory
$routeValue = '../' . substr($routeValue, 2);
}
else
{
//to relative urls e.g. /homepage or about
$routeValue = substr($routeValue, 2);
}
}
return ['code' => 302, 'url' => $routeValue];
}
return null;
}
/**
* Handle the response from a method or callable
*
* @param $response
* @param $capturedOutput
*
* @return CubexResponse|null
*/
public function handleResponse($response, $capturedOutput)
{
if(is_object($response))
{
return $response;
}
if($response !== null)
{
return new CubexResponse($response);
}
if(!empty($capturedOutput))
{
return new CubexResponse($capturedOutput);
}
return null;
}
/**
* Generate a response for Exceptions
*
* @param \Exception $exception
*
* @return CubexResponse|mixed
*/
public function handleException(\Exception $exception)
{
if($exception->getCode() == 404)
{
return $this->getCubex()->make('404');
}
else
{
return $this->getCubex()->exceptionResponse($exception);
}
}
protected function _sanitizeResponse($value)
{
if($value instanceof ICubexAware)
{
$value->setCubex($this->getCubex());
}
return $value;
}
/**
* Retrieve the Cubex request object
*
* @return \Cubex\Http\Request
*/
protected function _getRequest()
{
return $this->_request ?: $this->getCubex()->make('request');
}
/**
* Retrieve a cubex configuration item
*
* @param $section
* @param $item
* @param null $default
*
* @return mixed
*/
public function getConfigItem($section, $item, $default = null)
{
return $this->getCubex()->getConfiguration()->getItem(
$section,
$item,
$default
);
}
/**
* Return an array of sub classes to attempt to route to, using %s as a
* replacement for the current route part
*
* @return null|string[]
*/
public function subRouteTo()
{
return null;
}
/**
* Set the cubex instance on an object to the current instance
*
* @param ICubexAware $instance
*
* @return ICubexAware
* @throws \RuntimeException
*/
public function bindCubex(ICubexAware $instance)
{
$instance->setCubex($this->getCubex());
return $instance;
}
protected function _getRouteData($key = null, $default = null)
{
if($key === null)
{
return $this->_processParams;
}
// Since Arrays Value requires an array,we can break out early
if(!is_array($this->_processParams))
{
return $this->_processParams ?? $default;
}
return Arrays::value($this->_processParams, $key, $default);
}
}