UrlManager.php 7.46 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11
<?php
/**
 * UrlManager class file
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

Qiang Xue committed
12
use Yii;
Qiang Xue committed
13
use yii\base\Component;
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 19 20 21 22
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class UrlManager extends Component
{
Qiang Xue committed
23
	/**
Qiang Xue committed
24 25 26 27
	 * @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
28 29 30 31 32 33 34
	 */
	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
	 * is the configuration of creating a single URL rule whose class by default is [[defaultRuleClass]].
	 * If you modify this property after the UrlManager object is created, make sure
Qiang Xue committed
35
	 * you populate the array with rule objects instead of rule configurations.
Qiang Xue committed
36 37 38 39
	 */
	public $rules = array();
	/**
	 * @var string the URL suffix used when in 'path' format.
Qiang Xue committed
40 41
	 * 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
42
	 */
Qiang Xue committed
43
	public $suffix;
Qiang Xue committed
44 45
	/**
	 * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
Qiang Xue committed
46
	 * This property is used only if [[enablePrettyUrl]] is true.
Qiang Xue committed
47 48 49
	 */
	public $showScriptName = true;
	/**
Qiang Xue committed
50
	 * @var string the GET variable name for route. This property is used only if [[enablePrettyUrl]] is false.
Qiang Xue committed
51
	 */
Qiang Xue committed
52
	public $routeVar = 'r';
Qiang Xue committed
53
	/**
Qiang Xue committed
54 55
	 * @var string the ID of the cache component that is used to cache the parsed URL rules.
	 * Defaults to 'cache' which refers to the primary cache component registered with the application.
Qiang Xue committed
56
	 * Set this property to false if you do not want to cache the URL rules.
Qiang Xue committed
57 58 59
	 */
	public $cacheID = 'cache';
	/**
Qiang Xue committed
60 61
	 * @var string the default class name for creating URL rule instances
	 * when it is not specified in [[rules]].
Qiang Xue committed
62
	 */
Qiang Xue committed
63
	public $defaultRuleClass = 'yii\web\UrlRule';
Qiang Xue committed
64 65 66 67

	private $_baseUrl;
	private $_hostInfo;

Qiang Xue committed
68 69 70 71 72 73 74

	/**
	 * Initializes the application component.
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
75
		$this->compileRules();
Qiang Xue committed
76
	}
Qiang Xue committed
77

Qiang Xue committed
78 79 80
	/**
	 * Parses the URL rules.
	 */
Qiang Xue committed
81 82
	protected function compileRules()
	{
Qiang Xue committed
83 84 85
		if (!$this->enablePrettyUrl || $this->rules === array()) {
			return;
		}
Qiang Xue committed
86 87 88 89 90 91 92 93 94
		/**
		 * @var $cache \yii\caching\Cache
		 */
		if ($this->cacheID !== false && ($cache = Yii::$app->getComponent($this->cacheID)) !== null) {
			$key = $cache->buildKey(__CLASS__);
			$hash = md5(json_encode($this->rules));
			if (($data = $cache->get($key)) !== false && isset($data[1]) && $data[1] === $hash) {
				$this->rules = $data[0];
				return;
Qiang Xue committed
95
			}
Qiang Xue committed
96
		}
Qiang Xue committed
97

Qiang Xue committed
98 99 100
		foreach ($this->rules as $i => $rule) {
			if (!isset($rule['class'])) {
				$rule['class'] = $this->defaultRuleClass;
Qiang Xue committed
101
			}
Qiang Xue committed
102 103 104 105 106
			$this->rules[$i] = Yii::createObject($rule);
		}

		if (isset($cache)) {
			$cache->set($key, array($this->rules, $hash));
Qiang Xue committed
107
		}
Qiang Xue committed
108 109 110 111
	}

	/**
	 * Parses the user request.
Qiang Xue committed
112 113 114
	 * @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
115
	 */
Qiang Xue committed
116
	public function parseRequest($request)
