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.

113 lines
2.4 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. protected $error_layout = 'Error';
  17. /**
  18. * @var Route
  19. */
  20. protected $route;
  21. public function add($name, $route, $action, $params = array(), $layout = null)
  22. {
  23. if (!$layout) {
  24. $layout = $this->default_layout;
  25. }
  26. $this->routes[$name] = new Route($route, $action, $params, $layout);
  27. }
  28. public function route($request)
  29. {
  30. $req = explode('/', trim($request, '/'));
  31. foreach ($this->routes as $name => $route) {
  32. if ($route->match($req)) {
  33. $this->route_name = $name;
  34. $this->route = $route;
  35. Env::setParams($route->getParams());
  36. return $this->route;
  37. }
  38. }
  39. return false;
  40. }
  41. public function setDefaultLayout($layout = 'Default')
  42. {
  43. $this->default_layout = $layout;
  44. }
  45. /**
  46. * Sets the name of error page layout
  47. * @param string $layout
  48. */
  49. public function setErrorLayout($layout = 'Error')
  50. {
  51. $this->error_layout = $layout;
  52. }
  53. /**
  54. * Returns error layout name
  55. * @return string Error layout name
  56. */
  57. public function getErrorLayout()
  58. {
  59. return $this->error_layout . 'Layout';
  60. }
  61. public function getRouteName()
  62. {
  63. return $this->route_name;
  64. }
  65. /**
  66. * @param null|string $name
  67. * @return Route
  68. * @throws ErrorException
  69. */
  70. public function getRoute($name = null)
  71. {
  72. if (is_null($name)) {
  73. return $this->route;
  74. } else {
  75. if ($this->routeIsExists($name)) {
  76. return $this->getRouteByName($name);
  77. } else {
  78. throw new ErrorException('Unknown route name: "' . $name . '".');
  79. }
  80. }
  81. }
  82. /**
  83. * @param string $name
  84. * @return bool
  85. */
  86. public function routeIsExists($name)
  87. {
  88. return array_key_exists($name, $this->routes);
  89. }
  90. /**
  91. * @param string $name
  92. * @return Route
  93. */
  94. protected function getRouteByName($name)
  95. {
  96. return $this->routes[$name];
  97. }
  98. }