forked from jeffturcotte/anchor
/
Anchor.php
2490 lines (2117 loc) · 63 KB
/
Anchor.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
/**
* Anchor is a routing library for PHP 5
*
* @copyright Copyright (c) 2012 Jeff Turcotte, others
* @author Jeff Turcotte [jt] <jeff.turcotte@gmail.com>
* @author Will Bond [wb] <will@flourishlib.com>
* @author Will Bond [wb-imarc] <will@imarc.net>
* @author Bill Bushee [bb] <bill@imarc.net>
* @author Kerri Gertz [kg] <kerri@imarc.net>
* @author Kevin Hamer [kh] <kevin@imarc.net>
* @license MIT (see LICENSE or bottom of this file)
* @package Anchor
* @link http://github.com/jeffturcotte/anchor
*/
class AnchorForbiddenException extends Exception {}
class AnchorNotAuthorizedException extends Exception {}
class AnchorNotFoundException extends Exception {}
class AnchorContinueException extends Exception {}
class AnchorProgrammerException extends Exception {}
final class AnchorDefaultAdapter {
function printFooter()
{
?>
</div>
</body>
</html>
<?php
}
function printHeader()
{
?>
<html>
<head>
<title>Whoops! We're lost :-(</title>
<link href='http://fonts.googleapis.com/css?family=Oswald&v1' rel='stylesheet' type='text/css'>
<style type="text/css">
body {
margin: 0;
padding: 0;
background: #ddd;
color: #444;
font-size: 20px;
font-family: 'Oswald', Helvetica, Arial, sans-serif;
}
#container {
width: 900px;
margin: 30px auto;
}
.troubleshooting {
background: #aaa;
padding: 15px 30px 30px;
border-radius: 10px;
margin: 0 -30px;
}
h1, h2 {
text-transform: uppercase;
}
h1 {
color: #333;
font-size: 60px;
}
h2 {
color: #333;
font-size: 30px;
}
</style>
</head>
<body>
<div id="container">
<?php
}
function forbidden()
{
if (!headers_sent()) {
header("HTTP/1.1 403 Forbidden");
}
$this->printHeader();
?>
<h1>Anchor: 403</h1>
<div class="troubleshooting">
<h2>Troubleshooting</h2>
<p>Anchor found a route, however, the user you're logged in as does not have access ot it.</p>
<ul>
<li>Make sure you're logged in as the right user</li>
<li>If you don't require authorization at that level, don't <code>::triggerForbidden</code></code></li>
</ul>
</div>
<?php
$this->printFooter();
}
function notAuthorized()
{
if (!headers_sent()) {
header("HTTP/1.1 401 Unauthorized");
}
$this->printHeader();
?>
<h1>Anchor: 401</h1>
<div class="troubleshooting">
<h2>Troubleshooting</h2>
<p>Anchor found a route, however, the route is requesting authorization.</p>
<ul>
<li>Make sure you're logged in</li>
<li>If you don't require authorization, don't <code>::triggerNotAuthorized</code></code></li>
</ul>
</div>
<?php
$this->printFooter();
}
function notFound()
{
if (!headers_sent()) {
header("HTTP/1.1 404 Not Found");
}
$this->printHeader();
?>
<h1>Anchor: 404</h1>
<div class="troubleshooting">
<h2>Troubleshooting</h2>
<p>Anchor can't find a route to this URL or a valid controller method.</p>
<ul>
<li>Check your controller path location. See <code>::setControllerPath()</code></li>
<li>Is your controller class authorized for execution? See <code>::authorize()</code></li>
<li>Is your controller method a public instance method?</li>
<li>Don't want to see this page? Set your own 404 callback. See <code>::setNotFoundCallback()</code></li>
<li>Have you set up a route to this URL? See <code>::add()</code></li>
</ul>
</div>
<?php
$this->printFooter();
}
}
class Anchor {
/**
* The parsed URL from Anchor::parseURL() that is matched against
*
* @var stdClass
*/
protected $url;
/**
* An array of headers to match against
*
* @var array
*/
protected $headers;
/**
* The parsed callback from Anchor::parseCallback() that is executed upon
* a successful match of the $url
*
* @var stdClass
*/
protected $callback;
/**
* The closure to execute, if this route's callback was a closure
*
* @var Closure
*/
protected $closure;
/**
* Render map aliases
*
* @var string
*/
protected static $aliases = array();
/**
* The path to search for controllers in. used by load()
*
* @var string
*/
protected static $controller_path = '';
/**
* The controller loading callback
*
* @var string
*/
protected static $loading_callback = '';
/**
* If trailing slashes should be removed via redirect
*
* @var boolean
*/
protected static $redirect_trailing_slashes = TRUE;
/**
* If urls should be redirected to the lower case version
*
* @var boolean
*/
protected static $redirect_to_lower_case = FALSE;
/**
* A stack containing all of the data objects
*
* @var array
*/
protected static $active_data = array();
/**
* An array of class names that can be used as callbacks with Anchor
*
* This helps provide security by creating a whitelist of the valid
* adapter classes when using parts of a URL to create the name of the
* callback to execute.
*
* @var array
*/
protected static $authorized_adapters = array(
'AnchorDefaultAdapter'
);
/**
* A stack containing all of the callbacks that have been run
*
* The most recently called callback will be at the end of the array.
*
* @var array
*/
protected static $active_callback = array();
/**
* An array used internally for caching simple, deterministic values
*
* @var array
*/
protected static $cache = array(
'find' => array(),
'urlize' => array(),
'camelize' => array()
);
/**
* Redirect to canonical URL if secondary URL is given
*
* @var boolean
*/
protected static $canonical_redirect = FALSE;
/**
* An associative array with keys being explicit names give to closures
* and the values being the internal identifier
*
* @var array
*/
protected static $closure_aliases = array();
/**
* Same as above, only flipped
*
* @var array
*/
protected static $closure_aliases_flipped = array();
/**
* The persistent data that is passed to the currently executing callback
*
* @var stdClass
*/
protected static $persistent_data = NULL;
/**
* An array of stdClass objects representing the callbacks to be executed
* for each hook/URL combination
*
* @var array
*/
protected static $hooks = array();
protected static $global_hooks = array();
protected static $active_hooks = array();
/**
* Shortcut token for use when matching against HTTP headers in URLs
*
* @var array
*/
protected static $tokens = array(
'get' => '[request-method=get]',
'post' => '[request-method=post]',
'put' => '[request-method=put]',
'delete' => '[request-method=delete]',
'html' => '[accept-type=application/xml]',
'json' => '[accept-type=application/json]',
'xml' => '[accept-type=text/xml]'
);
/**
* The callback to execute when a matching route is not found
*
* @var string
*/
protected static $forbidden_callback = 'AnchorDefaultAdapter::forbidden';
/**
* The callback to execute when a matching route is not found
*
* @var string
*/
protected static $not_authorized_callback = 'AnchorDefaultAdapter::notAuthorized';
/**
* The callback to execute when a matching route is not found
*
* @var string
*/
protected static $not_found_callback = 'AnchorDefaultAdapter::notFound';
/**
* All of the defined routes, each of which is an Anchor object
*
* @var array
*/
protected static $routes = array();
/**
* The path part of the URL for the current request
*
* @var string
*/
protected static $request_path = NULL;
/**
* The symbols for params and what characters such params should match
*
* @var array
*/
protected static $param_types = array(
':' => '[^/]+',
'!' => '[A-Za-z][A-Za-z0-9_-]+',
'^' => '[0-9]+',
'@' => '[A-Za-z]+',
'*' => '.+'
);
/**
* Whether or not the canonical redirect should be permanent
*
* @var bool
*/
protected static $permanent_canonical_redirect = FALSE;
protected static $templates = array();
/**
* The special param names to use when building a callback string from
* a URL.
*
* The key is the callback string part and the value is the param name.
*
* @var array
*/
protected static $callback_param_names = array(
'namespace' => 'namespace',
'short_class' => 'class',
'short_method' => 'method'
);
/**
* The callbacks to use to format parts of a callback string
*
* The key is the callback string part, the value is the callback to pass
* the string to.
*
* @var array
*/
protected static $callback_param_formatters = array(
'namespace' => 'Anchor::formatNamespace',
'short_class' => 'Anchor::upperCamelize',
'short_method' => 'Anchor::lowerCamelize'
);
/**
* undocumented variable
*
* @var string
*/
protected static $namespace_separator = '\\';
protected static $url_param_formatter = array(
'*' => array(
'*' => 'Anchor::makeUrlFriendly',
'id' => 'urlencode',
'namespace' => 'Anchor::makeUrlFriendlyNamespace'
)
);
protected static $running = FALSE;
/**
* The delimiter for translating strings into a URL friendly format
*
* @var string
*/
protected static $word_delimiter = '-';
// ==============
// = Public API =
// ==============
/**
* Adds a route to a callback
*
*
* The simplest $map is an explict path:
*
* /users/browse
*
* Parameters may be pulled out of the URL by specifying a :param_name
*
* /users/view/:id
*
* There are different sets of values that params can match, based on the
* first character of the param:
*
* - :param will match anything but a slash
* - !param will match any valid PHP identifier name, i.e. letters, numbers and underscore
* - ^param will match digits
* - @param will match letters
* - *param will match anything (greedy)
*
* The following $map will match numeric user IDs:
*
* /users/view/%id/preferences
*
* A $map can also match specific HTTP headers by using the [header=value]
* syntax before a path name. A space must be present between the closing ]
* and the beginning of the path.
*
* [accept-type=application/json] /api/users/list
*
* The following headers are supported:
*
* - request-method
* - accept-type
* - accept-language
*
* Matching of headers is done by comparing strings in a case-insensitive
* manner. The accept-type and accept-language headers will only match on
* the value with the highest q value.
*
* The following predefined shortcuts have been set up for matching headers:
*
* - get: [request-method=get]
* - post: [request-method=post]
* - put: [request-method=put]
* - delete: [request-method=delete]
* - html: [accept-type=text/html]
* - json: [accept-type=application/json]
* - xml: [accept-type=text/xml]
*
* The following $map would match GET requests with the accept-type header
* of application/json:
*
* get json /api/users
*
*
* The $callback parameter accepts a callback string for the class
* and method to call when the $map is matched.
*
* The following callback string would call the browse method of the Users
* class:
*
* Users::browse
*
* In addition to a class and method, it is also possible to specify the
* namespace:
*
* Controllers\Users::browse
*
* Both PHP 5.3 namespaces (Namespace\Class) and PHP 5.2-style namespaces
* (Namespace_Class) are detected.
*
* The namespace, class and method can be inferred from the $map by using
* the special param names of "namespace", "class" and "method" and then
* a * in the appropriate place in the $callback:
*
* Anchor::add('/!namespace/!class/!method', '*_*::*');
* Anchor::add('/!method', 'MySite_Users::*);
*
* In addition to allowing any value for part of the callback, a specific
* list of namespaces, classes or method can be specified by separating
* them with a pipe:
*
* Anchor::add('/!class/browse', 'Users|Groups::browse');
* Anchor::add('/users/!method', '*::add|list');
*
* @param string $map The URL to route - see method description for valid syntax
* @param string $callback The callback to execute - see method description for valid syntax
* @param Closure $closure The closure to execute for the route - if this is provided, $callback will be a name to reference the closure by
* @return void
*/
public static function add($map, $callback='*_*::*', $closure=NULL)
{
$headers = array();
$url = NULL;
$data = new stdClass;
// add closure name aliases, using spl_object_hash internally
if ($closure instanceof Closure) {
$alias = $callback;
$callback = 'Anchor_' . spl_object_hash($closure);
static::$closure_aliases[$alias] = $callback;
static::$closure_aliases_flipped[$callback] = $alias;
}
if ($map == '401') {
static::$not_authorized_callback = $callback;
return;
} elseif ($map == '403') {
static::$forbidden_callback = $callback;
return;
} elseif ($map == '404') {
static::$not_found_callback = $callback;
return;
}
// if callback is closure, swap args and generate closure name
if ($callback instanceof Closure) {
$closure = $callback;
$callback = 'Anchor_' . spl_object_hash($closure);
}
// use array or non-closure object in $closure arg as $data
if (is_array($closure) || (is_object($closure) && !($closure instanceof Closure))) {
$data = (object) $closure;
$closure = '';
}
// set url and headers conditions
foreach(preg_split('/\s+/', $map, NULL, PREG_SPLIT_NO_EMPTY) as $cond) {
// translate tokens
if (isset(static::$tokens[strtolower($cond)])) {
$cond = static::$tokens[strtolower($cond)];
}
// match url
if (preg_match('#^/.*#', $cond, $matches)) {
$url = $matches[0];
// match special conditions
} else if (preg_match_all('/\[([^\]]+)\=([^\]]+)\]/', $cond, $matches)) {
$headers = array_merge(
$headers,
array_combine(
$matches[1],
$matches[2]
)
);
}
}
$route = new Anchor();
$route->headers = $headers;
$route->url = static::parseUrl($url);
$route->data = $data;
$route->callback = static::parseCallback($callback);
$route->closure = $closure;
array_push(static::$routes, $route);
}
/**
* Adds an alias for a link map
*
* @param string $alias The alias name
* @param string $render_map The render map
* @return void
*/
public static function alias($alias, $render_map)
{
static::$aliases[$alias] = $render_map;
}
/**
* Authorizes a class or parent class to be used as a controller
*
* For security, the router will skip over any non-authorized class.
*
* @param string $controller The class name to authorize as a controller
* @return void
*/
public static function authorize($controller)
{
array_push(static::$authorized_adapters, $controller);
}
/**
* Returns TRUE if a callback will handle the URL
*
* @param string $url The URL to match against
* @return boolean If the URL will be handled
*/
public static function check($url)
{
$offset = 0;
$headers = array();
$params = array();
$data = NULL;
while ($callback = static::resolve($url, $headers, $params, $data, $offset)) {
if (static::validateCallback($callback)) {
return TRUE;
}
$offset++;
}
return FALSE;
}
/**
* Destroys all hooks and routes. This is most useful for running tests
*
* @return void
*/
public static function clear()
{
static::$routes = array();
static::$hooks = array();
}
/**
* If trailing slashes should not be removed via redirect
*
* @return void
*/
public static function disableTrailingSlashRedirect()
{
static::$redirect_trailing_slashes = FALSE;
}
/**
* Enable redirecting urls to the lower case version
*
* @return void
*/
public static function enableLowerCaseRedirect()
{
static::$redirect_to_lower_case = TRUE;
}
/**
* dispatch a callable (closure or method string)
*
* @param string|Closure $callable The string callback or Closure to dispatch
* @param object $instance The object to dispatch
* @param object &$data The data for the request
* @return void
*/
protected static function dispatchCallable($callable, $instance, &$data)
{
if ($callable instanceof Closure) {
call_user_func_array(
$callable,
array(&$data)
);
return TRUE;
}
$short_method = static::parseCallback($callable)->short_method;
$instance->$short_method($data);
return TRUE;
}
/**
* Instantiate controller classes
*
* @param string|Closure $callable
* @return void
*/
protected static function instantiateCallable($callable, &$data)
{
if ($callable instanceof Closure) {
return $callable;
}
$callback = static::parseCallback($callable);
$class = $callback->class;
$short_method = $callback->short_method;
return new $class($data);
}
/**
* Runs a callback/closure as run() would
*
* @param string|Closure $callable The string callback or closure to call
* @param stdClass $data The persistent data object that is passed to $callable
* @return stdClass|FALSE The $data or FALSE upon failure
*/
public static function &call($callable, $data=NULL, $exit=FALSE)
{
// merge any incoming data
if ($data === NULL) {
$data = (object) '';
unset($data->scalar);
}
if (!($callable instanceof Closure)) {
$callable = static::format($callable);
if (!static::validateCallback($callable)) {
$false = FALSE;
return $false;
}
}
$hooks = array();
static::pushActiveData($data);
static::pushActiveCallback($callable);
static::pushActiveHooks($hooks);
try {
$active_data = static::getActiveData();
$hooks = static::collectHooks($callable, TRUE);
$instance = static::instantiateCallable($callable, $active_data);
$hooks = array_merge($hooks, static::collectHooks($callable, TRUE));
static::callHookCallbacks($hooks, 'init', $active_data);
try {
static::callHookCallbacks($hooks, 'before', $active_data);
} catch (Exception $e) {
static::catchExceptionFromCall($hooks, $e, $active_data);
}
try {
static::dispatchCallable($callable, $instance, $active_data);
} catch (Exception $e) {
static::catchExceptionFromCall($hooks, $e, $active_data);
}
try {
static::callHookCallbacks($hooks, 'after', $active_data);
} catch (Exception $e) {
static::catchExceptionFromCall($hooks, $e, $active_data);
}
static::callHookCallbacks($hooks, 'finish', $active_data);
static::popActiveCallback();
static::popActiveHooks();
if (method_exists($instance, '__destruct')) {
$instance->__destruct();
}
if ($exit) {
exit();
}
$active_data = static::popActiveData();
return $active_data;
} catch (Exception $e) {
static::popActiveCallback();
static::popActiveData();
static::popActiveHooks();
throw $e;
}
}
protected static function catchExceptionFromCall($hooks, $e, &$active_data) {
$exception = new ReflectionClass($e);
$called = FALSE;
do {
$hook_name = "catch " . $exception->getName();
if (isset($hooks[$hook_name])) {
foreach($hooks[$hook_name] as $hook_obj) {
$callback = static::format($hook_obj->callback);
if (!is_callable($callback)) {
continue;
}
call_user_func_array($callback, array(&$active_data, $e));
$called = TRUE;
}
if ($called) {
break;
}
}
} while ($exception = $exception->getParentClass());
if (!$called) {
static::popActiveData();
static::popActiveCallback();
static::popActiveHooks();
throw $e;
}
}
/**
* Formats a string, replacing symbols with active callback values
*
* %n => active namespace
* %N => active parent/outermost namespace
* %c => active class
* %C => active short class
* %m => active method
* %M => active short method
* %p => active full path
* %P => active class path
*
* @param string $format The string to format
* @param boolean $urlize If the active callback values should be urlized, does not affect active path(s)
* @return string The formatted string
*/
public static function format($format, $urlize=FALSE, $default=NULL)
{
// no callback, or format not a string, just return $format
if (!($callback = static::getActiveCallback()) || !is_string($format)) {
return $format;
}
if ($callback instanceof Closure) {
$callback = 'Anchor_' . spl_object_hash($callback);
}
if (isset(static::$closure_aliases_flipped[$callback])) {
$callback = static::$closure_aliases_flipped[$callback];
}
// parse the callback
$callback = static::parseCallback($callback);
// make the path and class path
$short_class = static::urlize($callback->short_class);
$short_method = static::urlize($callback->short_method);
$path = "{$short_class}/{$short_method}";
$class_path = $short_class;
// make the class path
$class_path = static::urlize($callback->short_class);
// alter the full and class paths with namespace
if ($callback->namespace) {
$namespace = static::urlize($callback->namespace);
$path = "{$namespace}/{$path}";
$class_path = "{$namespace}/{$class_path}";
}
$formatter_pattern = "/[^%]%.{1}/i";
// set the replacements
$replacements = array(
'%n' => ($urlize) ? static::urlize($callback->namespace) : $callback->namespace,
'%N' => ($urlize) ? static::urlize($callback->parent_namespace) : $callback->parent_namespace,
'%c' => ($urlize) ? static::urlize($callback->class) : $callback->class,
'%C' => ($urlize) ? static::urlize($callback->short_class) : $callback->short_class,
'%m' => ($urlize) ? static::urlize($callback->method) : $callback->method,
'%M' => ($urlize) ? static::urlize($callback->short_method) : $callback->short_method,
'%p' => ($path == '/') ? '' : $path,
'%P' => ($class_path == '/') ? '' : $class_path
);
$formatted = str_replace(
array_keys($replacements),
array_values($replacements),
$format
);
if ($default && (!$formatted || preg_match("/[^%]%.{1}/", $formatted))) {
return $default;
}
return $formatted;
}
public static function formatNamespace($namespace)
{
$namespaces = explode('/', $namespace);
$namespaces = array_map(__CLASS__.'::upperCamelize', $namespaces);
$namespace = static::$namespace_separator . join(static::$namespace_separator, $namespaces);
return $namespace;
}
/**
* Generates a link from a callback/params string
*
* Example usage, without or with : before param name:
*
* Anchor::link('Users::view id', 5);
* Anchor::link('Users::view :id', 5);
*
* @param string $callback_key A string containing a callback and (optionally) param names - params should be separated by space and may begin with a :
* @return string The matching URL
*/
public static function link($callback_key)
{
$param_values = func_get_args();
$callback_key = trim(array_shift($param_values));
if (isset(static::$aliases[$callback_key])) {
$callback_key = static::$aliases[$callback_key];
}
$param_names = preg_split('/\s+/', $callback_key);
$callback = array_shift($param_names);
if (isset(static::$closure_aliases[$callback])) {
$callback = static::$closure_aliases[$callback];
}
$callback = static::format($callback);
if (isset($param_values[0])) {
$data =& $param_values[0];
if (is_object($data)) {
$param_values = array();
foreach($param_names as $key => $name) {
list($name, $property) = explode(':', $name);
$value = NULL;
if (!$property) {
$property = $name;
}
if (substr($property, -2, 2) == '()') {
$property = substr($property, 0, -2);
if (method_exists($data, $property) || method_exists($data, '__call')) {
$value = $data->$property();
}
} else if (isset($data->$property)) {
$value = $data->$property;
}
$param_names[$key] = $name;
$param_values[$key] = $value;
}
} else if (is_array($data)) {
$param_values = array();
if ($param_names) {
foreach($param_names as $key => $name) {
list($name, $property) = explode(':', $name);
$value = NULL;
if (isset($data[$property])) {
$value = $data[$property];
} else if (isset($data[$name])) {
$value = $data[$name];
}
$param_names[$key] = $name;
$param_values[$key] = $value;
}
} else {
foreach ($data as $key => $value) {
$param_names[$key] = $key;
$param_values[$key] = $value;
}
}
}