123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- <?php namespace System;
- class Router {
-
- public static $routes;
-
- public static function route($method, $uri)
- {
- if (is_null(static::$routes))
- {
- static::$routes = static::load($uri);
- }
-
-
- $uri = $method.' /'.trim($uri, '/');
-
- if (isset(static::$routes[$uri]))
- {
- return Request::$route = new Route($uri, static::$routes[$uri]);
- }
- foreach (static::$routes as $keys => $callback)
- {
-
-
- if (strpos($keys, '(') !== false or strpos($keys, ',') !== false )
- {
- foreach (explode(', ', $keys) as $key)
- {
- if (preg_match('#^'.$key = static::translate_wildcards($key).'$#', $uri))
- {
- return Request::$route = new Route($keys, $callback, static::parameters($uri, $key));
- }
- }
- }
- }
- }
-
- public static function load($uri)
- {
- return (is_dir(APP_PATH.'routes')) ? static::load_from_directory($uri) : require APP_PATH.'routes'.EXT;
- }
-
- private static function load_from_directory($uri)
- {
-
-
- $home = (file_exists($path = APP_PATH.'routes/home'.EXT)) ? require $path : array();
- if ($uri == '')
- {
- return $home;
- }
- $segments = explode('/', $uri);
- return (file_exists($path = APP_PATH.'routes/'.$segments[0].EXT)) ? array_merge(require $path, $home) : $home;
- }
-
- private static function translate_wildcards($key)
- {
- return str_replace(':num', '[0-9]+', str_replace(':any', '[a-zA-Z0-9\-_]+', $key));
- }
-
- public static function parameters($uri, $route)
- {
- return array_values(array_intersect_key(explode('/', $uri), preg_grep('/\(.+\)/', explode('/', $route))));
- }
- }
|