UrlManager.php 11.7 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\base\InvalidConfigException;
13
use yii\caching\Cache;
Qiang Xue committed
14 15

/**
Qiang Xue committed
16
 * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
Qiang Xue committed
17
 *
18
 * UrlManager is configured as an application component in [[\yii\base\Application]] by default.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 * You can access that instance via `Yii::$app->urlManager`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ~~~
 * 'urlManager' => [
 *     'enablePrettyUrl' => true,
 *     'rules' => [
 *         // your rules go here
 *     ],
 *     // ...
 * ]
 * ~~~
 *
34
 * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend URLs it creates.
35 36
 * @property string $hostInfo The host info (e.g. "http://www.example.com") that is used by
 * [[createAbsoluteUrl()]] to prepend URLs it creates.
37
 *
Qiang Xue committed
38 39 40 41 42
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class UrlManager extends Component
{
Qiang Xue committed
43
	/**
Qiang Xue committed
44 45 46 47
	 * @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
48 49
	 */
	public $enablePrettyUrl = false;
50 51 52
	/**
	 * @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.
Qiang Xue committed
53
	 * Otherwise, the path info part of the request will be treated as the requested route.
54 55 56
	 * This property is used only when [[enablePrettyUrl]] is true.
	 */
	public $enableStrictParsing = false;
Qiang Xue committed
57 58 59
	/**
	 * @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
60 61 62 63 64 65 66 67
	 * 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'`.
	 *
68 69
	 * For RESTful routing the mentioned shortcut format also allows you to specify the
	 * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
70
	 * You can do that  by prepending it to the pattern, separated by space.
71 72 73
	 * 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'`.
74
	 * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
75 76 77 78
	 * 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:
79
	 *
80
	 * ~~~php
Alexander Makarov committed
81
	 * [
82 83 84 85 86 87 88 89
	 *     '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',
Alexander Makarov committed
90
	 * ];
91 92
	 * ~~~
	 *
Qiang Xue committed
93
	 * Note that if you modify this property after the UrlManager object is created, make sure
Qiang Xue committed
94
	 * you populate the array with rule objects instead of rule configurations.
Qiang Xue committed
95
	 */
Alexander Makarov committed
96
	public $rules = [];
Qiang Xue committed
97 98
	/**
	 * @var string the URL suffix used when in 'path' format.
Qiang Xue committed
99 100
	 * 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
101
	 */
Qiang Xue committed
102
	public $suffix;
Qiang Xue committed
103 104
	/**
	 * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
Qiang Xue committed
105
	 * This property is used only if [[enablePrettyUrl]] is true.
Qiang Xue committed
106
	 */
Qiang Xue committed
107
	public $showScriptName = true;
Qiang Xue committed
108
	/**
109
	 * @var string the GET parameter name for route. This property is used only if [[enablePrettyUrl]] is false.
Qiang Xue committed
110
	 */
111
	public $routeParam = 'r';
Qiang Xue committed
112
	/**
113 114 115 116 117 118
	 * @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
119
	 */
120
	public $cache = 'cache';
Qiang Xue committed
121
	/**
Qiang Xue committed
122 123
	 * @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
124
	 */
Alexander Makarov committed
125
	public $ruleConfig = ['class' => 'yii\web\UrlRule'];
Qiang Xue committed
126 127 128 129

	private $_baseUrl;
	private $_hostInfo;

Qiang Xue committed
130
	/**
131
	 * Initializes UrlManager.
Qiang Xue committed
132 133 134 135
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
136
		$this->compileRules();
Qiang Xue committed
137
	}
Qiang Xue committed
138

Qiang Xue committed
139 140 141
	/**
	 * Parses the URL rules.
	 */
Qiang Xue committed
142 143
	protected function compileRules()
	{
144
		if (!$this->enablePrettyUrl || empty($this->rules)) {
Qiang Xue committed
145 146
			return;
		}
Qiang Xue committed
147 148 149
		if (is_string($this->cache)) {
			$this->cache = Yii::$app->getComponent($this->cache);
		}
150
		if ($this->cache instanceof Cache) {
151
			$key = __CLASS__;
Qiang Xue committed
152
			$hash = md5(json_encode($this->rules));
153
			if (($data = $this->cache->get($key)) !== false && isset($data[1]) && $data[1] === $hash) {
Qiang Xue committed
154 155
				$this->rules = $data[0];
				return;
Qiang Xue committed
156
			}
Qiang Xue committed
157
		}
Qiang Xue committed
158

Alexander Makarov committed
159
		$rules = [];
160
		$verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
161 162
		foreach ($this->rules as $key => $rule) {
			if (!is_array($rule)) {
Alexander Makarov committed
163
				$rule = ['route' => $rule];
164
				if (preg_match("/^((?:($verbs),)*($verbs))\\s+(.*)$/", $key, $matches)) {
165 166 167
					$rule['verb'] = explode(',', $matches[1]);
					$rule['mode'] = UrlRule::PARSING_ONLY;
					$key = $matches[4];
168 169
				}
				$rule['pattern'] = $key;
Qiang Xue committed
170
			}
171 172 173 174 175
			$rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
			if (!$rule instanceof UrlRuleInterface) {
				throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
			}
			$rules[] = $rule;
Qiang Xue committed
176
		}
177
		$this->rules = $rules;
Qiang Xue committed
178

Qiang Xue committed
179
		if (isset($key, $hash)) {
Alexander Makarov committed
180
			$this->cache->set($key, [$this->rules, $hash]);
Qiang Xue committed
181
		}
Qiang Xue committed
182 183 184 185
	}

	/**
	 * Parses the user request.
Qiang Xue committed
186 187 188
	 * @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
189
	 */
Qiang Xue committed
190
	public function parseRequest($request)
