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
|
<?php
class Router {
private static $routes = [];
#===============================================================================
# Add route
#===============================================================================
public static function add($pattern, callable $callback) {
$pattern = Application::get('PATHINFO.BASE').$pattern;
return self::$routes[] = [
'type' => 'route',
'pattern' => $pattern,
'callback' => $callback
];
}
#===============================================================================
# Add redirect
#===============================================================================
public static function addRedirect($pattern, $location, $code = 302) {
$pattern = Application::get('PATHINFO.BASE').$pattern;
return self::$routes[] = [
'type' => 'redirect',
'code' => $code,
'pattern' => $pattern,
'location' => $location
];
}
#===============================================================================
# Execute routing
#===============================================================================
public static function execute($path) {
$path = ltrim($path, '/');
$route_found = FALSE;
foreach(self::$routes as $route) {
if($route['type'] === 'redirect') {
$location = preg_replace("#^{$route['pattern']}$#", $route['location'], $path, -1, $count);
if($count) {
HTTP::redirect($location, $route['code']);
}
}
else {
if(preg_match("#^{$route['pattern']}$#", $path, $matches)) {
# Remove the first element from matches which contains the whole string.
array_shift($matches);
$route_found = TRUE;
call_user_func_array($route['callback'], $matches);
}
}
}
if($route_found === FALSE) {
require_once ROOT.'404.php';
}
}
}
?>
|