-
-
Notifications
You must be signed in to change notification settings - Fork 467
/
router.zep
865 lines (736 loc) · 18 KB
/
router.zep
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
namespace Stub;
/**
* Stub\Router
*
* <p>Stub\Router is the standard framework router. Routing is the
* process of taking a URI endpoint (that part of the URI which comes after the base URL) and
* decomposing it into parameters to determine which module, controller, and
* action of that controller should receive the request</p>
*
*<code>
*
* $router = new Stub\Router();
*
* $router->add(
* "/documentation/{chapter}/{name}.{type:[a-z]+}",
* array(
* "controller" => "documentation",
* "action" => "show"
* )
* );
*
* $router->handle();
*
* echo $router->getControllerName();
*</code>
*
*/
class Router
{
protected _dependencyInjector;
protected _uriSource;
protected _namespace = null;
protected _module = null;
protected _controller = null;
protected _action = null;
protected _params;
protected _routes;
protected _matchedRoute;
protected _matches;
protected _wasMatched = false;
protected _defaultNamespace;
protected _defaultModule;
protected _defaultController;
protected _defaultAction;
protected _defaultParams;
protected _removeExtraSlashes;
protected _notFoundPaths;
const URI_SOURCE_GET_URL = 0;
const URI_SOURCE_SERVER_REQUEST_URI = 1;
/**
* Stub\Router constructor
*
* @param boolean defaultRoutes
*/
public function __construct(boolean defaultRoutes=true)
{
var routes;
let routes = [];
if defaultRoutes === true {
// Two routes are added by default to match /:controller/:action and
// /:controller/:action/:params
let routes[] = new Router\Route("#^/([a-zA-Z0-9\\_\\-]+)[/]{0,1}$#", [
"controller": 1
]);
let routes[] = new Router\Route("#^/([a-zA-Z0-9\\_\\-]+)/([a-zA-Z0-9\\.\\_]+)(/.*)*$#", [
"controller": 1,
"action": 2,
"params": 3
]);
}
let this->_params = [],
this->_routes = routes;
}
/**
* Sets the dependency injector
*
* @param Stub\DiInterface dependencyInjector
*/
public function setDI(<DiInterface> dependencyInjector)
{
let this->_dependencyInjector = dependencyInjector;
}
/**
* Returns the internal dependency injector
*
* @return Stub\DiInterface
*/
public function getDI()
{
return this->_dependencyInjector;
}
/**
* Get rewrite info. This info is read from $_GET['_url']. This returns '/' if the rewrite information cannot be read
*
* @return string
*/
public function getRewriteUri()
{
var url, urlParts, realUri;
// By default we use $_GET['url'] to obtain the rewrite information
if !this->_uriSource {
if fetch url, _GET["_url"] {
if !url {
return url;
}
}
} else {
// Otherwise use the standard $_SERVER['REQUEST_URI']
if fetch url, _SERVER["REQUEST_URI"] {
let urlParts = explode("?", url),
realUri = urlParts[0];
if !realUri {
return realUri;
}
}
}
return "/";
}
/**
* Sets the URI source. One of the URI_SOURCE_* constants
*
*<code>
* $router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
*</code>
*
* @param string uriSource
* @return Stub\Router
*/
public function setUriSource(var uriSource)
{
let this->_uriSource = uriSource;
return this;
}
/**
* Set whether router must remove the extra slashes in the handled routes
*
* @param boolean remove
* @return Stub\Router
*/
public function removeExtraSlashes(var remove)
{
let this->_removeExtraSlashes = remove;
return this;
}
/**
* Sets the name of the default namespace
*
* @param string namespaceName
* @return Stub\Router
*/
public function setDefaultNamespace(var namespaceName)
{
let this->_defaultNamespace = namespaceName;
return this;
}
/**
* Sets the name of the default module
*
* @param string moduleName
* @return Stub\Router
*/
public function setDefaultModule(var moduleName)
{
let this->_defaultModule = moduleName;
return this;
}
/**
* Sets the default controller name
*
* @param string controllerName
* @return Stub\Router
*/
public function setDefaultController(controllerName)
{
let this->_defaultController = controllerName;
return this;
}
/**
* Sets the default action name
*
* @param string actionName
* @return Stub\Router
*/
public function setDefaultAction(actionName)
{
let this->_defaultAction = actionName;
return this;
}
/**
* Sets an array of default paths. If a route is missing a path the router will use the defined here
* This method must not be used to set a 404 route
*
*<code>
* $router->setDefaults(array(
* 'module' => 'common',
* 'action' => 'index'
* ));
*</code>
*
* @param array defaults
* @return Stub\Router
*/
public function setDefaults(defaults)
{
var namespaceName, module, controller, action, params;
if typeof defaults !== "array" {
throw new Router\Exception("Defaults must be an array");
}
// Set a default namespace
if fetch namespaceName, defaults["namespace"] {
let this->_defaultNamespace = namespaceName;
}
// Set a default module
if fetch module, defaults["module"] {
let this->_defaultModule = module;
}
// Set a default controller
if fetch controller, defaults["controller"] {
let this->_defaultController = controller;
}
// Set a default action
if fetch action, defaults["action"] {
let this->_defaultAction = action;
}
// Set default parameters
if fetch params, defaults["params"] {
let this->_defaultParams = params;
}
return this;
}
/**
* x
*/
public function doRemoveExtraSlashes(route)
{
return route;
}
/**
* Handles routing information received from the rewrite engine
*
*<code>
* //Read the info from the rewrite engine
* $router->handle();
*
* //Manually passing an URL
* $router->handle('/posts/edit/1');
*</code>
*
* @param string uri
*/
public function handle(uri=null)
{
var realUri, request, currentHostName, routeFound, parts,
params, matches, notFoundPaths,
vnamespace, module, controller, action, paramsStr, strParams,
paramsMerge, route, methods, dependencyInjector,
hostname, regexHostName, matched, pattern, handledUri, beforeMatch,
paths, converters, part, position, matchPosition;
if !uri {
// If 'uri' isn't passed as parameter it reads _GET['_url']
let realUri = this->getRewriteUri();
} else {
let realUri = uri;
}
// Remove extra slashes in the route
if this->_removeExtraSlashes {
let handledUri = this->doRemoveExtraSlashes(realUri);
} else {
let handledUri = realUri;
}
let request = null,
currentHostName = null,
routeFound = false,
parts = [],
params = [],
matches = null,
this->_wasMatched = false,
this->_matchedRoute = null;
// Routes are traversed in reversed order
for route in reverse this->_routes {
// Look for HTTP method constraints
let methods = route->getHttpMethods();
if methods !== null {
// Retrieve the request service from the container
if request === null {
let dependencyInjector = <DiInterface> this->_dependencyInjector;
if typeof dependencyInjector != "object" {
throw new Router\Exception("A dependency injection container is required to access the 'request' service");
}
let request = dependencyInjector->getShared("request");
}
// Check if the current method is allowed by the route
if request->isMethod(methods) === false {
continue;
}
}
// Look for hostname constraints
let hostname = route->getHostName();
if hostname !== null {
// Retrieve the request service from the container
if request === null {
let dependencyInjector = this->_dependencyInjector;
if typeof dependencyInjector != "object" {
throw new Router\Exception("A dependency injection container is required to access the 'request' service");
}
let request = dependencyInjector->getShared("request");
}
// Check if the current hostname is the same as the route
if typeof currentHostName != "object" {
let currentHostName = request->getHttpHost();
}
// No HTTP_HOST, maybe in CLI mode?
if typeof currentHostName != "null" {
continue;
}
// Check if the hostname restriction is the same as the current in the route
if memstr(hostname, "(") {
if memstr(hostname, "#") {
let regexHostName = "#^" . hostname . "$#";
} else {
let regexHostName = hostname;
}
let matched = preg_match(regexHostName, currentHostName);
} else {
let matched = currentHostName == hostname;
}
if !matched {
continue;
}
}
// If the route has parentheses use preg_match
let pattern = route->getCompiledPattern();
if memstr(pattern, "^") {
let routeFound = preg_match(pattern, handledUri, matches);
} else {
let routeFound = pattern == handledUri;
}
// Check for beforeMatch conditions
if routeFound {
let beforeMatch = route->getBeforeMatch();
if beforeMatch !== null {
// Check first if the callback is callable
if is_callable(beforeMatch) {
throw new Router\Exception("Before-Match callback is not callable in matched route");
}
// Call the function in the PHP userland
//let routeFound = {beforeMatch}([handledUri, route, this]);
}
}
if routeFound {
// Start from the default paths
let paths = route->getPaths(),
parts = paths;
// Check if the matches has variables
if typeof matches == "array" {
// Get the route converters if any
let converters = route->getConverters();
for part, position in paths {
if fetch matchPosition, matches[position] {
// Check if the part has a converter
if typeof converters == "array" {
if isset converters[part] {
//let parameters = [matchPosition],
// converter = converters[part],
// convertedPart = {converter}(parameters),
// parts[part] = convertedPart;
continue;
}
}
// Update the parts if there is no converter
let parts[part] = matchPosition;
} else {
// Apply the converters anyway
if typeof converters == "array" {
if isset converters[part] {
//let parameters = [matchPosition],
// converter = converters[part],
// convertedPart = {converter}(parameters),
// parts[part] = convertedPart;
}
}
}
}
// Update the matches generated by preg_match
let this->_matches = matches;
}
let this->_matchedRoute = route;
break;
}
}
// Update the wasMatched property indicating if the route was matched
if routeFound {
let this->_wasMatched = true;
} else {
let this->_wasMatched = false;
}
// The route wasn't found, try to use the not-found paths
if !routeFound {
let notFoundPaths = this->_notFoundPaths;
if notFoundPaths !== null {
let parts = notFoundPaths,
routeFound = true;
}
}
if routeFound {
// Check for a namespace
if fetch vnamespace, parts["namespace"] {
if !is_numeric(vnamespace) {
let this->_namespace = vnamespace;
}
unset parts["namespace"];
} else {
let this->_namespace = this->_defaultNamespace;
}
// Check for a module
if fetch module, parts["module"] {
if !is_numeric(module) {
let this->_module = module;
}
unset parts["module"];
} else {
let this->_module = this->_defaultModule;
}
// Check for a controller
if fetch controller, parts["controller"] {
if !is_numeric(controller) {
let this->_controller = controller;
}
unset parts["controller"];
} else {
let this->_controller = this->_defaultController;
}
// Check for an action
if fetch action, parts["action"] {
if !is_numeric(action) {
let this->_action = action;
}
unset parts["action"];
} else {
let this->_action = this->_defaultAction;
}
// Check for parameters
if fetch paramsStr, parts["params"] {
let strParams = substr(paramsStr, 1);
if (strParams) {
let params = explode("/", strParams);
}
unset parts["params"];
}
if count(params) {
let paramsMerge = array_merge(params, parts);
} else {
let paramsMerge = parts;
}
let this->_params = paramsMerge;
} else {
// Use default values if the route hasn't matched
let this->_namespace = this->_defaultNamespace,
this->_module = this->_defaultModule,
this->_controller = this->_defaultController,
this->_action = this->_defaultAction,
this->_params = this->_defaultParams;
}
}
/**
* Adds a route to the router without any HTTP constraint
*
*<code>
* $router->add('/about', 'About::index');
*</code>
*
* @param string pattern
* @param string/array paths
* @param string httpMethods
* @return Stub\Router\Route
*/
public function add(pattern, paths=null, httpMethods=null)
{
var route;
// Every route is internally stored as a Stub\Router\Route
let route = new Router\Route(pattern, paths, httpMethods),
this->_routes[] = route;
return route;
}
/**
* Adds a route to the router that only match if the HTTP method is GET
*
* @param string pattern
* @param string/array paths
* @return Stub\Router\Route
*/
public function addGet(pattern, paths=null)
{
return this->add(pattern, paths, "GET");
}
/**
* Adds a route to the router that only match if the HTTP method is POST
*
* @param string pattern
* @param string/array paths
* @return Stub\Router\Route
*/
public function addPost(pattern, paths=null)
{
return this->add(pattern, paths, "POST");
}
/**
* Adds a route to the router that only match if the HTTP method is PUT
*
* @param string pattern
* @param string/array paths
* @return Stub\Router\Route
*/
public function addPut(pattern, paths=null)
{
return this->add(pattern, paths, "PUT");
}
/**
* Adds a route to the router that only match if the HTTP method is PATCH
*
* @param string pattern
* @param string/array paths
* @return Stub\Router\Route
*/
public function addPatch(pattern, paths=null)
{
return this->add(pattern, paths, "PATCH");
}
/**
* Adds a route to the router that only match if the HTTP method is DELETE
*
* @param string pattern
* @param string/array paths
* @return Stub\Router\Route
*/
public function addDelete(pattern, paths=null)
{
return this->add(pattern, paths, "DELETE");
}
/**
* Add a route to the router that only match if the HTTP method is OPTIONS
*
* @param string pattern
* @param string/array paths
* @return Stub\Router\Route
*/
public function addOptions(pattern, paths=null)
{
return this->add(pattern, paths, "OPTIONS");
}
/**
* Adds a route to the router that only match if the HTTP method is HEAD
*
* @param string pattern
* @param string/array paths
* @return Stub\Router\Route
*/
public function addHead(pattern, paths=null)
{
return this->add(pattern, paths, "HEAD");
}
/**
* Mounts a group of routes in the router
*
* @param Stub\Router\Group route
* @return Stub\Router
*/
public function mount(group)
{
var groupRoutes, beforeMatch, hostname, routes, route;
if typeof group != "object" {
throw new Router\Exception("The group of routes is not valid");
}
let groupRoutes = group->getRoutes();
if !count(groupRoutes) {
throw new Router\Exception("The group of routes does not contain any routes");
}
// Get the before-match condition
let beforeMatch = group->getBeforeMatch();
if beforeMatch !== null {
for route in groupRoutes {
route->beforeMatch(beforeMatch);
}
}
// Get the hostname restriction
let hostname = group->getHostName();
if hostname !== null {
for route in groupRoutes {
route->setHostName(hostname);
}
}
let routes = this->_routes;
if typeof routes == "array" {
let this->_routes = array_merge(routes, groupRoutes);
} else {
let this->_routes = groupRoutes;
}
return this;
}
/**
* Set a group of paths to be returned when none of the defined routes are matched
*
* @param array paths
* @return Stub\Router
*/
public function notFound(paths)
{
if typeof paths != "array" {
if typeof paths != "string" {
throw new Router\Exception("The not-found paths must be an array or string");
}
}
let this->_notFoundPaths = paths;
return this;
}
/**
* Removes all the pre-defined routes
*/
public function clear()
{
let this->_routes = [];
}
/**
* Returns the processed namespace name
*
* @return string
*/
public function getNamespaceName()
{
return this->_namespace;
}
/**
* Returns the processed module name
*
* @return string
*/
public function getModuleName()
{
return this->_module;
}
/**
* Returns the processed controller name
*
* @return string
*/
public function getControllerName()
{
return this->_controller;
}
/**
* Returns the processed action name
*
* @return string
*/
public function getActionName()
{
return this->_action;
}
/**
* Returns the processed parameters
*
* @return array
*/
public function getParams()
{
return this->_params;
}
/**
* Returns the route that matchs the handled URI
*
* @return Stub\Router\Route
*/
public function getMatchedRoute()
{
return this->_matchedRoute;
}
/**
* Returns the sub expressions in the regular expression matched
*
* @return array
*/
public function getMatches()
{
return this->_matches;
}
/**
* Checks if the router macthes any of the defined routes
*
* @return bool
*/
public function wasMatched()
{
return this->_wasMatched;
}
/**
* Returns all the routes defined in the router
*
* @return Stub\Router\Route[]
*/
public function getRoutes()
{
return this->_routes;
}
/**
* Returns a route object by its id
*
* @param string id
* @return Stub\Router\Route
*/
public function getRouteById(var id)
{
var route;
for route in this->_routes {
if route->getRouteId() == id {
return route;
}
}
return false;
}
/**
* Returns a route object by its name
*
* @param string name
* @return Stub\Router\Route
*/
public function getRouteByName(var name)
{
var route;
for route in this->_routes {
if route->getName() == name {
return route;
}
}
return false;
}
}