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.

322 lines
10 KiB

12 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
12 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
12 years ago
use Yii;
use yii\base\Component;
use yii\caching\Cache;
12 years ago
/**
* UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
12 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class UrlManager extends Component
{
12 years ago
/**
* @var boolean whether to enable pretty URLs. Instead of putting all parameters in the query
* string part of a URL, pretty URLs allow using path info to represent some of the parameters
* and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of
* "/index.php?r=news/view&id=100".
12 years ago
*/
public $enablePrettyUrl = false;
/**
* @var boolean whether to enable strict parsing. If strict parsing is enabled, the incoming
* requested URL must match at least one of the [[rules]] in order to be treated as a valid request.
11 years ago
* Otherwise, the path info part of the request will be treated as the requested route.
* This property is used only when [[enablePrettyUrl]] is true.
*/
public $enableStrictParsing = false;
/**
12 years ago
* @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is true.
* This property is used only if [[enablePrettyUrl]] is true. Each element in the array
* is the configuration array for creating a single URL rule. The configuration will
* be merged with [[ruleConfig]] first before it is used for creating the rule object.
*
* A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
* and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
* array, one can use the key to represent the pattern and the value the corresponding route.
* For example, `'post/<id:\d+>' => 'post/view'`.
*
* For RESTful routing the mentioned shortcut format also allows you to specify the
* [[UrlRule::verb|HTTP verb]] that the rule should apply for.
* You can do that by prepending it to the pattern, separated by space.
* For example, `'PUT post/<id:\d+>' => 'post/update'`.
* You may specify multiple verbs by separating them with comma
* like this: `'POST,PUT post/index' => 'post/create'`.
* The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
* Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
* so you normally would not specify a verb for normal GET request.
*
* Here is an example configuration for RESTful CRUD controller:
*
* ~~~php
* array(
* 'dashboard' => 'site/index',
*
* 'POST <controller:\w+>s' => '<controller>/create',
* '<controller:\w+>s' => '<controller>/index',
*
* 'PUT <controller:\w+>/<id:\d+>' => '<controller>/update',
* 'DELETE <controller:\w+>/<id:\d+>' => '<controller>/delete',
* '<controller:\w+>/<id:\d+>' => '<controller>/view',
* );
* ~~~
*
* Note that if you modify this property after the UrlManager object is created, make sure
* you populate the array with rule objects instead of rule configurations.
12 years ago
*/
public $rules = array();
/**
* @var string the URL suffix used when in 'path' format.
12 years ago
* For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
* This property is used only if [[enablePrettyUrl]] is true.
12 years ago
*/
12 years ago
public $suffix;
12 years ago
/**
* @var boolean whether to show entry script name in the constructed URL. Defaults to true.
12 years ago
* This property is used only if [[enablePrettyUrl]] is true.
12 years ago
*/
11 years ago
public $showScriptName = true;
12 years ago
/**
* @var string the GET variable name for route. This property is used only if [[enablePrettyUrl]] is false.
12 years ago
*/
12 years ago
public $routeVar = 'r';
12 years ago
/**
* @var Cache|string the cache object or the application component ID of the cache object.
* Compiled URL rules will be cached through this cache object, if it is available.
*
* After the UrlManager object is created, if you want to change this property,
* you should only assign it with a cache object.
* Set this property to null if you do not want to cache the URL rules.
12 years ago
*/
public $cache = 'cache';
12 years ago
/**
* @var array the default configuration of URL rules. Individual rule configurations
* specified via [[rules]] will take precedence when the same property of the rule is configured.
12 years ago
*/
public $ruleConfig = array(
'class' => 'yii\web\UrlRule',
);
private $_baseUrl;
private $_hostInfo;
12 years ago
/**
* Initializes UrlManager.
12 years ago
*/
public function init()
{
parent::init();
$this->compileRules();
12 years ago
}
12 years ago
/**
* Parses the URL rules.
*/
12 years ago
protected function compileRules()
{
if (!$this->enablePrettyUrl || empty($this->rules)) {
return;
}
if (is_string($this->cache)) {
$this->cache = Yii::$app->getComponent($this->cache);
}
if ($this->cache instanceof Cache) {
$key = __CLASS__;
12 years ago
$hash = md5(json_encode($this->rules));
if (($data = $this->cache->get($key)) !== false && isset($data[1]) && $data[1] === $hash) {
12 years ago
$this->rules = $data[0];
return;
12 years ago
}
12 years ago
}
12 years ago
$rules = array();
foreach ($this->rules as $key => $rule) {
if (!is_array($rule)) {
$rule = array(
'route' => $rule,
);
if (preg_match('/^((?:(GET|HEAD|POST|PUT|PATCH|DELETE),)*(GET|HEAD|POST|PUT|PATCH|DELETE))\s+(.*)$/', $key, $matches)) {
$rule['verb'] = explode(',', $matches[1]);
$rule['mode'] = UrlRule::PARSING_ONLY;
$key = $matches[4];
}
$rule['pattern'] = $key;
12 years ago
}
$rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule));
12 years ago
}
$this->rules = $rules;
12 years ago
if (isset($key, $hash)) {
$this->cache->set($key, array($this->rules, $hash));
12 years ago
}
12 years ago
}
/**
* Parses the user request.
12 years ago
* @param Request $request the request component
* @return array|boolean the route and the associated parameters. The latter is always empty
* if [[enablePrettyUrl]] is false. False is returned if the current request cannot be successfully parsed.
12 years ago
*/
12 years ago
public function parseRequest($request)
12 years ago
{
12 years ago
if ($this->enablePrettyUrl) {
$pathInfo = $request->getPathInfo();
12 years ago
/** @var $rule UrlRule */
foreach ($this->rules as $rule) {
if (($result = $rule->parseRequest($this, $request)) !== false) {
Yii::trace("Request parsed with URL rule: {$rule->name}", __METHOD__);
12 years ago
return $result;
}
}
if ($this->enableStrictParsing) {
return false;
}
12 years ago
$suffix = (string)$this->suffix;
11 years ago
if ($suffix !== '' && $pathInfo !== '') {
12 years ago
$n = strlen($this->suffix);
if (substr($pathInfo, -$n) === $this->suffix) {
$pathInfo = substr($pathInfo, 0, -$n);
if ($pathInfo === '') {
// suffix alone is not allowed
return false;
}
} else {
// suffix doesn't match
return false;
12 years ago
}
}
Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);
12 years ago
return array($pathInfo, array());
} else {
$route = $request->get($this->routeVar);
if (is_array($route)) {
$route = '';
}
Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
return array((string)$route, array());
12 years ago
}
12 years ago
}
/**
* Creates a URL using the given route and parameters.
* The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
* @param string $route the route
* @param array $params the parameters (name-value pairs)
* @return string the created URL
*/
12 years ago
public function createUrl($route, $params = array())
{
$anchor = isset($params['#']) ? '#' . $params['#'] : '';
unset($params['#'], $params[$this->routeVar]);
12 years ago
12 years ago
$route = trim($route, '/');
$baseUrl = $this->getBaseUrl();
12 years ago
12 years ago
if ($this->enablePrettyUrl) {
/** @var $rule UrlRule */
foreach ($this->rules as $rule) {
if (($url = $rule->createUrl($this, $route, $params)) !== false) {
if ($rule->host !== null) {
if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
return substr($url, 0, $pos) . $baseUrl . substr($url, $pos);
} else {
return $url . $baseUrl . $anchor;
}
} else {
return "$baseUrl/{$url}{$anchor}";
}
12 years ago
}
12 years ago
}
12 years ago
if ($this->suffix !== null) {
$route .= $this->suffix;
}
if (!empty($params)) {
12 years ago
$route .= '?' . http_build_query($params);
}
return "$baseUrl/{$route}{$anchor}";
12 years ago
} else {
$url = "$baseUrl?{$this->routeVar}=$route";
if (!empty($params)) {
$url .= '&' . http_build_query($params);
}
return $url;
12 years ago
}
12 years ago
}
12 years ago
/**
* Creates an absolute URL using the given route and parameters.
* This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
* @param string $route the route
* @param array $params the parameters (name-value pairs)
* @return string the created URL
* @see createUrl()
*/
public function createAbsoluteUrl($route, $params = array())
12 years ago
{
$url = $this->createUrl($route, $params);
if (strpos($url, '://') !== false) {
return $url;
} else {
return $this->getHostInfo() . $url;
}
12 years ago
}
/**
* Returns the base URL that is used by [[createUrl()]] to prepend URLs it creates.
* It defaults to [[Request::scriptUrl]] if [[showScriptName]] is true or [[enablePrettyUrl]] is false;
* otherwise, it defaults to [[Request::baseUrl]].
* @return string the base URL that is used by [[createUrl()]] to prepend URLs it creates.
12 years ago
*/
12 years ago
public function getBaseUrl()
12 years ago
{
12 years ago
if ($this->_baseUrl === null) {
/** @var $request \yii\web\Request */
$request = Yii::$app->getRequest();
$this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
12 years ago
}
12 years ago
return $this->_baseUrl;
}
12 years ago
/**
* Sets the base URL that is used by [[createUrl()]] to prepend URLs it creates.
* @param string $value the base URL that is used by [[createUrl()]] to prepend URLs it creates.
*/
12 years ago
public function setBaseUrl($value)
{
$this->_baseUrl = rtrim($value, '/');
12 years ago
}
12 years ago
/**
* Returns the host info that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
* @return string the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
*/
12 years ago
public function getHostInfo()
{
if ($this->_hostInfo === null) {
$this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
12 years ago
}
return $this->_hostInfo;
12 years ago
}
12 years ago
/**
* Sets the host info that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
* @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
12 years ago
*/
public function setHostInfo($value)
12 years ago
{
$this->_hostInfo = rtrim($value, '/');
12 years ago
}
12 years ago
}