Advertisement
stuppid_bot

Router

Jun 11th, 2014
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.21 KB | None | 0 0
  1. <?php
  2.  
  3. class Router {
  4.     protected $path;
  5.     protected $defaultHandler;
  6.     protected $routes = array();
  7.  
  8.     public function __construct($path = null, $default_handler = null, array $routes = null) {
  9.         $this->setPath($path);
  10.         $this->setDefaultHandler($default_handler);
  11.         if (is_array($routes)) {
  12.             $this->setRoutes($routes);
  13.         }
  14.     }
  15.  
  16.     public function setPath($path) {
  17.         $this->path = $path;
  18.     }
  19.  
  20.     public function setDefaultHandler($handler) {
  21.         $this->defaultHandler = $handler;
  22.     }
  23.  
  24.     public function setRoutes(array $routes) {
  25.         foreach ($routes as $pattern => $handler) {
  26.             $this->setRoute($pattern, $handler);
  27.         }
  28.     }
  29.  
  30.     public function setRoute($route, $handler) {
  31.         preg_match('!^(?:(\w+)\s*)?(/\S*)$!', trim($route), $matches);
  32.         if (empty($matches)) {
  33.             throw new Exception('Bad route');
  34.         }
  35.         list($method, $pattern) = array_slice($matches, 1);
  36.         $method = $method ? strtoupper($method) : '*';
  37.         $placeholders = array(
  38.             'id' => '[1-9]\d{0,9}',
  39.             'int' => '\d+',
  40.             'str' => '\w+',
  41.         );
  42.         foreach ($placeholders as $k => $v) {
  43.             $pattern = str_replace("<$k>", "($v)", $pattern);
  44.         }
  45.         $pattern = "#^$pattern\$#";
  46.         $this->routes[$method][$pattern] = $handler;
  47.     }
  48.  
  49.     public function run() {
  50.         foreach ($this->routes as $method => $patterns) {
  51.             if ($method == '*' || $method == $_SERVER['REQUEST_METHOD']) {
  52.                 foreach ($patterns as $pattern => $handler) {
  53.                     if (preg_match($pattern, $this->path, $matches)) {
  54.                         return $this->invoke($handler, array_slice($matches, 1));
  55.                     }
  56.                 }
  57.             }
  58.         }
  59.         if ($this->defaultHandler) {
  60.             $this->invoke($this->defaultHandler);
  61.         }
  62.     }
  63.  
  64.     protected function invoke($handler, $args = array()) {
  65.         $arr = preg_split('/\s*\.\s*/', trim($handler), 2);
  66.         $arr[0] = new $arr[0];
  67.         $arr[1] = isset($arr[1]) && $arr[1] ? $arr[1] : 'index';
  68.         call_user_func_array($arr, $args);
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement