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

	private $_baseUrl;
	private $_hostInfo;

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

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

Alexander Makarov committed
158
		$rules = [];
159 160
		foreach ($this->rules as $key => $rule) {
			if (!is_array($rule)) {
Alexander Makarov committed
161
				$rule = ['route' => $rule];
162
				if (preg_match('/^((?:(GET|HEAD|POST|PUT|PATCH|DELETE),)*(GET|HEAD|POST|PUT|PATCH|DELETE))\s+(.*)$/', $key, $matches)) {
163 164 165
					$rule['verb'] = explode(',', $matches[1]);
					$rule['mode'] = UrlRule::PARSING_ONLY;
					$key = $matches[4];
166 167
				}
				$rule['pattern'] = $key;
Qiang Xue committed
168
			}
Qiang Xue committed
169
			$rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule));
Qiang Xue committed
170
		}
171
		$this->rules = $rules;
Qiang Xue committed
172

Qiang Xue committed
173
		if (isset($key, $hash)) {
Alexander Makarov committed
174
			$this->cache->set($key, [$this->rules, $hash]);
Qiang Xue committed
175
		}
Qiang Xue committed
176 177 178 179
	}

	/**
	 * Parses the user request.
Qiang Xue committed
180 181 182
	 * @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
183
	 */
Qiang Xue committed
184
	public function parseRequest($request)
Qiang Xue committed
185
	{
Qiang Xue committed
186
		if ($this->enablePrettyUrl) {
187
			$pathInfo = $request->getPathInfo();
slavcodev committed
188
			/** @var UrlRule $rule */
Qiang Xue committed
189
			foreach ($this->rules as $rule) {
Qiang Xue committed
190
				if (($result = $rule->parseRequest($this, $request)) !== false) {
Qiang Xue committed
191
					Yii::trace("Request parsed with URL rule: {$rule->name}", __METHOD__);
Qiang Xue committed
192 193 194 195
					return $result;
				}
			}

196 197 198 199
			if ($this->enableStrictParsing) {
				return false;
			}

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

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

Alexander Makarov committed
217
			return [$pathInfo, []];
Qiang Xue committed
218
		} else {
Qiang Xue committed
219
			Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
Qiang Xue committed
220
			$route = $request->get($this->routeVar);
Qiang Xue committed
221 222 223
			if (is_array($route)) {
				$route = '';
			}
Alexander Makarov committed
224
			return [(string)$route, []];
Qiang Xue committed
225
		}
Qiang Xue committed
226 227
	}

Qiang Xue committed
228 229 230 231 232 233 234
	/**
	 * 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
	 */
Alexander Makarov committed
235
	public function createUrl($route, $params = [])
Qiang Xue committed
236 237
	{
		$anchor = isset($params['#']) ? '#' . $params['#'] : '';
238
		unset($params['#'], $params[$this->routeVar]);
Qiang Xue committed
239

Qiang Xue committed
240
		$route = trim($route, '/');
Qiang Xue committed
241
		$baseUrl = $this->getBaseUrl();
Qiang Xue committed
242

Qiang Xue committed
243
		if ($this->enablePrettyUrl) {
slavcodev committed
244
			/** @var UrlRule $rule */
Qiang Xue committed
245 246
			foreach ($this->rules as $rule) {
				if (($url = $rule->createUrl($this, $route, $params)) !== false) {
Qiang Xue committed
247
					if ($rule->host !== null) {
248 249 250 251 252 253 254 255
						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
256
				}
Qiang Xue committed
257 258
			}

Qiang Xue committed
259 260 261
			if ($this->suffix !== null) {
				$route .= $this->suffix;
			}
262
			if (!empty($params)) {
Qiang Xue committed
263 264
				$route .= '?' . http_build_query($params);
			}
265
			return "$baseUrl/{$route}{$anchor}";
Qiang Xue committed
266
		} else {
267
			$url = "$baseUrl?{$this->routeVar}=$route";
268
			if (!empty($params)) {
Qiang Xue committed
269 270
				$url .= '&' . http_build_query($params);
			}
271
			return $url . $anchor;
Qiang Xue committed
272
		}
Qiang Xue committed
273
	}
Qiang Xue committed
274

Qiang Xue committed
275 276 277 278 279 280 281 282
	/**
	 * 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()
	 */
Alexander Makarov committed
283
	public function createAbsoluteUrl($route, $params = [])
Qiang Xue committed
284
	{
285 286 287 288 289 290
		$url = $this->createUrl($route, $params);
		if (strpos($url, '://') !== false) {
			return $url;
		} else {
			return $this->getHostInfo() . $url;
		}
Qiang Xue committed
291 292 293
	}

	/**
Qiang Xue committed
294 295 296 297
	 * 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
298
	 */
Qiang Xue committed
299
	public function getBaseUrl()
Qiang Xue committed
300
	{
Qiang Xue committed
301
		if ($this->_baseUrl === null) {
slavcodev committed
302
			/** @var \yii\web\Request $request */
Qiang Xue committed
303
			$request = Yii::$app->getRequest();
Qiang Xue committed
304
			$this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
Qiang Xue committed
305
		}
Qiang Xue committed
306 307
		return $this->_baseUrl;
	}
Qiang Xue committed
308

Qiang Xue committed
309 310 311 312
	/**
	 * 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
313 314
	public function setBaseUrl($value)
	{
315
		$this->_baseUrl = rtrim($value, '/');
Qiang Xue committed
316
	}
Qiang Xue committed
317

Qiang Xue committed
318 319 320 321
	/**
	 * 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
322 323 324
	public function getHostInfo()
	{
		if ($this->_hostInfo === null) {
Qiang Xue committed
325
			$this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
Qiang Xue committed
326
		}
Qiang Xue committed
327
		return $this->_hostInfo;
Qiang Xue committed
328 329
	}

Qiang Xue committed
330
	/**
Qiang Xue committed
331 332
	 * 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
333
	 */
Qiang Xue committed
334
	public function setHostInfo($value)
Qiang Xue committed
335
	{
Qiang Xue committed
336
		$this->_hostInfo = rtrim($value, '/');
Qiang Xue committed
337
	}
Qiang Xue committed
338
}