-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRouter.php
119 lines (98 loc) · 2.97 KB
/
Router.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
<?php namespace Devtools;
use Exception;
class Router
{
private static $resources = array();
public static function resource($path, RestInterface $controller = null)
{
if (is_array($path)) {
foreach ($path as $subpath => $subcontroller) {
self::resource($subpath, $subcontroller);
}
}
if (!is_null($controller)) {
self::$resources[$path] = $controller;
}
}
public static function resources()
{
return self::$resources;
}
public static function call($uri)
{
if ($request = self::parseRequest($uri)) {
$method = strtolower($_SERVER['REQUEST_METHOD']);
return self::$resources[$request['route']]->$method($request['params']);
}
throw new Exception("Route for {$uri} not found.");
}
private static function isOptional($element)
{
return substr($element, 0, 1) === '('
&& substr($element, -1) === ')';
}
private static function parseOptional($element)
{
return substr($element, 1, strlen($element)-2);
}
private static function isParameter($element)
{
return substr($element, 0, 1) === ':';
}
private static function isNotAtEndOfPath($path, $checkIndex)
{
return count($path)-1 >= $checkIndex;
}
private static function validateRoute($pattern, $path)
{
$patternArray = explode('/', $pattern);
$path = explode('/', $path);
$checkIndex = 0;
$params = array();
foreach ($patternArray as $element) {
if ($optional = self::isOptional($element)) {
$element = self::parseOptional($element);
}
if (!$optional
&& $element !== $path[$checkIndex]
&& !self::isParameter($element)
) {
return false;
}
if (self::isNotAtEndOfPath($path, $checkIndex)) {
if ($element === $path[$checkIndex]) {
++$checkIndex;
continue;
}
if (!empty($element) && self::isParameter($element)) {
$params[substr($element, 1)] = self::formatValue($path[$checkIndex]);
++$checkIndex;
continue;
}
}
if ($optional) {
continue;
}
return false;
}
return array(
'route' => $pattern,
'params' => $params
);
}
public static function formatValue($value)
{
return is_numeric($value)
? intval($value)
: $value;
}
public static function parseRequest($path)
{
foreach (array_keys(self::$resources) as $potentialRoute) {
if ($route = self::validateRoute($potentialRoute, $path)) {
return $route;
}
}
return false;
}
}