SimpleRouter/Route.php

89 lines
1.7 KiB
PHP
Raw Normal View History

2015-09-10 06:37:52 -05:00
<?PHP
class Route{
2018-03-12 10:58:57 -05:00
private static $routes = Array();
private static $routes404 = Array();
private static $path;
private static $basepath = '/';
2015-09-10 06:37:52 -05:00
2018-03-12 10:58:57 -05:00
public static function init($basepath = '/'){
self::$basepath = $basepath;
2015-09-10 07:09:42 -05:00
$parsed_url = parse_url($_SERVER['REQUEST_URI']);//Parse Uri
2017-10-25 01:25:13 -05:00
2015-09-10 06:37:52 -05:00
if(isset($parsed_url['path'])){
2017-10-25 01:25:13 -05:00
self::$path = $parsed_url['path'];
2015-09-10 06:37:52 -05:00
}else{
2017-10-25 01:25:13 -05:00
self::$path = '/';
2015-09-10 06:37:52 -05:00
}
2017-10-25 01:35:17 -05:00
2015-09-10 06:37:52 -05:00
}
public static function add($expression,$function){
array_push(self::$routes,Array(
'expression'=>$expression,
'function'=>$function
));
}
public static function add404($function){
array_push(self::$routes404,$function);
}
public static function run(){
$route_found = false;
foreach(self::$routes as $route){
2018-03-12 10:49:55 -05:00
// Add basepath to matching string
2018-03-12 10:58:57 -05:00
if(self::$basepath!=''&&self::$basepath!='/'){
$route['expression'] = '('.self::$basepath.')'.$route['expression'];
2015-09-10 06:37:52 -05:00
}
2018-03-12 10:49:55 -05:00
// Add 'find string start' automatically
2015-09-10 06:37:52 -05:00
$route['expression'] = '^'.$route['expression'];
2018-03-12 10:49:55 -05:00
// Add 'find string end' automatically
2015-09-10 06:37:52 -05:00
$route['expression'] = $route['expression'].'$';
// echo $route['expression'].'<br/>';
2018-03-12 10:49:55 -05:00
// Check match
2015-09-10 06:37:52 -05:00
if(preg_match('#'.$route['expression'].'#',self::$path,$matches)){
2016-05-16 11:41:04 -05:00
2018-03-12 10:49:55 -05:00
array_shift($matches);// Always remove first element. This contains the whole string
2015-09-10 06:37:52 -05:00
2018-03-12 10:58:57 -05:00
if(self::$basepath!=''&&self::$basepath!='/'){
2015-09-10 06:37:52 -05:00
2018-03-12 10:49:55 -05:00
array_shift($matches);// Remove Basepath
2015-09-10 06:37:52 -05:00
}
call_user_func_array($route['function'], $matches);
$route_found = true;
}
}
if(!$route_found){
foreach(self::$routes404 as $route404){
call_user_func_array($route404, Array(self::$path));
}
}
}
}