forked from dannyvankooten/PHP-Router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRouter.php
323 lines (283 loc) · 9.9 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
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
<?php
/**
* GetValue function.
*
* Returns the value of the specified key or default is the key is not defined.
*
* @param array $array The array to search.
* @param string|int $key The key to retrieve.
* @param mixed $default The default value of the key.
* @return mixed The default value if the key is not set, the value of the key
* otherwise.
*/
function getValue(array $array, $key, $default = '') {
return (isset($array[$key])) ? $array[$key] : $default;
}
/**
* Router class.
*
* Generates routes from given parameters and stores them. Can match a request
* to its associated route, returning that route object. Can generate an URL
* from given parameters if the parameters have been associated with a given
* route.
*
* @package AS-Router
* @license MIT
*/
class Router {
/**
* Array that holds all Route objects.
*
* @var array
*/
private $routes = array();
/**
* The base url.
*
* @var string
*/
private $basePath = '';
/**
* The instance of the class.
*
* @var Router
*/
private static $instance;
/**
* The current matched route.
*
* @var Route
*/
public $currentRoute;
/**
* Router constructor.
*/
private function __construct() {
}
/**
* Clone magic function.
*/
private function __clone() {
}
/**
* GetInstance method.
*
* Returns current instance of the Router object
*
* @return Router
*/
public static function getInstance() {
if (self::$instance == NULL) {
self::$instance = new Router();
}
return self::$instance;
}
/**
* SetBasePath method.
*
* Sets the base url that will get prepended to all route urls.
*
* @param string $basePath
*/
public function setBasePath($basePath) {
$this->basePath = (string) $basePath;
}
/**
* GetBasePath method.
*
* Returns the base url.
*
* @return string
*/
public function getBasePath() {
return $this->basePath;
}
/**
* PrefixURL method.
*
* Prefixes url by the Router::$basePath.
*
* @param string $url
* @return string
*/
public function prefixURL($url) {
return $this->basePath . $url;
}
/**
* Route factory method.
*
* Registers a route matching the given URL. The optionals arguments are:
*
* - `target`: an array specifying the controller and action.
* - `methods`: the HTTP methods allowed by the route. Defaults to `GET`.
* - `filters`: custom regexes matching named parameters in the URL. Named
* parameters with no matching filter will default to `([\w-]+)`.
* - `params`: pre-set the value of the route's parameters.
* - `name`: the name of the route. REQUIRED.
*
* The magic named parameters `:controller` and `:action` will set the route's
* target to their value, regardless of the previous target value.
*
* @param string $routeUrl string
* @param array $args Array of optional arguments.
*/
public function map($routeUrl, array $args = array()) {
if (is_array($routeUrl)) {
foreach ($routeUrl as $key => $value)
$this->map($key, $value);
} else {
$route = new Route();
$route->setUrl($routeUrl);
if (isset($args['target']))
$route->setTarget($args['target']);
if (isset($args['methods'])) {
$methods = (is_array($args['methods'])) ? $args['methods'] : explode('|', $args['methods']);
$route->setMethods($methods);
}
if (isset($args['filters']))
$route->setFilters($args['filters']);
if (isset($args['params']))
$route->setParameters($args['params']);
$this->routes[] = $route;
}
}
/**
* Matches the current request against mapped routes.
*/
public function matchCurrentRequest() {
$requestMethod = (isset($_POST['_method']) && ($_method = strtoupper($_POST['_method'])) && in_array($_method, array('PUT', 'DELETE'))) ? $_method : $_SERVER['REQUEST_METHOD'];
$requestUrl = $_SERVER['REQUEST_URI'];
// strip GET variables from URL
if (($pos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $pos);
}
return $this->match($requestUrl, $requestMethod);
}
/**
* Match given request url and request method and see if a route has been
* defined for it.
* If so, return route's target.
* If not, try to extract a controller and target.
* @param string $requestUrl
* @param string $requestMethod
* @return Route
* @throws RoutingException
*/
private function match($requestUrl, $requestMethod = 'GET') {
$cleanUrl = str_replace($this->getBasePath(), '', $requestUrl);
foreach ($this->routes as $route) {
// compare server request method with route's allowed http methods
if (!in_array($requestMethod, $route->getMethods()))
continue;
// check if request url matches route regex. if not, return false.
if (!preg_match("@^" . $route->getRegex() . "*$@i", $cleanUrl, $matches))
continue;
$this->currentRoute = clone $route;
$params = $this->currentRoute->getParameters();
if (preg_match_all("@:([\w-]+)@", $this->currentRoute->getUrl(), $argument_keys)) {
// grab array with matches
$argument_keys = $argument_keys[1];
// loop trough parameter names, store matching value in $params array
foreach ($argument_keys as $key => $name) {
if (isset($matches[$key + 1]))
$params[$name] = $matches[$key + 1];
}
}
$target = $this->currentRoute->getTarget();
if (isset($params['controller'])) {
$target['controller'] = ucfirst(strtolower($params['controller']));
unset($params['controller']);
}
if (isset($params['action'])) {
$target['action'] = $params['action'];
unset($params['action']);
}
$this->currentRoute->setTarget($target);
$params['requestMethod'] = $requestMethod;
$params['requestURL'] = $requestUrl;
$params['cleanURL'] = $cleanUrl;
$this->currentRoute->setParameters($params);
return $this->currentRoute;
}
throw new RoutingException("No route matching $requestMethod $requestUrl has been found.");
}
/**
* URL generation method.
*
* Generates a URL from the given target.
*
* @param array $target The target to generate.
* @param array $params Optional array of parameters to use in URL
* @return string The url to the route
* @throws UrlException
*/
public function generate(array $rawTarget, array $params = array()) {
$target = array(
'controller' => getValue($rawTarget, 'controller', null),
'action' => getValue($rawTarget, 'action', null)
);
if (is_indexed($rawTarget)) {
if (2 == count($rawTarget)) {
$target['controller'] = $rawTarget[0];
$target['action'] = $rawTarget[1];
} elseif (1 == count($rawTarget))
$target['action'] = $rawTarget[0];
}
// Check that controller is complete
if (!isset($target['controller']) || empty($target['controller']) || null === $target['controller']) {
if ($this->currentRoute instanceof Route) {
$currentTarget = $this->currentRoute->getTarget();
if (!empty($currentTarget['controller']))
$target['controller'] = $currentTarget['controller'];
else
throw new UrlException('Incomplete target was given for route generation (Current route has no controller).');
} else
throw new UrlException('Incomplete target was given for route generation (No current route).');
}
if (!isset($target['action']))
$target['action'] = 'index';
foreach ($this->routes as $route) {
if (!$route->match($target, $params))
continue;
$url = $route->getUrl();
$param_keys = array();
// replace route url with given parameters
if (0 < preg_match_all("@:(\w+)@", $url, $param_keys)) {
// grab array with matches
$param_keys = $param_keys[1];
// loop trough parameter names, store matching value in $params array
foreach ($param_keys as $i => $key) {
switch ($key) {
case 'controller':
case 'action':
$url = str_replace(':' . $key, $target[$key], $url);
break;
default:
$url = str_replace(':' . $key, $params[$key], $url);
break;
}
}
}
return $this->prefixURL($url);
}
throw new UrlException("No route matching {$target['controller']}#{$target['action']}(" . urldecode(http_build_query($params)) . ") has been found.");
}
}
/**
* Routing Exception
*
* Exception thrown when we can't match the current request to a route.
*
* @package AS-Router
* @license MIT
*/
class RoutingException extends Exception {}
/**
* Url Exception
*
* Exception thrown when we can't generate a url with the given information.
*
* @package AS-Router
* @license MIT
*/
class UrlException extends Exception {}