123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?php namespace System\Routing;
- use System\Request;
- class Router {
-
- public $request;
-
- public $routes;
-
- public function __construct($method, $uri, $loader)
- {
-
-
- $this->request = $method.' /'.trim($uri, '/');
- $this->routes = $loader->load($uri);
- }
-
- public static function make($method, $uri, $loader)
- {
- return new static($method, $uri, $loader);
- }
-
- public function route()
- {
-
-
- if (isset($this->routes[$this->request]))
- {
- return Request::$route = new Route($this->request, $this->routes[$this->request]);
- }
- foreach ($this->routes as $keys => $callback)
- {
-
-
- if (strpos($keys, '(') !== false or strpos($keys, ',') !== false )
- {
- foreach (explode(', ', $keys) as $key)
- {
- if (preg_match('#^'.$this->translate_wildcards($key).'$#', $this->request))
- {
- return Request::$route = new Route($keys, $callback, $this->parameters($this->request, $key));
- }
- }
- }
- }
- }
-
- private function translate_wildcards($key)
- {
- $replacements = 0;
-
-
-
- $key = str_replace(array('/(:num?)', '/(:any?)'), array('(?:/([0-9]+)', '(?:/([a-zA-Z0-9\.\-_]+)'), $key, $replacements);
- $key .= ($replacements > 0) ? str_repeat(')?', $replacements) : '';
- return str_replace(array(':num', ':any'), array('[0-9]+', '[a-zA-Z0-9\.\-_]+'), $key);
- }
-
- private function parameters($uri, $route)
- {
- return array_values(array_intersect_key(explode('/', $uri), preg_grep('/\(.+\)/', explode('/', $route))));
- }
- }
|