UrlManager.php 8.82 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
	 */
	public $enablePrettyUrl = false;
29 30 31 32 33 34
	/**
	 * @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.
	 * This property is used only when [[enablePrettyUrl]] is true.
	 */
	public $enableStrictParsing = false;
Qiang Xue committed
35 36 37
	/**
	 * @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
38 39 40 41 42 43 44 45 46
	 * 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
47
	 * you populate the array with rule objects instead of rule configurations.
Qiang Xue committed
48 49 50 51
	 */
	public $rules = array();
	/**
	 * @var string the URL suffix used when in 'path' format.
Qiang Xue committed
52 53
	 * 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
54
	 */
Qiang Xue committed
55
	public $suffix;
Qiang Xue committed
56 57
	/**
	 * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
Qiang Xue committed
58
	 * This property is used only if [[enablePrettyUrl]] is true.
Qiang Xue committed
59
	 */
60
	public $showScriptName = false;
Qiang Xue committed
61
	/**
Qiang Xue committed
62
	 * @var string the GET variable name for route. This property is used only if [[enablePrettyUrl]] is false.
Qiang Xue committed
63
	 */
Qiang Xue committed
64
	public $routeVar = 'r';
Qiang Xue committed
65
	/**
66 67 68 69 70 71
	 * @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
72
	 */
73
	public $cache = 'cache';
Qiang Xue committed
74
	/**
Qiang Xue committed
75 76
	 * @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
77
	 */
Qiang Xue committed
78 79 80
	public $ruleConfig = array(
		'class' => 'yii\web\UrlRule',
	);
Qiang Xue committed
81 82 83 84

	private $_baseUrl;
	private $_hostInfo;

Qiang Xue committed
85
	/**
86
	 * Initializes UrlManager.
Qiang Xue committed
87 88 89 90
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
91
		$this->compileRules();
Qiang Xue committed
92
	}
Qiang Xue committed
93

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

114 115 116 117 118 119 120
		$rules = array();
		foreach ($this->rules as $key => $rule) {
			if (!is_array($rule)) {
				$rule = array(
					'pattern' => $key,
					'route' => $rule,
				);
Qiang Xue committed
121
			}
Qiang Xue committed
122
			$rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule));
Qiang Xue committed
123
		}
124
		$this->rules = $rules;
Qiang Xue committed
125

Qiang Xue committed
126
		if (isset($key, $hash)) {
127
			$this->cache->set($key, array($this->rules, $hash));
Qiang Xue committed
128
		}
Qiang Xue committed
129 130 131 132
	}

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

148 149 150 151
			if ($this->enableStrictParsing) {
				return false;
			}

Qiang Xue committed
152 153 154 155 156 157 158 159 160
			$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
161 162 163
				} else {
					// suffix doesn't match
					return false;
Qiang Xue committed
164 165 166 167 168
				}
			}

			return array($pathInfo, array());
		} else {
Qiang Xue committed
169 170 171 172 173
			$route = $request->getParam($this->routeVar);
			if (is_array($route)) {
				$route = '';
			}
			return array((string)$route, array());
Qiang Xue committed
174
		}
Qiang Xue committed
175 176
	}

Qiang Xue committed
177 178 179 180 181 182 183
	/**
	 * 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
184 185 186
	public function createUrl($route, $params = array())
	{
		$anchor = isset($params['#']) ? '#' . $params['#'] : '';
187
		unset($params['#'], $params[$this->routeVar]);
Qiang Xue committed
188

Qiang Xue committed
189
		$route = trim($route, '/');
Qiang Xue committed
190
		$baseUrl = $this->getBaseUrl();
Qiang Xue committed
191

Qiang Xue committed
192 193 194 195
		if ($this->enablePrettyUrl) {
			/** @var $rule UrlRule */
			foreach ($this->rules as $rule) {
				if (($url = $rule->createUrl($this, $route, $params)) !== false) {
Qiang Xue committed
196
					if ($rule->host !== null) {
197 198 199 200 201 202 203 204
						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}";
					}
Qiang Xue committed
205
				}
Qiang Xue committed
206 207
			}

Qiang Xue committed
208 209 210
			if ($this->suffix !== null) {
				$route .= $this->suffix;
			}
211
			if (!empty($params)) {
Qiang Xue committed
212 213
				$route .= '?' . http_build_query($params);
			}
214
			return "$baseUrl/{$route}{$anchor}";
Qiang Xue committed
215
		} else {
216
			$url = "$baseUrl?{$this->routeVar}=$route";
217
			if (!empty($params)) {
Qiang Xue committed
218 219 220
				$url .= '&' . http_build_query($params);
			}
			return $url;
Qiang Xue committed
221
		}
Qiang Xue committed
222
	}
Qiang Xue committed
223

Qiang Xue committed
224 225 226 227 228 229 230 231 232
	/**
	 * 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
233
	{
234 235 236 237 238 239
		$url = $this->createUrl($route, $params);
		if (strpos($url, '://') !== false) {
			return $url;
		} else {
			return $this->getHostInfo() . $url;
		}
Qiang Xue committed
240 241 242
	}

	/**
Qiang Xue committed
243 244 245 246
	 * 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
247
	 */
Qiang Xue committed
248
	public function getBaseUrl()
Qiang Xue committed
249
	{
Qiang Xue committed
250 251 252
		if ($this->_baseUrl === null) {
			/** @var $request \yii\web\Request */
			$request = Yii::$app->getRequest();
Qiang Xue committed
253
			$this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
Qiang Xue committed
254
		}
Qiang Xue committed
255 256
		return $this->_baseUrl;
	}
Qiang Xue committed
257

Qiang Xue committed
258 259 260 261
	/**
	 * 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
262 263
	public function setBaseUrl($value)
	{
264
		$this->_baseUrl = rtrim($value, '/');
Qiang Xue committed
265
	}
Qiang Xue committed
266

Qiang Xue committed
267 268 269 270
	/**
	 * 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
271 272 273
	public function getHostInfo()
	{
		if ($this->_hostInfo === null) {
Qiang Xue committed
274
			$this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
Qiang Xue committed
275
		}
Qiang Xue committed
276
		return $this->_hostInfo;
Qiang Xue committed
277 278
	}

Qiang Xue committed
279
	/**
Qiang Xue committed
280 281
	 * 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
282
	 */
Qiang Xue committed
283
	public function setHostInfo($value)
Qiang Xue committed
284
	{
Qiang Xue committed
285
		$this->_hostInfo = rtrim($value, '/');
Qiang Xue committed
286
	}
Qiang Xue committed
287
}