/
Moor.php
1381 lines (1176 loc) · 36.1 KB
/
Moor.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
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Moor is a URL Routing/Linking/Controller library for PHP 5
*
* @copyright Copyright (c) 2010-2011 Jeff Turcotte, others
* @author Jeff Turcotte [jt] <jeff.turcotte@gmail.com>
* @author Will Bond [wb] <will@flourishlib.com>
* @author Will Bond, iMarc LLC [wb-imarc] <will@imarc.net>
* @license MIT (see LICENSE or bottom of this file)
* @package Moor
* @link http://github.com/jeffturcotte/moor
* @version 1.0.0b9
*/
class Moor {
/**
* The currently running callback
*
* @var string
*/
private static $active_callback = NULL;
/**
* The currently running namespace
*
* @var string
*/
private static $active_namespace = NULL;
/**
* The currently running class (w/ namespace)
*
* @var string
*/
private static $active_class = NULL;
/**
* The currently running class (w/o namespace)
*
* @var string
*/
private static $active_short_class = NULL;
/**
* The currently running method (w/ namespace & class)
*
* @var string
*/
private static $active_method = NULL;
/**
* The currently running method (w/o namespace or class)
*
* @var string
*/
private static $active_short_method = NULL;
/**
* The currently running function
*
* @var string
*/
private static $active_function = NULL;
/**
* The currently active proxy URI
*
* @var string
*/
private static $active_proxy_uri = NULL;
/**
* The camelize() cache
*
* @var array
*/
private static $camelize = array();
/**
* Default pattern to match :id params in incoming urls
*
* @var string
*/
private static $default_request_param_pattern = '[A-Za-z0-9_]+';
/**
* Whether or not to show debug messages on default 404 page
*
* @var boolean
**/
private static $debug = FALSE;
/**
* Wether or not to cache with APC
*
* @var boolean
**/
private static $enable_cache = FALSE;
/**
* The current more instance, only used for chaining
*
* @var object Moor
*/
private static $instance = NULL;
/**
* The linkTo() cache
*
* @var array
*/
private static $link_to = array();
/**
* Debug messages
*
* @var array
**/
private static $messages = array();
/**
* The 404 callback to run upon no route matches
*
* @var string
**/
private static $not_found_callback = 'Moor::routeNotFoundCallback';
/**
* The paramsTo() cache
*
* @var array
*/
private static $params_to = array();
/**
* The request path
*
* @var string
**/
private static $request_path = NULL;
/**
* Restless URLs
*
* @var boolean
*/
private static $restless_urls = FALSE;
/**
* All routes in their compiled form
*
* @var array
**/
private static $routes = array();
/**
* Whether or not the router is running
*
* @var boolean
*/
private static $running = FALSE;
/**
* The underscore() cache
*
* @var array
*/
private static $underscorize = array();
/**
* The prefix to add to $url_string when calling ::route()
*
* @var string
*/
private static $url_prefix = '';
// ==============
// = Public API =
// ==============
/**
* Enable or disable the debugging
*
* @return object The Moor instance for chaining
**/
public static function enableDebug()
{
self::$debug = TRUE;
return self::getInstance();
}
/**
* Enable automatic redirecting for added/missing slashes at the end of
* the request path
*
* @return void
*/
public static function enableRestlessURLs()
{
self::$restless_urls = TRUE;
}
/**
* Find the URL where a particular callback lives
*
* @param string $callback_string The callback to search for
* @param string $params The GET params to send
* @return string The URL
*/
public static function linkTo($key)
{
$param_values = func_get_args();
$callback_string = array_shift($param_values);
$callback_string = trim($callback_string);
$callback_string = self::expandCallback($callback_string);
if (!isset(self::$link_to[$key])) {
//self::$cache_for_linkTo[$key] = FALSE;
$best_route = NULL;
$param_names = preg_split('/(\s+:)|(\s+)|((?<!:):(?!:))/', $callback_string);
$callback_string = array_shift($param_names);
$param_names_flipped = array_flip($param_names);
$callback_params = array();
$param_matches = NULL;
$low_dist = NULL;
$top_accu = NULL;
$low_diff = NULL;
$top_sect = NULL;
if (!$best_route) {
foreach(self::$routes as $route) {
$callback = $route->callback;
if (!preg_match($callback->pattern, $callback_string, $callback_param_matches)) {
continue;
}
foreach($callback_param_matches as $name => $param_match) {
if (is_string($name)) { $callback_params[$name] = $param_match; }
}
$dist = levenshtein($callback->finder, $callback_string);
$accu = strrpos($callback->finder, '*');
$diff = count(array_diff(array_keys($route->url->request_params), $param_names));
$sect = count(array_intersect_key(array_flip(array_keys($route->url->request_params)), $param_names_flipped));
$is_best = (
$best_route === NULL ||
$low_dist > $dist ||
$low_dist == $dist && $top_accu < $accu ||
$low_dist == $dist && $top_accu == $accu && $top_sect < $sect ||
$low_dist == $dist && $top_accu == $accu && $top_sect <= $sect && $low_diff > $diff
);
if ($is_best) {
$best_route = $route;
$low_dist = $dist;
$top_accu = $accu;
$top_sect = $sect;
$low_diff = $diff;
}
}
}
if (!$best_route) {
throw new MoorProgrammerException('No link could be found for the callback ' . $callback_string);
}
if ($best_route) {
$cache = (object) $best_route->url->shorthand;
$cache->param_names = $param_names;
$cache->included_param_names = array_flip(array_intersect(
$param_names, array_keys($best_route->url->request_params)
));
$cache->excluded_param_names = array_flip(array_diff(
$param_names, array_keys($best_route->url->request_params)
));
$url = $best_route->url->shorthand;
foreach($best_route->url->callback_params as $name => $callback_param) {
$url = str_replace(
$callback_param->search,
call_user_func_array(
self::compat($callback_param->formatter),
array($callback_params[$callback_param->name])
),
$url
);
}
$cache->url = $url;
self::$link_to[$key] = $cache;
}
}
$cache =& self::$link_to[$key];
if ($cache == FALSE) {
return '#';
}
$url = $cache->url;
$params = array();
if (!empty($cache->param_names)) {
$params = array_combine(
$cache->param_names,
$param_values
);
}
$included_params = array_intersect_key($params, $cache->included_param_names);
$excluded_params = array_intersect_key($params, $cache->excluded_param_names);
foreach($included_params as $name => $value) {
$url = str_replace(':'.$name, urlencode($value), $url);
}
foreach($excluded_params as $name => $value) {
$excluded_params[$name] = $value;
}
if (!empty($excluded_params)) {
// Remove any fragment so we can place it fter the query string
if (preg_match('/#.*$/', $url, $match)) {
$url = substr($url, 0, 0 - strlen($match[0]));
}
$url .= '?' . http_build_query($excluded_params);
if (!empty($match)) {
$url .= $match[0];
}
}
if (isset(self::$active_proxy_uri)) {
$url = self::$active_proxy_uri . $url;
}
return $url;
}
/**
* Return whether debugging is enabled or not
*
* @return boolean
*/
public static function getDebug()
{
return self::$debug;
}
/**
* Return all debug messages set up to this point
*
* @return array
**/
public static function getMessages()
{
return self::$messages;
}
/**
* Returns the callback for the currently running route
*
* @return string
*/
public static function getActiveCallback()
{
return self::$active_callback;
}
/**
* Returns the class (w/ namespace for the currently running route
*
* @return string
**/
public static function getActiveClass()
{
return self::$active_class;
}
/**
* Returns the path for the currently running route's class
*
* @return string
*/
public static function getActiveClassPath()
{
return self::pathTo(self::getActiveClass());
}
/**
* Returns the function for the currently running route
*
* @return string
*/
public static function getActiveFunction()
{
return self::$active_function;
}
/**
* Returns the method (w/ class and namespace) for the currently running route
*
* @return string
*/
public static function getActiveMethod()
{
return self::$active_method;
}
/**
* Returns the namespace for the currently running route
*
* @return string
*/
public static function getActiveNamespace()
{
return self::$active_namespace;
}
/**
* Returns the short class name (class w/o namespace) for the currently running route
*
* @return string
*/
public static function getActiveShortClass()
{
return self::$active_short_class;
}
/**
* Returns the short method (method w/o class or namespace) for the currently running route
*
* @return string
*/
public static function getActiveShortMethod()
{
return self::$active_short_method;
}
/**
* Returns the path for the currently running route
*
* @return string
*/
public static function getActivePath()
{
return self::pathTo(self::getActiveCallback());
}
/**
* Returns the proxy URI for the currently running route
*
* @return string
*/
public static function getActiveProxyURI()
{
return self::$active_proxy_uri;
}
/**
* Returns the request path for the current request
*
* @return string
*/
public static function getRequestPath()
{
return self::$request_path;
}
/**
* Gets the callback for when a route is not found.
*
* @return callback The callback to use for executing the not found functionality
**/
public static function getNotFoundCallback()
{
return self::$not_found_callback;
}
/**
* Get the path to the supplied callback
*
* @param string $callback
* @param string $directory_separator
* @return void
*/
public static function pathTo($callback, $directory_separator=NULL)
{
$string = self::expandCallback($callback);
return self::makePath($string, $directory_separator);
}
/**
* Find the params to a particular callback. Will return an array of arrays.
* one per router with valid param of the route's URL.
*
* @param string $callback The callback to search for
* @return array The params
*/
public static function paramsTo($callback)
{
$callback = self::expandCallback($callback);
if (isset(self::$params_to[$callback])) {
return self::$params_to[$callback];
}
$params = array();
foreach(self::$routes as $route) {
if (preg_match($route->callback->pattern, $callback)) {
$route_params = array();
foreach($route->url->request_params as $name => $request_param) {
array_push($route_params, $name);
}
array_push($params, $route_params);
}
}
self::$params_to[$callback] = $params;
return self::$params_to[$callback];
}
/**
* Assign a URL to a callback for routing
*
* @param string $url_string The shorthand URL or regular expression pattern to match
* @param string|closure $callback_string The callback to be run on a successful match, the name of the assoc. closure, or a closure
* @param closure $function An optional closure, named by the previous argument (for linking)
* @return object The Moor instance for chaining
*/
public static function route($url_string, $callback_string, $function=NULL)
{
// reset caches using routes
self::$link_to = array();
self::$params_to = array();
if (self::$running == TRUE) {
throw new MoorProgrammerException(
'No new routes can be added once routing has been started.'
);
}
$url_string = self::$url_prefix . $url_string;
if ($callback_string instanceof Closure) {
$function = $callback_string;
$callback_string = '';
}
$route = (object) 'route';
$route->url = self::parseUrl($url_string);
$route->callback = self::parseCallback($callback_string);
$route->function = $function;
// validate that the url and callback use the same callback params
$diff = array_merge(
array_diff_key($route->callback->params, $route->url->callback_params),
array_diff_key($route->url->callback_params, $route->callback->params)
);
if (count($diff)) {
throw new MoorProgrammerException(
'Route: ' . $route->url->scalar . ', url and callback have different callback params: ' . join(',', array_keys($diff))
);
}
array_push(self::$routes, $route);
return self::getInstance();
}
/**
* Starts routing
*
* @return void
*/
public static function run()
{
self::$running = TRUE;
if (!empty($_SERVER['PATH_INFO'])) {
self::$active_proxy_uri = str_replace($_SERVER['PATH_INFO'], '', $_SERVER['REQUEST_URI']);
self::$request_path = urldecode(preg_replace('#\?.*$#', '', $_SERVER['PATH_INFO']));
} else {
self::$request_path = urldecode(preg_replace('#\?.*$#', '', $_SERVER['REQUEST_URI']));
}
$old_GET = $_GET;
$_GET = array();
foreach(self::$routes as $route) {
self::$active_callback = NULL;
self::$active_namespace = NULL;
self::$active_class = NULL;
self::$active_short_class = NULL;
self::$active_method = NULL;
self::$active_short_method = NULL;
self::$active_function = NULL;
$_GET = $old_GET;
try {
self::dispatchRoute($route);
} catch (MoorContinueException $e) {
continue;
} catch (MoorNotFoundException $e) {
break;
}
}
self::$messages[] = 'No Valid Matches Found. Running Not Found callback: ' . self::$not_found_callback;
$route = (object) 'route';
$route->url = self::parseUrl('*');
$route->callback = self::parseCallback(self::$not_found_callback);
$route->function = NULL;
self::dispatchRoute($route);
}
/**
* Sets the pattern that will match a URL request param if no pattern is given
*
* @param string $pattern The regular expression to match a request param in the URL
* @return object The Moor instance for chaining
**/
public static function setRequestParamPattern($pattern)
{
self::$default_request_param_pattern = $pattern;
return self::getInstance();
}
/**
* Set the callback for when a route is not found.
*
* @param string $callback The static method or function callback for 404s
* @return object The Moor instance for chaining
**/
public static function setNotFoundCallback($callback)
{
self::$not_found_callback = $callback;
return self::getInstance();
}
/**
* Sets a string to prefix to $url_string when calling ::route()
*
* @param string $prefix The string to prefix
* @return object The Moor instance for chaining
**/
public static function setUrlPrefix($prefix)
{
self::$url_prefix = $prefix;
return self::getInstance();
}
/**
* Triggers skipping the current route and moving to the next one.
*
* @return void
*/
public static function triggerContinue()
{
throw new MoorContinueException();
}
/**
* Triggers the not found callback when the router is running.
*
* @return void
*/
public static function triggerNotFound()
{
throw new MoorNotFoundException();
}
// ===============
// = Private API =
// ===============
/**
* Private constructor to disallow instantiating
*
* @return object
*/
private function __construct() {}
/**
* Converts an `underscore_notation` or `camelCase` string to `camelCase`
*
* Derived from MIT fGrammer::camelize
* Source: http://flourishlib.com/browser/fGrammar.php
*
* Copyright (c) 2007-2009 Will Bond <will@flourishlib.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @param string $original The string to convert
* @param boolean $upper If the camel case should be `UpperCamelCase`
* @return string The converted string
*/
private static function &camelize($original, $upper=FALSE)
{
$upper = (int) $upper;
$key = "{$upper}/{$original}";
if (isset(self::$camelize[$key])) {
return self::$camelize[$key];
}
$string = $original;
// Check to make sure this is not already camel case
if (strpos($string, '_') === FALSE) {
if ($upper) {
$string = strtoupper($string[0]) . substr($string, 1);
}
// Handle underscore notation
} else {
$string = strtolower($string);
if ($upper) { $string = strtoupper($string[0]) . substr($string, 1); }
$string = preg_replace('/(_([a-z0-9]))/e', 'strtoupper("\2")', $string);
}
self::$camelize[$key] =& $string;
return $string;
}
/**
* Provides a compatibility layer for PHP 5.2 style static callbacks to
* work with PHP 5.1.
*
* @param callback $callback The callback to make compatible
* @return callback A callback that is compatibile with PHP 5.1
*/
private static function compat($callback)
{
if (is_string($callback) && strpos($callback, '::') !== FALSE) {
$callback = explode('::', $callback);
}
return $callback;
}
/**
* Dispatch a callback
*
* @param object $route a route stdObject
* @return void
**/
private static function dispatchRoute($route)
{
if (!preg_match($route->url->pattern, self::$request_path, $matches)) {
if (self::$restless_urls) {
$rev = strrev(self::$request_path);
$try_path = ($rev{0} == '/')
? substr(self::$request_path, 0, -1)
: self::$request_path . '/';
if (preg_match($route->url->pattern, $try_path)) {
$new_location = (!empty($_SERVER['PATH_INFO']))
? self::$active_proxy_uri . $try_path
: $try_path;
header('Location: ' . $new_location, TRUE, 301);
exit();
}
}
return FALSE;
}
self::$messages[] = 'Match. Request path ' . self::$request_path . ' matched URL definition "' . $route->url->scalar . '"';
foreach($matches as $name => $param) {
if (is_string($name)) {
$_GET[$name] = urldecode($param);
}
}
$callback_string = self::injectParamsIntoCallback($route->callback);
self::$messages[] = 'Generated Callback: ' . $callback_string;
self::$active_callback = $callback_string;
// dispatch closure
if ($route->function instanceof Closure) {
self::$active_function = $callback_string;
self::$messages[] = 'Calling assigned closure';
call_user_func(self::compat($route->function));
exit();
// dispatch function
} else if (function_exists($callback_string)) {
// disallow dangerous functions
if (preg_match('/^[\*_\\\\]+$/', $route->callback->finder)) {
self::$messages[] = 'Skipping callback ' . $callback_string . ': Callback definition is dangerous.';
self::triggerContinue();
}
$function = new ReflectionFunction($callback_string);
if (method_exists($function, 'getNamespaceName')) {
self::$active_namespace = $function->getNamespaceName();
}
self::$active_function = $callback_string;
self::$messages[] = 'Calling function: ' . $callback_string;
call_user_func($callback_string);
exit();
// dispatch method
} else {
self::validateMethodCallback($callback_string);
$method = new ReflectionMethod($callback_string);
$class = self::compat($callback_string);
$class = $class[0];
$parsed_class = self::parseClass($class);
self::$active_method = $callback_string;
self::$active_short_method = $method->getName();
self::$active_class = $class;
self::$active_short_class = $parsed_class['short_class'];
self::$active_namespace = $parsed_class['namespace'];
if ($method->isStatic()) {
self::$messages[] = 'Calling static method: ' . $callback_string;
call_user_func(self::compat($callback_string));
exit();
} else {
self::$messages[] = 'Instantiating class for ' . $callback_string;
new $class();
exit();
}
}
self::$messages[] = 'Skipping callback: ' . $callback_string . '. Not a valid method or function.';
self::triggerContinue();
}
/**
* Expands a callback starting with *:: or *\ or *_ to include the active class/namespace
*
* @param string $callback
* @return string The expanded callback
*/
private static function expandCallback($callback) {
$string = $callback;
if (strpos($callback, '*::') === 0) {
$string = self::getActiveClass() . substr($callback, 1);
}
if (strpos($callback, '*\\') === 0 || preg_match('/^\*_[A-Z][A-Za-z0-9]*::/', $callback)) {
$string = self::getActiveNamespace() . substr($callback, 1);
}
return $string;
}
/**
* Extracts callback params (@*) from a url string
*
* @param string $string A url or callback string from route()
* @return array An array of callback params in stdObject form
*/
private static function &extractCallbackParams($string)
{
$callback_params = array();
preg_match_all(
'/{?(?P<param>@
(?P<name>[A-Za-z]([A-Za-z]|(_(?!@)))*)
(\((?P<format>[A_Z0-9a-z-_]+)\))?
)}?/x',
$string,
$matches
);
$validator = $string;
foreach($matches['param'] as $i => $param) {
$name = '_Moor_'.$matches['name'][$i];
// if no format, default format to u
$format = $matches['format'][$i] ? $matches['format'][$i] : 'u';
switch ($format) {
// UpperCamelCaseFormat
case "uc":
$pattern = '[A-Z][0-9A-Za-z]*';
$formatter = __CLASS__.'::upperCamelize';
break;
// lowerCamelCaseFormat
case "lc":
$pattern = '[a-z][0-9A-Za-z]*';
$formatter = __CLASS__.'::lowerCamelize';
break;
// underscore_format
case "u":
$pattern = '[a-z_][0-9a-z_]*';
$formatter = __CLASS__.'::underscorize';
break;
// invalid format
default:
throw new MoorProgrammerException(
$string . ' contains invalid formatting rule: ' . $format
);
}
$callback_param = (object) $name;
$callback_param->search = $param;
$callback_param->name = $name;
$callback_param->pattern = $pattern;
$callback_param->formatter = $formatter;
$callback_param->replacement = "(?P<{$name}>{$pattern})";
$callback_params[$name] = $callback_param;
$validator = str_replace($param, '%@'.$format.'%', $validator);
}
// check for invalid callback param juxtapositions
// that can't be used for routing/linking
$invalid_patterns = array();
$invalid_patterns['/(%@u%%@lc%)/'] =
'an underscore param directly before lowerCamelCase param';
$invalid_patterns['/(((%@lc%)|(%@uc%))%@u%)/'] =
'an underscore param directly after UpperCamelCase param or lowerCamelCase param';
$invalid_patterns['/(%@u%_?%@u%)/'] =
'directly juxtaposed underscore params or underscore params joined by an underscore character';
$invalid_patterns['/((%@lc%%@uc%)|(%@uc%%@lc%))/'] =
'directly juxtaposed lowerCamelCase and/or UpperCamelCase params';
foreach($invalid_patterns as $pattern => $message) {
if (preg_match($pattern, $validator)) {
throw new MoorProgrammerException(
"Unroutable/Unlinkable callback params. {$string} contains {$message}"
);
}
}
return $callback_params;
}
/**
* Extracts request params (:*) from a url string
*
* @param string $url_string A url string from route()
* @return array An array of request params in stdObject form
*/
private static function &extractRequestParams($url_string)
{
$request_params = array();
preg_match_all(
'/(?P<search>:(?P<param>[A-Za-z_][A-Za-z0-9_]*))(?P<pattern_offset>\()?/x',
$url_string,
$matches,
PREG_OFFSET_CAPTURE
);
foreach($matches['param'] as $key => $name) {
$request_param = (object) $name[0];
$request_param->name = $name[0];
$request_param->search = ':'.$name[0];
$pattern = self::$default_request_param_pattern;
if (isset($matches['pattern_offset'][$key][1])) {