fork download
  1. <?php
  2.  
  3. /**
  4.  * Description of Router
  5.  *
  6.  * @author home
  7.  */
  8.  
  9. namespace Core;
  10.  
  11. class Router
  12. {
  13.  
  14. public $routes = [];
  15. public $params = [];
  16.  
  17. public function addRoute(string $route, string $controller, string $action)
  18. {
  19. //экранируем слеши внутри
  20. $route = preg_replace('/\//', '\\/', $route);
  21.  
  22. //вычленяем параметры из строки запроса в фигурных скобках
  23. $route = preg_replace('/\{([\w\d-]+)\}/', '(?P<\1>[\w\d-]+)', $route);
  24.  
  25. //оформляем необходимые для регулярки элементы
  26. $route = '/^' . $route . '$/';
  27.  
  28. $this->routes[] = ['route' => $route, 'controller' => $controller, 'action' => $action];
  29. }
  30.  
  31. public function matchUri()
  32. {
  33. $uri = $_SERVER['QUERY_STRING'];
  34.  
  35. foreach ($this->routes as $route) {
  36. if (preg_match($route['route'], $uri, $matches)) {
  37.  
  38. $this->params['controller'] = $route['controller'];
  39. $this->params['action'] = $route['action'];
  40.  
  41. //цикл необходим, т.к. в массив совпаденией попадают элементы как и с цифровы индексом, так и с ассоциативным
  42. foreach ($matches as $param => $value) {
  43. if (is_string($param)) $this->params[$param] = $value;
  44. }
  45.  
  46. return $this->params;
  47. }
  48. }
  49. }
  50.  
  51. }
  52.  
Success #stdin #stdout 0.02s 82880KB
stdin
Standard input is empty
stdout
Standard output is empty