UrlManager.php 8.18 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Component;
12
use yii\caching\Cache;
Qiang Xue committed
13 14

/**
Qiang Xue committed
15
 * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
Qiang Xue committed
16 17 18 19 20 21
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class UrlManager extends Component
{
Qiang Xue committed
22
	/**
Qiang Xue committed
23 24 25 26
	 * @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".
Qiang Xue committed
27 28 29 30 31
	 */
	public $enablePrettyUrl = false;
	/**
	 * @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
Qiang Xue committed
32 33 34 35 36 37 38 39 40
	 * 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'`.
	 *
	 * Note that if you modify this property after the UrlManager object is created, make sure
Qiang Xue committed
41
	 * you populate the array with rule objects instead of rule configurations.
Qiang Xue committed
42 43 44 45
	 */
	public $rules = array();
	/**
	 * @var string the URL suffix used when in 'path' format.
Qiang Xue committed
46 47
	 * 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.
Qiang Xue committed
48
	 */
Qiang Xue committed
49
	public $suffix;
Qiang Xue committed
50 51
	/**
	 * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
Qiang Xue committed
52
	 * This property is used only if [[enablePrettyUrl]] is true.
Qiang Xue committed
53
	 */
54
	public $showScriptName = false;
Qiang Xue committed
55
	/**
Qiang Xue committed
56
	 * @var string the GET variable name for route. This property is used only if [[enablePrettyUrl]] is false.
Qiang Xue committed
57
	 */
Qiang Xue committed
58
	public $routeVar = 'r';
Qiang Xue committed
59
	/**
60 61 62 63 64 65
	 * @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.
Qiang Xue committed
66
	 */
67
	public $cache = 'cache';
Qiang Xue committed
68
	/**
Qiang Xue committed
69 70
	 * @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.
Qiang Xue committed
71
	 */
Qiang Xue committed
72 73 74
	public $ruleConfig = array(
		'class' => 'yii\web\UrlRule',
	);
Qiang Xue committed
75 76 77 78

	private $_baseUrl;
	private $_hostInfo;

Qiang Xue committed
79
	/**
80
	 * Initializes UrlManager.
Qiang Xue committed
81 82 83 84
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
85
		$this->compileRules();
Qiang Xue committed
86
	}
Qiang Xue committed
87

Qiang Xue committed
88 89 90
	/**
	 * Parses the URL rules.
	 */
Qiang Xue committed
91 92
	protected function compileRules()
	{
93
		if (!$this->enablePrettyUrl || empty($this->rules)) {
Qiang Xue committed
94 95
			return;
		}
Qiang Xue committed
96 97 98
		if (is_string($this->cache)) {
			$this->cache = Yii::$app->getComponent($this->cache);
		}
99 100
		if ($this->cache instanceof Cache) {
			$key = $this->cache->buildKey(__CLASS__);
Qiang Xue committed
101
			$hash = md5(json_encode($this->rules));
102
			if (($data = $this->cache->get($key)) !== false && isset($data[1]) && $data[1] === $hash) {
Qiang Xue committed
103 104
				$this->rules = $data[0];
				return;
Qiang Xue committed
105
			}
Qiang Xue committed
106
		}
Qiang Xue committed
107

108 109 110 111 112 113 114
		$rules = array();
		foreach ($this->rules as $key => $rule) {
			if (!is_array($rule)) {
				$rule = array(
					'pattern' => $key,
					'route' => $rule,
				);
Qiang Xue committed
115
			}
Qiang Xue committed
116
			$rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule));
Qiang Xue committed
117
		}
118
		$this->rules = $rules;
Qiang Xue committed
119

Qiang Xue committed
120
		if (isset($key, $hash)) {
121
			$this->cache->set($key, array($this->rules, $hash));
Qiang Xue committed
122
		}
Qiang Xue committed
123 124 125 126
	}

	/**
	 * Parses the user request.
Qiang Xue committed
127 128 129
	 * @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.
Qiang Xue committed
130
	 */
Qiang Xue committed
131
	public function parseRequest($request)
