/
RecursiveRoute.php
656 lines (574 loc) · 20 KB
/
RecursiveRoute.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
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
<?php
class RecursiveRoute_InvalidArgument_Exception extends InvalidArgumentException {}
/**
* (c) 2009 Tibo Beijen (http://www.tibobeijen.nl)
*
* @TODO match callback
* @TODO subroutes restricted to certain param values (isn't that same as validators, no)
* @TODO change way url parts are transferred internally to avoid having to
* 'copy' filter methods to child routes (and thereby making it hard to manage
* filter order)
*/
class RecursiveRoute {
const SEPARATOR = '/';
/**
* The configuration pattern the Router is constructed with
*
* @var string
*/
private $pattern = '';
/**
* Tells it this is the root-route or a subroute.
* Will be set by addRoute()
*
* @var boolean
*/
private $isSubRoute = false;
/**
* List of optional regexp validator patterns for variables
*
* @var array
*/
protected $validators = array();
/**
* List of optional default values for variables.
* If a variable has a default value and is omitted when creating an url
* this router will match.
*
* @var array
*/
protected $defaults = array();
/**
* The configuration pattern exploded into parts
*
* @var array
*/
protected $patternParts;
/**
* List of subRouters in the order they were added
*
* @var array
*/
protected $subRoutes = array();
/**
* All the variables defined in the pattern
*
* @var array
*/
protected $definedParamList = array();
/**
* All the variables that are required
*
* @var array
*/
protected $requiredParamList = array();
/**
* Array holding filters applied on parts when creating an url
*
* @var array
*/
protected $createFilters = array();
/**
* Constructor, accepting options array.
* Possible options: validators, defaults
*
* @param string $pattern
* @param array $options
*/
public function __construct($pattern='', $options=array()) {
$this->pattern = $pattern;
$this->patternParts = $this->explode($pattern);
$this->buildParamLists($this->patternParts);
if (isset($options['validators'])) {
$this->setValidators($options['validators']);
}
if (isset($options['defaults'])) {
$this->setDefaults($options['defaults']);
}
// add default urlEncode filter
array_push(
$this->createFilters,
array($this, 'filterCreateUrlEncode')
);
}
/**
* Will add a subroute to this route
*
* @param $route
*/
public function addRoute( $route ) {
if ( is_string($route) ) {
$route = new RecursiveRoute($route);
}
if (!($route instanceof RecursiveRoute)) {
throw new RecursiveRoute_InvalidArgument_Exception(
__METHOD__.': Arguement should be string or RecursiveRoute object'
);
}
$route->setSubRoute();
array_push($this->subRoutes, $route);
}
/**
* Will set defaults for given parameters.
* Defaults are only allowed for params at the end of the route.
*
* @param array $defaults
*/
public function setDefaults(array $defaults) {
foreach($defaults as $key=>$value) {
if(is_numeric($key)) {
throw new RecursiveRoute_InvalidArgument_Exception(
__METHOD__.': $defaults should be an assoc. array'
);
}
// validate if default is for end part
$pos = array_search(':'.$key, $this->patternParts);
if ($pos !== false) {
// not valid if a part following this param exists in the
// patterns that:
// a) is not a parameter, or:
// b) is not in the given set of defaults
if (isset($this->patternParts[$pos+1])) {
$valid = true;
$patternPartExamined = $this->patternParts[$pos+1];
if ($patternPartExamined[0] !== ':') {
$valid = false;
}
$paramName = substr($patternPartExamined, 1);
if (!array_key_exists($paramName, $defaults)) {
$valid = false;
}
if (!$valid) {
throw new RecursiveRoute_InvalidArgument_Exception(
__METHOD__.': defaults can only be set for params ending the route definition'
);
}
}
}
$tempReqParam = array_flip($this->requiredParamList);
unset ($tempReqParam[$key]);
$this->requiredParamList = array_flip($tempReqParam);
}
$this->defaults = $defaults;
}
/**
* Will set validators for given parameters
* @param array $validators
*/
public function setValidators(array $validators) {
foreach($validators as $key=>$value) {
if(is_numeric($key)) {
throw new RecursiveRoute_InvalidArgument_Exception(
__METHOD__.': $validaors should be an assoc. array'
);
}
}
$this->validators = $validators;
}
/**
* Adds a method to the stack that will be applied when creating an url.
* Like the routes themselve, last edited will be applied first.
*
* The method signature should be compatible with php's call_user_func
* signature.
*
* By default an url_encode filter is allready registered.
*
* @param string|array $userFuncDefinition
*/
public function addCreateFilter( $userFuncDefinition ) {
array_push($this->createFilters, $userFuncDefinition);
// propagate filter to subroutes
foreach($this->subRoutes as $subRoute) {
$subRoute->addCreateFilter( $userFuncDefinition );
}
}
/**
* Will parse a given url and return an array containing parameters
*
* @param string $url
* @return array
*/
public function parseUrl( $url ) {
$urlParts = $this->explode( $url );
// the array holding params parsed by this router
$collectedParams = array();
// only self collect params if parseMatch
// (Only occcurs in root route as this method is not called on
// subroutes if they're not a match)
if ($this->isParseMatch($url)) {
$collectedParams = $this->defaults;
for ( $i=0; $i<count($this->patternParts); $i++ ) {
$partPattern = $this->patternParts[$i];
if ($partPattern[0] === ':') {
$paramName = substr($partPattern, 1);
if (isset($urlParts[$i])) {
$collectedParams[$paramName] = $urlParts[$i];
}
}
}
}
// construct partial url that gets passed to subroutes
$urlRemainingParts = array_slice($urlParts, count($this->patternParts));
$urlRemaining = implode('/', $urlRemainingParts);
$collectedSubRouteParams = array();
// search subRoutes, if match then call parseUrl on that one with the
// remaining part of this url
$subRouteMatched = false;
$subRoutes = array_reverse($this->subRoutes);
foreach ($subRoutes as $subRoute) {
if ( $subRoute->isParseMatch($urlRemaining)) {
$collectedSubRouteParams = $subRoute->parseUrl($urlRemaining);
$subRouteMatched = true;
break;
}
}
// if no subroute is able to handle further parsing, extract the remaining
// url parts as key/value pairs.
if ($subRouteMatched !== true) {
for($i=0; $i<count($urlRemainingParts); $i=$i+2) {
if(
isset($urlRemainingParts[$i]) &&
isset($urlRemainingParts[$i+1]) &&
!is_numeric($urlRemainingParts[$i])
) {
// store in subrouteparams
$collectedSubRouteParams[$urlRemainingParts[$i]] = $urlRemainingParts[$i+1];
}
}
}
return array_merge($collectedParams, $collectedSubRouteParams);
}
/**
* Will create an url of the given set of parameters
*
* @param array $params
* @return string
*/
public function createUrl($params = array() ) {
if (!is_array($params)) {
throw new RecursiveRoute_InvalidArgument_Exception(
__METHOD__.', Invalid argument: '.var_export($params,true)
);
}
// no problem if not a create match (delegate to children) unless
// this route has a defined pattern and no params are given.
if (
!$this->isCreateMatch($params) &&
count($params) < count($this->requiredParamList)
) {
throw new RecursiveRoute_InvalidArgument_Exception(
__METHOD__.', Missing required array keys for creating url'
);
}
// call recursive method that creates url parts
$collectResult = $this->collectUrlParts($params);
$urlParts = $collectResult['parts'];
$paramsProcessed = $collectResult['paramsProcessed'];
// add any unprocessed param as last url part
$paramsNotProcessed = $params;
foreach($paramsProcessed as $key) {
unset($paramsNotProcessed[$key]);
}
$unprocParamUrlPart = $this->constructUrlFromExcessParams($paramsNotProcessed);
$urlParts[] = $unprocParamUrlPart['parts'];
// create url
$urlChunks = array();
foreach($urlParts as $part) {
if (count($part)) {
$urlChunks[] = implode(self::SEPARATOR,$part);
}
}
$url = implode(self::SEPARATOR,$urlChunks);
if ($url!='' && $url!='/') {
$url = self::SEPARATOR . $url . self::SEPARATOR;
}
return $url;
}
/**
* If this route is a parse match for the parameters given it will add
* an url part and recursively call collectUrlParts on all subroutes
*
* @param array $paramsLeft
* @return array
*/
protected function collectUrlParts(array $paramsLeft) {
$currentUrlParts = array();
$paramsProcessed = array();
if( $this->isCreateMatch($paramsLeft)) {
$constructResult = $this->constructUrl($paramsLeft);
$constructedPart = $constructResult['parts'];
$paramsProcessed = $constructResult['paramsProcessed'];
// only add if not empty (likely the 'root' Route)
if (count($constructedPart) != 0) {
$currentUrlParts[] = $constructedPart;
}
// remove tags covered in this route from the list
$truncatedParamsLeft = $paramsLeft;
foreach ($this->definedParamList as $paramName) {
unset($truncatedParamsLeft[$paramName]);
}
// iterate over routes
$subRouteMatched = false;
$subRoutes = array_reverse($this->subRoutes);
foreach ($subRoutes as $subRoute) {
$collectResult = $subRoute->collectUrlParts($truncatedParamsLeft);
$returnedUrlParts = $collectResult['parts'];
$paramsProcessed = array_merge(
$paramsProcessed,
$collectResult['paramsProcessed']
);
if (count($returnedUrlParts)>0) {
foreach( $returnedUrlParts as $part ) {
$currentUrlParts[] = $part;
}
$subRouteMatched = true;
break;
}
}
}
$return = array(
'parts' => $currentUrlParts,
'paramsProcessed' => $paramsProcessed
);
return $return;
}
/**
* Determines if this Route is a match for creating a partial url.
* A Route is only then a match if all the required parameters
* are provided in $paramHash
*
* Exception: If this route doesn't have any required parts, has subRoutes,
* and is not the root route, at least one of the children has to match for this route
* to be considered a match
*
* @param array $paramHash
* @return boolean
*/
protected function isCreateMatch($paramHash) {
if (
$this->isSubRoute==true &&
count($this->subRoutes)>0 &&
count($this->requiredParamList)==0
) {
$match = false;
$subRoutes = array_reverse($this->subRoutes);
foreach ($subRoutes as $subRoute) {
if ($subRoute->isCreateMatch($paramHash)) {
$match = true;
break;
}
}
} else {
$match = true;
// only check for params that don't have a default specified
foreach($this->requiredParamList as $paramName) {
if( !isset($paramHash[$paramName])) {
$match = false;
} elseif (isset($this->validators[$paramName])) {
if (!preg_match(
$this->validators[$paramName],
$paramHash[$paramName]
)) {
$match = false;
}
}
}
}
return $match;
}
/**
* Will determine if this route is a match for parsing.
* A route is a parse match if the given url is at least as long and if
* all non variable url parts match that of the pattern.
*
* @TODO if not root router and itself has no required parts,
* it should delegate to subroutes.
*
* @param string $url
* @return boolean
*/
protected function isParseMatch($url = null) {
// @TODO check this
if (count($this->patternParts)==0 && count($this->subRoutes)==0) {
return false;
}
$urlParts = $this->explode($url);
// check length, if shorter: no match
if (count($urlParts) < (count($this->patternParts)-count($this->defaults)) ) {
return false;
}
// check separate params
$match = true;
if( count($this->patternParts) > 0 ) {
for ( $i=0; $i<count($this->patternParts); $i++ ) {
$partPattern = $this->patternParts[$i];
if ( $partPattern[0] === ':') {
// param, check if a validator exists
$paramName = substr($partPattern, 1);
$partUrl = false;
if (isset($this->defaults[$paramName])) {
$partUrl = $this->defaults[$paramName];
}
if (isset($urlParts[$i])) {
$partUrl = $urlParts[$i];
}
// if somehow not set as default and not in the url:
// no match
if ($partUrl===false) {
return false;
}
// part defined, validate if neccessary
if (isset($this->validators[$paramName])) {
if (!preg_match(
$this->validators[$paramName],
$partUrl
)) {
$match = false;
break;
}
}
} else {
$partUrl = $urlParts[$i];
if ($partPattern !== $partUrl) {
$match = false;
break;
}
}
}
}
return $match;
}
/**
* Creates an url as defined by the configuration pattern and the values
* given by $params
*
* @TODO url encode
*
* @param array $params
* @return string
*/
protected function constructUrl($params = array()) {
$constructedUrlParts = array();
$paramsProcessed = array();
foreach($this->patternParts as $part) {
if ($part[0] === ':') {
// variable, get it from params
$paramName = substr($part, 1);
$paramValue = '';
if (isset($this->defaults[$paramName])) {
$paramValue = $this->defaults[$paramName];
}
if (isset($params[$paramName])) {
$paramValue = $params[$paramName];
}
// apply filters
$paramValueFiltered = $this->applyCreateFilters(
$paramValue,
$paramName
);
$constructedUrlParts[] = $paramValueFiltered;
$paramsProcessed[] = $paramName;
} else {
// apply filter and add
$partFiltered = $this->applyCreateFilters($part);
$constructedUrlParts[] = $partFiltered;
}
}
$return = array(
'parts' => $constructedUrlParts,
'paramsProcessed' => $paramsProcessed
);
return $return;
}
/**
* Creates an url of excess params as key/value combinations
*
* @TODO url encode
*
* @param array $params
* @return array
*/
protected function constructUrlFromExcessParams($params = array()) {
$constructedUrlParts = array();
$paramsProcessed = array();
foreach($params as $key=>$value) {
// apply filters
$keyFiltered = $this->applyCreateFilters($key);
$valueFiltered = $this->applyCreateFilters($value, $key);
$constructedUrlParts[] = $keyFiltered;
$constructedUrlParts[] = $valueFiltered;
$paramsProcessed[] = $key;
}
$return = array(
'parts' => $constructedUrlParts,
'paramsProcessed' => $paramsProcessed
);
return $return;
}
/**
* Marks the route object as being a subroute
*
* @param boolean $value
*/
protected function setSubRoute($value=true) {
$this->isSubRoute = (boolean) $value;
}
/**
* Will turn the given (partial) url into separate parts
*
* @param string $urlPart
* @return array
*/
protected function explode($urlPart) {
$urlTrimmed = trim(trim($urlPart, self::SEPARATOR));
$parts = array();
if($urlTrimmed!='') {
$parts = explode(self::SEPARATOR, $urlTrimmed);
}
return $parts;
}
/**
* Will fill some member vars with lists defining the configured variables
*
* @param array $pattern_parts
*/
protected function buildParamLists( $pattern_parts = array() ) {
$arr_params = array();
foreach ($pattern_parts as $part_pattern ) {
if ( $part_pattern[0] === ':' ) {
$arr_params[] = substr( $part_pattern, 1 );
}
}
$this->definedParamList = $arr_params;
$this->requiredParamList = $arr_params;
}
/**
* Applies all the create filters. Last added first.
*
* @param string $value
* @param string $paramName
* @return string
*/
protected function applyCreateFilters($value, $paramName='') {
$filters = array_reverse($this->createFilters);
$valueFiltered = $value;
foreach ($filters as $filterDef) {
if (!is_array($filterDef)) {
}
$valueFiltered = call_user_func($filterDef, $valueFiltered, $paramName);
}
return $valueFiltered;
}
/**
* Create filter that will rawurlencode() value.
*
* @param string $value
* @param string $paramName
* @return string
*/
protected function filterCreateUrlEncode($value, $paramName='') {
$valueFiltered = rawurlencode($value);
return $valueFiltered;
}
}