SimpleRouter/Route.php

104 lines
2.5 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();
2018-03-13 10:01:52 -05:00
private static $pathNotFound = null;
private static $methodNotAllowed = null;
public static function add($expression, $function, $method = 'get'){
array_push(self::$routes,Array(
'expression' => $expression,
'function' => $function,
'method' => $method
));
}
public static function pathNotFound($function){
self::$pathNotFound = $function;
}
public static function methodNotAllowed($function){
self::$methodNotAllowed = $function;
}
2015-09-10 06:37:52 -05:00
2018-03-13 10:01:52 -05:00
public static function run($basepath = '/'){
// Parse current url
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'])){
2018-03-13 10:01:52 -05:00
$path = $parsed_url['path'];
2015-09-10 06:37:52 -05:00
}else{
2018-03-13 10:01:52 -05:00
$path = '/';
2015-09-10 06:37:52 -05:00
}
2017-10-25 01:35:17 -05:00
2018-03-13 10:01:52 -05:00
// Get current request method
$method = $_SERVER['REQUEST_METHOD'];
$path_match_found = false;
$route_match_found = false;
2015-09-10 06:37:52 -05:00
foreach(self::$routes as $route){
2018-03-13 10:01:52 -05:00
// If the method matches check the path
2018-03-12 10:49:55 -05:00
// Add basepath to matching string
2018-03-13 10:01:52 -05:00
if($basepath!=''&&$basepath!='/'){
$route['expression'] = '('.$basepath.')'.$route['expression'];
}
// Add 'find string start' automatically
$route['expression'] = '^'.$route['expression'];
2015-09-10 06:37:52 -05:00
2018-03-13 10:01:52 -05:00
// Add 'find string end' automatically
$route['expression'] = $route['expression'].'$';
// echo $route['expression'].'<br/>';
2018-03-13 10:01:52 -05:00
// Check path match
if(preg_match('#'.$route['expression'].'#',$path,$matches)){
$path_match_found = true;
// Check method match
if(strtolower($method) == strtolower($route['method'])){
array_shift($matches);// Always remove first element. This contains the whole string
if($basepath!=''&&$basepath!='/'){
array_shift($matches);// Remove basepath
}
call_user_func_array($route['function'], $matches);
$route_match_found = true;
// Do not check other routes
break;
}
2015-09-10 06:37:52 -05:00
}
}
2018-03-13 10:01:52 -05:00
// No matching route was found
if(!$route_match_found){
2015-09-10 06:37:52 -05:00
2018-03-13 10:01:52 -05:00
// But a matching path exists
if($path_match_found){
header("HTTP/1.0 405 Method Not Allowed");
if(self::$methodNotAllowed){
call_user_func_array(self::$methodNotAllowed, Array($path,$method));
}
}else{
header("HTTP/1.0 404 Not Found");
if(self::$pathNotFound){
call_user_func_array(self::$pathNotFound, Array($path));
}
}
2015-09-10 06:37:52 -05:00
}
}
}