|
| 1 | +<?php |
| 2 | +namespace GuahanWeb\Http; |
| 3 | + |
| 4 | +class Router { |
| 5 | + protected $routes; |
| 6 | + |
| 7 | + protected function __construct() { |
| 8 | + $this->routes = array( |
| 9 | + 'GET' => array(), |
| 10 | + 'POST' => array(), |
| 11 | + 'PUT' => array(), |
| 12 | + 'DELETE' => array() |
| 13 | + ); |
| 14 | + } |
| 15 | + |
| 16 | + static public function instance() { |
| 17 | + static $instance; |
| 18 | + |
| 19 | + if (is_null($instance)) { |
| 20 | + $instance = new Router(); |
| 21 | + } |
| 22 | + |
| 23 | + return $instance; |
| 24 | + } |
| 25 | + |
| 26 | + protected function match($method, $uri, &$params = null) { |
| 27 | + if (isset($this->routes[$method])) { |
| 28 | + foreach ($this->routes[$method] as $route => $handler) { |
| 29 | + if ($uri == $route) { |
| 30 | + // exact match |
| 31 | + return $handler; |
| 32 | + } elseif (false !== preg_match_all('/\{([^}]+)\}/', $route, $match, PREG_PATTERN_ORDER)) { |
| 33 | + $args = $match[1]; |
| 34 | + if (count($args) > 0) { |
| 35 | + $keys = array(); |
| 36 | + $replacements = array(); |
| 37 | + |
| 38 | + foreach ($args as $k => $arg) { |
| 39 | + $keys[] = rtrim($arg, '*'); |
| 40 | + $replacements[] = (substr($arg, -1) == '*') ? '(.+?)' : '([^/]+)'; |
| 41 | + } |
| 42 | + |
| 43 | + $matcher = '/^' . str_replace('/', '\/', str_replace($match[0], $replacements, $route)) . '$/'; |
| 44 | + if (preg_match($matcher, $uri, $placeholders)) { |
| 45 | + // update params and return |
| 46 | + array_shift($placeholders); |
| 47 | + $params = array(); |
| 48 | + foreach ($keys as $k => $arg) { |
| 49 | + $params[$arg] = $placeholders[$k]; |
| 50 | + } |
| 51 | + |
| 52 | + return $handler; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + public function get($route, $handler) { |
| 62 | + $this->routes['GET'][$route] = $handler; |
| 63 | + } |
| 64 | + |
| 65 | + public function process() { |
| 66 | + $request = new Request(); |
| 67 | + $response = new Response(); |
| 68 | + |
| 69 | + if (false === ($handler = $this->match($request->method, $request->uri, $params))) { |
| 70 | + // Error case |
| 71 | + $response->send('Not found', 404); |
| 72 | + } |
| 73 | + |
| 74 | + // route params applied to the request object |
| 75 | + if (null !== $params) { |
| 76 | + foreach ($params as $k => $v) { |
| 77 | + $request->$k = $v; |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + $handler($request, $response); |
| 82 | + } |
| 83 | +} |
0 commit comments