Qiang Xue committed
191
	{
Qiang Xue committed
192
		if ($this->enablePrettyUrl) {
193
			$pathInfo = $request->getPathInfo();
slavcodev committed
194
			/** @var UrlRule $rule */
Qiang Xue committed
195
			foreach ($this->rules as $rule) {
Qiang Xue committed
196
				if (($result = $rule->parseRequest($this, $request)) !== false) {
Qiang Xue committed
197 198 199 200
					return $result;
				}
			}

201 202 203 204
			if ($this->enableStrictParsing) {
				return false;
			}

Qiang Xue committed
205 206
			Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);

Qiang Xue committed
207
			$suffix = (string)$this->suffix;
Qiang Xue committed
208
			if ($suffix !== '' && $pathInfo !== '') {
Qiang Xue committed
209 210 211 212 213 214 215
				$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
216 217 218
				} else {
					// suffix doesn't match
					return false;
Qiang Xue committed
219 220 221
				}
			}

222
			return [$pathInfo, []];
Qiang Xue committed
223
		} else {
Qiang Xue committed
224
			Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
225
			$route = $request->getQueryParam($this->routeParam, '');
Qiang Xue committed
226 227 228
			if (is_array($route)) {
				$route = '';
			}
Alexander Makarov committed
229
			return [(string)$route, []];
Qiang Xue committed
230
		}
Qiang Xue committed
231 232
	}

Qiang Xue committed
233 234 235
	/**
	 * Creates a URL using the given route and parameters.
	 * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
236
	 * @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2']
Qiang Xue committed
237 238
	 * @return string the created URL
	 */
239
	public function createUrl($params)
Qiang Xue committed
240
	{
241
		$params = (array)$params;
Qiang Xue committed
242
		$anchor = isset($params['#']) ? '#' . $params['#'] : '';
243
		unset($params['#'], $params[$this->routeParam]);
Qiang Xue committed
244

245 246
		$route = trim($params[0], '/');
		unset($params[0]);
Qiang Xue committed
247
		$baseUrl = $this->getBaseUrl();
Qiang Xue committed
248

Qiang Xue committed
249
		if ($this->enablePrettyUrl) {
slavcodev committed
250
			/** @var UrlRule $rule */
Qiang Xue committed
251 252
			foreach ($this->rules as $rule) {
				if (($url = $rule->createUrl($this, $route, $params)) !== false) {
253
					if (strpos($url, '://') !== false) {
254 255 256 257 258 259 260 261
						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
262
				}
Qiang Xue committed
263 264
			}

Qiang Xue committed
265 266 267
			if ($this->suffix !== null) {
				$route .= $this->suffix;
			}
268 269
			if (!empty($params) && ($query = http_build_query($params)) !== '') {
				$route .= '?' . $query;
Qiang Xue committed
270
			}
271
			return "$baseUrl/{$route}{$anchor}";
Qiang Xue committed
272
		} else {
273
			$url = "$baseUrl?{$this->routeParam}=$route";
274 275
			if (!empty($params) && ($query = http_build_query($params)) !== '') {
				$url .= '&' . $query;
Qiang Xue committed
276
			}
277
			return $url . $anchor;
Qiang Xue committed
278
		}
Qiang Xue committed
279
	}
Qiang Xue committed
280

Qiang Xue committed
281 282 283
	/**
	 * Creates an absolute URL using the given route and parameters.
	 * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
284
	 * @param string|array $params route as a string or route and parameters in form of ['route', 'param1' => 'value1', 'param2' => 'value2']
285 286
	 * @param string $schema the schema to use for the url. e.g. 'http' or 'https'. If not specified
	 * the schema of the current request will be used.
Qiang Xue committed
287 288 289
	 * @return string the created URL
	 * @see createUrl()
	 */
290
	public function createAbsoluteUrl($params, $schema = null)
Qiang Xue committed
291
	{
292
		$params = (array)$params;
293
		$url = $this->createUrl($params);
294
		if (strpos($url, '://') === false) {
295
			$url = $this->getHostInfo() . $url;
296
		}
297
		if ($schema && ($pos = strpos($url, '://')) !== false) {
298
			$url = $schema . substr($url, $pos);
299
		}
300
		return $url;
Qiang Xue committed
301 302 303
	}

	/**
Qiang Xue committed
304 305 306 307
	 * 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
308
	 */
Qiang Xue committed
309
	public function getBaseUrl()
Qiang Xue committed
310
	{
Qiang Xue committed
311
		if ($this->_baseUrl === null) {
slavcodev committed
312
			/** @var \yii\web\Request $request */
Qiang Xue committed
313
			$request = Yii::$app->getRequest();
Qiang Xue committed
314
			$this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
Qiang Xue committed
315
		}
Qiang Xue committed
316 317
		return $this->_baseUrl;
	}
Qiang Xue committed
318

Qiang Xue committed
319 320 321 322
	/**
	 * 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
323 324
	public function setBaseUrl($value)
	{
325
		$this->_baseUrl = rtrim($value, '/');
Qiang Xue committed
326
	}
Qiang Xue committed
327

Qiang Xue committed
328 329 330 331
	/**
	 * 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
332 333 334
	public function getHostInfo()
	{
		if ($this->_hostInfo === null) {
Qiang Xue committed
335
			$this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
Qiang Xue committed
336
		}
Qiang Xue committed
337
		return $this->_hostInfo;
Qiang Xue committed
338 339
	}

Qiang Xue committed
340
	/**
Qiang Xue committed
341 342
	 * 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
343
	 */
Qiang Xue committed
344
	public function setHostInfo($value)
Qiang Xue committed
345
	{
Qiang Xue committed
346
		$this->_hostInfo = rtrim($value, '/');
Qiang Xue committed
347
	}
Qiang Xue committed
348
}