diff options
Diffstat (limited to 'core/namespace')
-rw-r--r-- | core/namespace/Router.php | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/core/namespace/Router.php b/core/namespace/Router.php new file mode 100644 index 0000000..22784c2 --- /dev/null +++ b/core/namespace/Router.php @@ -0,0 +1,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 'system/404.php'; + } + } +} +?>
\ No newline at end of file |