You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.3 KiB

  1. <?php
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage app
  7. * @since 2010-02-25
  8. * @version SVN: $Id$
  9. * @filesource $URL$
  10. */
  11. class Router
  12. {
  13. protected $routes = array();
  14. protected $route_name;
  15. protected $default_layout = 'Default';
  16. /**
  17. * @var Route
  18. */
  19. protected $route;
  20. public function add($name, $route, $action, $params = array(), $layout = null)
  21. {
  22. if (!$layout) {
  23. $layout = $this->default_layout;
  24. }
  25. $this->routes[$name] = new Route($route, $action, $params, $layout);
  26. }
  27. public function route($request)
  28. {
  29. $req = explode('/', trim($request, '/'));
  30. foreach ($this->routes as $name => $route) {
  31. if ($route->match($req)) {
  32. $this->route_name = $name;
  33. $this->route = $route;
  34. Env::setParams($route->getParams());
  35. return $this->route;
  36. }
  37. }
  38. return false;
  39. }
  40. public function setDefaultLayout($layout = 'Default')
  41. {
  42. $this->default_layout = $layout;
  43. }
  44. public function getRouteName()
  45. {
  46. return $this->route_name;
  47. }
  48. /**
  49. * @return Route
  50. */
  51. public function getRoute()
  52. {
  53. return $this->route;
  54. }
  55. /**
  56. * @param $name
  57. * @return bool
  58. */
  59. protected function routeIsExists($name)
  60. {
  61. return array_key_exists($name, $this->routes);
  62. }
  63. /**
  64. * @param $name
  65. * @return Route
  66. */
  67. protected function getRouteByName($name)
  68. {
  69. return $this->routes[$name];
  70. }
  71. /**
  72. * @param null $route_name
  73. * @return string
  74. * @throws ErrorException
  75. */
  76. public function getUri($route_name = null)
  77. {
  78. if (is_null($route_name)) {
  79. $route = $this->getRoute();
  80. } else {
  81. if ($this->routeIsExists($route_name)) {
  82. $route = $this->getRouteByName($route_name);
  83. } else {
  84. $btrace = debug_backtrace();
  85. throw new ErrorException('Unknown route name: "' . $route_name . '". ' . 'Call from "' . $btrace[0]['file'] . '" on line ' . $btrace[0]['line'] . '.');
  86. }
  87. }
  88. return $route->getUri();
  89. }
  90. }