forked from dannyvankooten/AltoRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAltoRouter.php
619 lines (619 loc) · 18.1 KB
/
AltoRouter.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
<?php
/**
* An api map/routing mechanism. Simplified and small.
* Based on klein.php and uses elements of Sinatra for regex
* matching for routes.
*
* PHP Version 5
*
* @category AltoRouter
* @package AltoRouter
* @author Danny van Kooten <[email protected]>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/dannyvankooten/AltoRouter
*/
namespace AltoRouter;
/**
* An api map/routing mechanism. Simplified and small.
* Based on klein.php and uses elements of Sinatra for regex
* matching for routes.
*
* @category AltoRouter
* @package AltoRouter
* @author Danny van Kooten <[email protected]>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/dannyvankooten/AltoRouter
*/
class AltoRouter
{
/**
* Array of all routes (incl. named routes).
*
* @var array
*/
protected $routes = array();
/**
* Array of all named routes.
*
* @var array
*/
protected $namedRoutes = array();
/**
* Can be used to ignore leading part of the request
* URL (if main file lives in subdirectory of host).
*
* @var string
*/
protected $basePath = '';
/**
* Can be used to set case sensitivity.
*
* @var bool
*/
protected $ignoreCase = false;
/**
* Array of default match types (regex helpers)
*
* @var array
*/
protected $matchTypes = array(
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
);
/**
* Array of default parameters.
*
* @var array
*/
protected $defaultParams = array();
/**
* Array of transformers.
*
* @var array
*/
protected $transformers = array();
/**
* Create router in one call from config.
*
* @param array $routes The default routes to add.
* @param string $basePath The basePath at instantiation time.
* @param array $matchTypes Any additions matching types you'd like.
* @param array $defaultParams Any default parameters.
* @param bool $ignoreCase Ignore the case in matching?
*
* @return void
*/
public function __construct(
$routes = array(),
$basePath = '',
$matchTypes = array(),
$defaultParams = array(),
$ignoreCase = false
) {
$this->addRoutes($routes);
$this->setBasePath($basePath);
$this->addMatchTypes($matchTypes);
$this->addDefaultParams($defaultParams);
$this->setIgnoreCase($ignoreCase);
}
/**
* Magic method to route get, put, post, patch, and delete
* to the map method. So you can call router->get(...) or
* router->post(...) without constant rewriting.
*
* $router->get($route, $target, $name);
* $router->put($route, $target, $name);
* $router->post($route, $target, $name);
* $router->patch($route, $target, $name);
* $router->delete($route, $target, $name);
*
* @param string $name What are we calling.
* @param array $arguments The arguments less the method.
*
* @return void
*/
public function __call(
$name,
$arguments
) {
$name = strtolower($name);
$validTypes = array(
'get' => 'GET',
'put' => 'PUT',
'post' => 'POST',
'patch' => 'PATCH',
'delete' => 'DELETE'
);
// If method type is invalid don't do anything.
if (!isset($validTypes[$name])) {
return;
}
// Prepend the type to our arguments to pass to the map.
array_unshift(
$arguments,
$validTypes[$name]
);
// Pass to the map method.
call_user_func_array(
array($this, 'map'),
$arguments
);
return $this;
}
/**
* Retrieves all routes.
* Useful if you want to process or display routes.
* Returns array of all routes.
*
* @return array
*/
public function getRoutes()
{
return $this->routes;
}
/**
* Returns the named routes.
*
* @return array
*/
public function getNamedRoutes()
{
return $this->namedRoutes;
}
/**
* Returns the base path.
*
* @return array
*/
public function getBasePath()
{
return $this->basePath;
}
/**
* Returns the default parameters.
*
* @return array
*/
public function getDefaultParams()
{
return $this->getDefaultParams();
}
/**
* Returns ignore case value.
*
* @return bool
*/
public function getIgnoreCase()
{
return $this->ignoreCase;
}
/**
* Add multiple routes at once from array in the following format:
*
* $routes = array(
* array($method, $route, $target, $name)
* );
*
* @param array $routes Array of routes you'd like to add.
*
* @author Koen Punt
*
* @throws Exception
*
* @return AltoRouter
*/
public function addRoutes($routes)
{
if (!is_array($routes)
&& !$routes instanceof \Traversable
) {
$msg
= 'Routes should be an array or an instance of Traversable';
if (!defined('HHVM_VERSION')) {
$msg = _('Routes should be an array or an instance of Traversable');
}
throw new \Exception($msg);
}
foreach ($routes as $route) {
call_user_func_array(array($this, 'map'), $route);
}
return $this;
}
/**
* Set the base path.
* Useful if you are running your application from a subdirectory.
*
* @param string $basePath The basepath to set as needed.
*
* @return AltoRouter
*/
public function setBasePath($basePath)
{
$this->basePath = $basePath;
return $this;
}
/**
* Set the ignore case value.
* Useful to enable/disable case sensitivity.
*
* @param bool $ignoreCase Set or not?
*
* @return AltoRouter
*/
public function setIgnoreCase($ignoreCase)
{
$this->ignoreCase = (bool)$ignoreCase;
return $this;
}
/**
* Add named match types. It uses array_merge so keys can be overwritten.
*
* @param array $matchTypes The key is the name and the value is the regex.
*
* @return AltoRouter
*/
public function addMatchTypes($matchTypes)
{
$this->matchTypes = array_merge(
$this->matchTypes,
$matchTypes
);
return $this;
}
/**
* Adds default parameters.
*
* @param array $defaultParams The items to add.
*
* @return AltoRouter
*/
public function addDefaultParams($defaultParams)
{
$this->defaultParams = array_merge(
$this->defaultParams,
$defaultParams
);
return $this;
}
/**
* Add transformer.
*
* @param string $matchType The name/key for an added match type
* (see: addMatchTypes())
* @param \AltoTransformer $transformer A transformer instance.
*
* @return AltoRouter
*/
public function addTransformer($matchType, \AltoTransformer $transformer)
{
$this->transformers[$matchType] = $transformer;
return $this;
}
/**
* Map a route to a target.
*
* @param string $method One of 5 HTTP Methods,
* or a pipe-separated list of multiple HTTP Methods
* (GET|POST|PATCH|PUT|DELETE)
* @param string $route The route regex,
* custom regex must start with an @.
* You can use multiple pre-set regex filters, like [i:id].
* @param mixed $target The target where this route
* should point to. Can be anything.
* @param string $name Optional name of this route.
* Supply if you want to reverse route this url in your application.
*
* @throws Exception
*
* @return AltoRouter
*/
public function map(
$method,
$route,
$target,
$name = null
) {
foreach (explode('|', $method) as $method) {
if (!isset($this->routes[$method])) {
$this->routes[$method] = array();
}
$this->routes[$method][] = array($route, $target, $name);
unset($method);
}
if ($name) {
if (isset($this->namedRoutes[$name])) {
$msg = sprintf(
"%s '%s'",
'Can not redeclare route',
$name
);
if (!defined('HHVM_VERSION')) {
$msg = sprintf(
"%s '%s'",
_('Can not redeclare route'),
$name
);
}
throw new \Exception($msg);
}
$this->namedRoutes[$name] = $route;
}
return $this;
}
/**
* Reversed routing.
* Generate the URL for a named route. Replace regexes with supplied parameters
*
* @param string $routeName The name of the route.
* @param array $params Associative array of parameters
* to replace placeholders with.
*
* @throws Exception
*
* @return string The URL of the route with named parameters in place.
*/
public function generate(
$routeName,
array $params = array()
) {
// Check if named route exists
if (!isset($this->namedRoutes[$routeName])) {
throw new \Exception(
"Route '{$routeName}' does not exist."
);
}
// Replace named parameters
$route = $this->namedRoutes[$routeName];
// prepend base path to route url again
$url = $this->basePath . $route;
// merge with default params.
$params = array_merge(
$this->defaultParams,
$params
);
$pattern = '`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`';
if (preg_match_all($pattern, $route, $matches, PREG_SET_ORDER)) {
foreach ($matches as $index => $match) {
list(
$block,
$pre,
$type,
$param,
$optional
) = $match;
if ($pre) {
$block = substr($block, 1);
}
if (isset($this->transformers[$type])) {
$params[$param] = $this->transformers[$type]
->toUrl($params[$param]);
}
if (isset($params[$param])) {
// Part is found, replace for param value.
$url = str_replace(
$block,
$params[$param],
$url
);
} elseif ($optional && $index !== 0) {
$url = str_replace(
$pre . $block,
'',
$url
);
} else {
$url = str_replace(
$block,
'',
$url
);
}
}
}
return $url;
}
/**
* Match a given Request Url against stored routes.
* Returns Array with route information on success,
* false on failure (no match).
*
* @param string $requestUrl The request url if needed specifically.
* @param string $requestMethod The request method if needed specifically.
*
* @return array|boolean
*/
public function match(
$requestUrl = null,
$requestMethod = null
) {
$params = array();
$match = false;
// set Request Url if it isn't passed as parameter
if (null === $requestUrl) {
$requestUrl = $this->getRequestURI() ?: '/';
}
// strip base path from request url
$requestUrl = substr(
$requestUrl,
strlen($this->basePath)
);
// Strip query string (?a=b) from Request Url
if (false !== ($strpos = strpos($requestUrl, '?'))) {
$requestUrl = substr($requestUrl, 0, $strpos);
}
// set Request Method if it isn't passed as a parameter
if (null === $requestMethod) {
$requestMethod = $this->getRequestMethod() ?: 'GET';
}
if (empty($this->routes[$requestMethod])) {
return false;
}
foreach ($this->routes[$requestMethod] as $handler) {
list(
$route,
$target,
$name
) = $handler;
unset($handler);
if ('*' === $route) {
// * wildcard (matches all)
$match = true;
} elseif (isset($route[0])
&& $route[0] === '@'
) {
// @ regex delimiter
$pattern = '`'
. substr($route, 1)
. '`u'
. ($this->ignoreCase ? 'i' : null);
$match = (1 === preg_match($pattern, $requestUrl, $params));
} elseif (false === ($position = strpos($route, '['))) {
// No params in url, do string comparison
$match = 0 === strcmp($requestUrl, $route);
} else {
// Compare longest non-param string with url
if (0 !== strncmp($requestUrl, $route, $position)) {
continue;
}
$regex = $this->_compileRoute($route);
$match = (1 === preg_match($regex['regex'], $requestUrl, $params));
}
if ($match) {
if ($params) {
$routeisarr = is_array($route);
foreach ($params as $key => $value) {
if (is_numeric($key)) {
unset($params[$key]);
continue;
}
if (!$routeisarr) {
continue;
}
$type = $route['types'][$key];
if (isset($this->transformers[$type])) {
$params[$key]
= $this->transformers[$type]->fromUrl($value);
}
unset($values);
}
/**
* Send the request method so we can test.
* Most likely we use php://input so we wouldn't
* be able to tell by the variables.
*
* Sending the method with the system allows us to
* map a single route that acts upon both types.
* You could do this in the function too but we
* already know the method, why not just pass it in?
*/
$params['method'] = $requestMethod;
}
$result = $this->getMatchedResult(
$target,
$params,
$name
);
if ($result) {
return $result;
}
}
}
return false;
}
/**
* Compile the regex for a given route (EXPENSIVE)
*
* @param string $route The route to compile.
*
* @return string
*/
private function _compileRoute($route)
{
$pattern = '`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`';
$route = array(
'regex' => sprintf(
'`^%s$`u%s',
$route,
($this->ignoreCase ? 'i' : '')
),
'types' => array()
);
if (preg_match_all($pattern, $route['regex'], $matches, PREG_SET_ORDER)) {
$matchTypes = $this->matchTypes;
foreach ($matches as $match) {
list(
$block,
$pre,
$type,
$param,
$optional,
) = $match;
unset($match);
$optional = ('' !== $optional ? '?' : null);
$route['types'][$param] = $type;
if (isset($matchTypes[$type])) {
$type = $matchTypes[$type];
}
if ('.' === $pre) {
$pre = '\.';
}
// Older versions of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ('' !== $pre ? $pre.'+' : null)
. '('
. ('' !== $param ? "?P<$param>" : null)
. $type
. ')'
. $optional
. '(/+|))'
. $optional;
$route['regex'] = str_replace($block, $pattern, $route['regex']);
}
}
return $route;
}
/**
* Get request URI from $_SERVER.
*
* @return string
*/
protected function getRequestURI()
{
return filter_input(INPUT_SERVER, 'REQUEST_URI');
}
/**
* Get request method from $_SERVER
*
* @return string
*/
protected function getRequestMethod()
{
return filter_input(INPUT_SERVER, 'REQUEST_METHOD');
}
/**
* Get the matched result to return.
* Doing so from a function allows user to override
* in their own extends.
*
* @param string $target The target.
* @param mixed $params The parms (how we call).
* @param string $name The name of the match.
*
* @return array
*/
protected function getMatchedResult(
$target,
$params,
$name
) {
return array(
'target' => $target,
'params' => $params,
'name' => $name
);
}
}