Qiang Xue committed
117
	{
Qiang Xue committed
118 119 120 121
		if ($this->enablePrettyUrl) {
			$pathInfo = $request->pathInfo;
			/** @var $rule UrlRule */
			foreach ($this->rules as $rule) {
Qiang Xue committed
122
				if (($result = $rule->parseRequest($this, $request)) !== false) {
Qiang Xue committed
123 124 125 126 127 128 129 130 131 132 133 134 135
					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
136 137 138
				} else {
					// suffix doesn't match
					return false;
Qiang Xue committed
139 140 141 142 143
				}
			}

			return array($pathInfo, array());
		} else {
Qiang Xue committed
144 145 146 147 148
			$route = $request->getParam($this->routeVar);
			if (is_array($route)) {
				$route = '';
			}
			return array((string)$route, array());
Qiang Xue committed
149
		}
Qiang Xue committed
150 151
	}

Qiang Xue committed
152 153 154 155 156 157 158
	/**
	 * 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
159 160 161
	public function createUrl($route, $params = array())
	{
		$anchor = isset($params['#']) ? '#' . $params['#'] : '';
Qiang Xue committed
162
		unset($params['#']);
Qiang Xue committed
163

Qiang Xue committed
164
		$route = trim($route, '/');
Qiang Xue committed
165
		$baseUrl = $this->getBaseUrl();
Qiang Xue committed
166

Qiang Xue committed
167 168 169 170
		if ($this->enablePrettyUrl) {
			/** @var $rule UrlRule */
			foreach ($this->rules as $rule) {
				if (($url = $rule->createUrl($this, $route, $params)) !== false) {
Qiang Xue committed
171
					return rtrim($baseUrl, '/') . '/' . $url . $anchor;
Qiang Xue committed
172
				}
Qiang Xue committed
173 174
			}

Qiang Xue committed
175 176 177 178 179 180
			if ($this->suffix !== null) {
				$route .= $this->suffix;
			}
			if ($params !== array()) {
				$route .= '?' . http_build_query($params);
			}
Qiang Xue committed
181
			return rtrim($baseUrl, '/') . '/' . $route . $anchor;
Qiang Xue committed
182
		} else {
Qiang Xue committed
183 184 185 186 187
			$url = $baseUrl . '?' . $this->routeVar . '=' . $route;
			if ($params !== array()) {
				$url .= '&' . http_build_query($params);
			}
			return $url;
Qiang Xue committed
188
		}
Qiang Xue committed
189
	}
Qiang Xue committed
190

Qiang Xue committed
191 192 193 194 195 196 197 198 199
	/**
	 * 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
200
	{
Qiang Xue committed
201
		return $this->getHostInfo() . $this->createUrl($route, $params);
Qiang Xue committed
202 203 204
	}

	/**
Qiang Xue committed
205 206 207 208
	 * 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
209
	 */
Qiang Xue committed
210
	public function getBaseUrl()
Qiang Xue committed
211
	{
Qiang Xue committed
212 213 214
		if ($this->_baseUrl === null) {
			/** @var $request \yii\web\Request */
			$request = Yii::$app->getRequest();
Qiang Xue committed
215
			$this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
Qiang Xue committed
216
		}
Qiang Xue committed
217 218
		return $this->_baseUrl;
	}
Qiang Xue committed
219

Qiang Xue committed
220 221 222 223
	/**
	 * 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
224 225
	public function setBaseUrl($value)
	{
Qiang Xue committed
226
		$this->_baseUrl = $value;
Qiang Xue committed
227
	}
Qiang Xue committed
228

Qiang Xue committed
229 230 231 232
	/**
	 * 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
233 234 235
	public function getHostInfo()
	{
		if ($this->_hostInfo === null) {
Qiang Xue committed
236
			$this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
Qiang Xue committed
237
		}
Qiang Xue committed
238
		return $this->_hostInfo;
Qiang Xue committed
239 240
	}

Qiang Xue committed
241
	/**
Qiang Xue committed
242 243
	 * 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
244
	 */
Qiang Xue committed
245
	public function setHostInfo($value)
Qiang Xue committed
246
	{
Qiang Xue committed
247
		$this->_hostInfo = rtrim($value, '/');
Qiang Xue committed
248
	}
Qiang Xue committed
249
}