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.

128 lines
2.6 KiB

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