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

	private $_baseUrl;
	private $_hostInfo;

Qiang Xue committed
113
	/**
114
	 * Initializes UrlManager.
Qiang Xue committed
115 116 117 118
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
119
		$this->compileRules();
Qiang Xue committed
120
	}
Qiang Xue committed
121

Qiang Xue committed
122 123 124
	/**
	 * Parses the URL rules.
	 */
Qiang Xue committed
125 126
	protected function compileRules()
	{
127
		if (!$this->enablePrettyUrl || empty($this->rules)) {
Qiang Xue committed
128 129
			return;
		}
Qiang Xue committed
130 131 132
		if (is_string($this->cache)) {
			$this->cache = Yii::$app->getComponent($this->cache);
		}
133
		if ($this->cache instanceof Cache) {
134
			$key = __CLASS__;
Qiang Xue committed
135
			$hash = md5(json_encode($this->rules));
136
			if (($data = $this->cache->get($key)) !== false && isset($data[1]) && $data[1] === $hash) {
Qiang Xue committed
137 138
				$this->rules = $data[0];
				return;
Qiang Xue committed
139
			}
Qiang Xue committed
140
		}
Qiang Xue committed
141

Alexander Makarov committed
142
		$rules = [];
143 144
		foreach ($this->rules as $key => $rule) {
			if (!is_array($rule)) {
Alexander Makarov committed
145
				$rule = ['route' => $rule];
146
				if (preg_match('/^((?:(GET|HEAD|POST|PUT|PATCH|DELETE),)*(GET|HEAD|POST|PUT|PATCH|DELETE))\s+(.*)$/', $key, $matches)) {
147 148 149
					$rule['verb'] = explode(',', $matches[1]);
					$rule['mode'] = UrlRule::PARSING_ONLY;
					$key = $matches[4];
150 151
				}
				$rule['pattern'] = $key;
Qiang Xue committed
152
			}
Qiang Xue committed
153
			$rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule));
Qiang Xue committed
154
		}
155
		$this->rules = $rules;
Qiang Xue committed
156

Qiang Xue committed
157
		if (isset($key, $hash)) {
Alexander Makarov committed
158
			$this->cache->set($key, [$this->rules, $hash]);
Qiang Xue committed
159
		}
Qiang Xue committed
160 161 162 163
	}

	/**
	 * Parses the user request.
Qiang Xue committed
164 165 166
	 * @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
167
	 */
Qiang Xue committed
168
	public function parseRequest($request)
Qiang Xue committed
169
	{
Qiang Xue committed
170
		if ($this->enablePrettyUrl) {
171
			$pathInfo = $request->getPathInfo();
Qiang Xue committed
172 173
			/** @var $rule UrlRule */
			foreach ($this->rules as $rule) {
Qiang Xue committed
174
				if (($result = $rule->parseRequest($this, $request)) !== false) {
Qiang Xue committed
175
					Yii::trace("Request parsed with URL rule: {$rule->name}", __METHOD__);
Qiang Xue committed
176 177 178 179
					return $result;
				}
			}

180 181 182 183
			if ($this->enableStrictParsing) {
				return false;
			}

Qiang Xue committed
184
			$suffix = (string)$this->suffix;
Qiang Xue committed
185
			if ($suffix !== '' && $pathInfo !== '') {
Qiang Xue committed
186 187 188 189 190 191 192
				$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
193 194 195
				} else {
					// suffix doesn't match
					return false;
Qiang Xue committed
196 197 198
				}
			}

Qiang Xue committed
199
			Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);
Alexander Makarov committed
200
			return [$pathInfo, []];
Qiang Xue committed
201
		} else {
Qiang Xue committed
202
			$route = $request->get($this->routeVar);
Qiang Xue committed
203 204 205
			if (is_array($route)) {
				$route = '';
			}
Qiang Xue committed
206
			Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
Alexander Makarov committed
207
			return [(string)$route, []];
Qiang Xue committed
208
		}
Qiang Xue committed
209 210
	}

Qiang Xue committed
211 212 213 214 215 216 217
	/**
	 * 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
218
	public function createUrl($route, $params = [])
Qiang Xue committed
219 220
	{
		$anchor = isset($params['#']) ? '#' . $params['#'] : '';
221
		unset($params['#'], $params[$this->routeVar]);
Qiang Xue committed
222

Qiang Xue committed
223
		$route = trim($route, '/');
Qiang Xue committed
224
		$baseUrl = $this->getBaseUrl();
Qiang Xue committed
225

Qiang Xue committed
226 227 228 229
		if ($this->enablePrettyUrl) {
			/** @var $rule UrlRule */
			foreach ($this->rules as $rule) {
				if (($url = $rule->createUrl($this, $route, $params)) !== false) {
Qiang Xue committed
230
					if ($rule->host !== null) {
231 232 233 234 235 236 237 238
						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
239
				}
Qiang Xue committed
240 241
			}

Qiang Xue committed
242 243 244
			if ($this->suffix !== null) {
				$route .= $this->suffix;
			}
245
			if (!empty($params)) {
Qiang Xue committed
246 247
				$route .= '?' . http_build_query($params);
			}
248
			return "$baseUrl/{$route}{$anchor}";
Qiang Xue committed
249
		} else {
250
			$url = "$baseUrl?{$this->routeVar}=$route";
251
			if (!empty($params)) {
Qiang Xue committed
252 253 254
				$url .= '&' . http_build_query($params);
			}
			return $url;
Qiang Xue committed
255
		}
Qiang Xue committed
256
	}
Qiang Xue committed
257

Qiang Xue committed
258 259 260 261 262 263 264 265
	/**
	 * 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
266
	public function createAbsoluteUrl($route, $params = [])
Qiang Xue committed
267
	{
268 269 270 271 272 273
		$url = $this->createUrl($route, $params);
		if (strpos($url, '://') !== false) {
			return $url;
		} else {
			return $this->getHostInfo() . $url;
		}
Qiang Xue committed
274 275 276
	}

	/**
Qiang Xue committed
277 278 279 280
	 * 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
281
	 */
Qiang Xue committed
282
	public function getBaseUrl()
Qiang Xue committed
283
	{
Qiang Xue committed
284 285 286
		if ($this->_baseUrl === null) {
			/** @var $request \yii\web\Request */
			$request = Yii::$app->getRequest();
Qiang Xue committed
287
			$this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
Qiang Xue committed
288
		}
Qiang Xue committed
289 290
		return $this->_baseUrl;
	}
Qiang Xue committed
291

Qiang Xue committed
292 293 294 295
	/**
	 * 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
296 297
	public function setBaseUrl($value)
	{
298
		$this->_baseUrl = rtrim($value, '/');
Qiang Xue committed
299
	}
Qiang Xue committed
300

Qiang Xue committed
301 302 303 304
	/**
	 * 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
305 306 307
	public function getHostInfo()
	{
		if ($this->_hostInfo === null) {
Qiang Xue committed
308
			$this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
Qiang Xue committed
309
		}
Qiang Xue committed
310
		return $this->_hostInfo;
Qiang Xue committed
311 312
	}

Qiang Xue committed
313
	/**
Qiang Xue committed
314 315
	 * 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
316
	 */
Qiang Xue committed
317
	public function setHostInfo($value)
Qiang Xue committed
318
	{
Qiang Xue committed
319
		$this->_hostInfo = rtrim($value, '/');
Qiang Xue committed
320
	}
Qiang Xue committed
321
}