Qiang Xue committed
132
	{
Qiang Xue committed
133 134 135 136
		if ($this->enablePrettyUrl) {
			$pathInfo = $request->pathInfo;
			/** @var $rule UrlRule */
			foreach ($this->rules as $rule) {
Qiang Xue committed
137
				if (($result = $rule->parseRequest($this, $request)) !== false) {
Qiang Xue committed
138 139 140 141 142 143 144 145 146 147 148 149 150
					return $result;
				}
			}

			$suffix = (string)$this->suffix;
			if ($suffix !== '' && $suffix !== '/' && $pathInfo !== '') {
				$n = strlen($this->suffix);
				if (substr($pathInfo, -$n) === $this->suffix) {
					$pathInfo = substr($pathInfo, 0, -$n);
					if ($pathInfo === '') {
						// suffix alone is not allowed
						return false;
					}
Qiang Xue committed
151 152 153
				} else {
					// suffix doesn't match
					return false;
Qiang Xue committed
154 155 156 157 158
				}
			}

			return array($pathInfo, array());
		} else {
Qiang Xue committed
159 160 161 162 163
			$route = $request->getParam($this->routeVar);
			if (is_array($route)) {
				$route = '';
			}
			return array((string)$route, array());
Qiang Xue committed
164
		}
Qiang Xue committed
165 166
	}

Qiang Xue committed
167 168 169 170 171 172 173
	/**
	 * 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
	 */
Qiang Xue committed
174 175 176
	public function createUrl($route, $params = array())
	{
		$anchor = isset($params['#']) ? '#' . $params['#'] : '';
177
		unset($params['#'], $params[$this->routeVar]);
Qiang Xue committed
178

Qiang Xue committed
179
		$route = trim($route, '/');
Qiang Xue committed
180
		$baseUrl = $this->getBaseUrl();
Qiang Xue committed
181

Qiang Xue committed
182 183 184 185
		if ($this->enablePrettyUrl) {
			/** @var $rule UrlRule */
			foreach ($this->rules as $rule) {
				if (($url = $rule->createUrl($this, $route, $params)) !== false) {
Qiang Xue committed
186
					return rtrim($baseUrl, '/') . '/' . $url . $anchor;
Qiang Xue committed
187
				}
Qiang Xue committed
188 189
			}

Qiang Xue committed
190 191 192 193 194 195
			if ($this->suffix !== null) {
				$route .= $this->suffix;
			}
			if ($params !== array()) {
				$route .= '?' . http_build_query($params);
			}
Qiang Xue committed
196
			return rtrim($baseUrl, '/') . '/' . $route . $anchor;
Qiang Xue committed
197
		} else {
Qiang Xue committed
198 199 200 201 202
			$url = $baseUrl . '?' . $this->routeVar . '=' . $route;
			if ($params !== array()) {
				$url .= '&' . http_build_query($params);
			}
			return $url;
Qiang Xue committed
203
		}
Qiang Xue committed
204
	}
Qiang Xue committed
205

Qiang Xue committed
206 207 208 209 210 211 212 213 214
	/**
	 * 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())
Qiang Xue committed
215
	{
Qiang Xue committed
216
		return $this->getHostInfo() . $this->createUrl($route, $params);
Qiang Xue committed
217 218 219
	}

	/**
Qiang Xue committed
220 221 222 223
	 * 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.
Qiang Xue committed
224
	 */
Qiang Xue committed
225
	public function getBaseUrl()
Qiang Xue committed
226
	{
Qiang Xue committed
227 228 229
		if ($this->_baseUrl === null) {
			/** @var $request \yii\web\Request */
			$request = Yii::$app->getRequest();
Qiang Xue committed
230
			$this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
Qiang Xue committed
231
		}
Qiang Xue committed
232 233
		return $this->_baseUrl;
	}
Qiang Xue committed
234

Qiang Xue committed
235 236 237 238
	/**
	 * 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.
	 */
Qiang Xue committed
239 240
	public function setBaseUrl($value)
	{
Qiang Xue committed
241
		$this->_baseUrl = $value;
Qiang Xue committed
242
	}
Qiang Xue committed
243

Qiang Xue committed
244 245 246 247
	/**
	 * 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.
	 */
Qiang Xue committed
248 249 250
	public function getHostInfo()
	{
		if ($this->_hostInfo === null) {
Qiang Xue committed
251
			$this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
Qiang Xue committed
252
		}
Qiang Xue committed
253
		return $this->_hostInfo;
Qiang Xue committed
254 255
	}

Qiang Xue committed
256
	/**
Qiang Xue committed
257 258
	 * 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.
Qiang Xue committed
259
	 */
Qiang Xue committed
260
	public function setHostInfo($value)
Qiang Xue committed
261
	{
Qiang Xue committed
262
		$this->_hostInfo = rtrim($value, '/');
Qiang Xue committed
263
	}
Qiang Xue committed
264
}