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.

114 lines
2.4 KiB

<?php
/**
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage app
* @since 2010-02-25
* @version SVN: $Id$
* @filesource $URL$
*/
class Router
{
protected $routes = array();
protected $route_name;
protected $default_layout = 'Default';
protected $error_layout = 'Error';
/**
* @var Route
*/
protected $route;
public function add($name, $route, $action, $params = array(), $layout = null)
{
if (!$layout) {
$layout = $this->default_layout;
}
$this->routes[$name] = new Route($route, $action, $params, $layout);
}
public function route($request)
{
$req = explode('/', trim($request, '/'));
foreach ($this->routes as $name => $route) {
if ($route->match($req)) {
$this->route_name = $name;
$this->route = $route;
Env::setParams($route->getParams());
return $this->route;
}
}
return false;
}
public function setDefaultLayout($layout = 'Default')
{
$this->default_layout = $layout;
}
/**
* Sets the name of error page layout
* @param string $layout
*/
public function setErrorLayout($layout = 'Error')
{
$this->error_layout = $layout;
}
/**
* Returns error layout name
* @return string Error layout name
*/
public function getErrorLayout()
{
return $this->error_layout . 'Layout';
}
public function getRouteName()
{
return $this->route_name;
}
/**
* @param null|string $name
* @return Route
* @throws ErrorException
*/
public function getRoute($name = null)
{
if (is_null($name)) {
return $this->route;
} else {
if ($this->routeIsExists($name)) {
return $this->getRouteByName($name);
} else {
throw new ErrorException('Unknown route name: "' . $name . '".');
}
}
}
/**
* @param string $name
* @return bool
*/
public function routeIsExists($name)
{
return array_key_exists($name, $this->routes);
}
/**
* @param string $name
* @return Route
*/
protected function getRouteByName($name)
{
return $this->routes[$name];
}
}