UrlRule.php 9.75 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;

10
use Yii;
Qiang Xue committed
11
use yii\base\Object;
Qiang Xue committed
12
use yii\base\InvalidConfigException;
Qiang Xue committed
13 14

/**
15 16 17 18 19 20 21 22 23 24 25
 * UrlRule represents a rule used by [[UrlManager]] for parsing and generating URLs.
 *
 * To define your own URL parsing and creation logic you can extend from this class
 * and add it to [[UrlManager::rules]] like this:
 *
 * ~~~
 * 'rules' => [
 *     ['class' => 'MyUrlRule', 'pattern' => '...', 'route' => 'site/index', ...],
 *     // ...
 * ]
 * ~~~
Qiang Xue committed
26 27 28 29
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
30
class UrlRule extends Object implements UrlRuleInterface
Qiang Xue committed
31
{
Qiang Xue committed
32 33 34 35 36 37 38 39 40
	/**
	 * Set [[mode]] with this value to mark that this rule is for URL parsing only
	 */
	const PARSING_ONLY = 1;
	/**
	 * Set [[mode]] with this value to mark that this rule is for URL creation only
	 */
	const CREATION_ONLY = 2;

Qiang Xue committed
41 42 43 44
	/**
	 * @var string the name of this rule. If not set, it will use [[pattern]] as the name.
	 */
	public $name;
Qiang Xue committed
45
	/**
Qiang Xue committed
46 47
	 * @var string the pattern used to parse and create the path info part of a URL.
	 * @see host
Qiang Xue committed
48
	 */
Qiang Xue committed
49
	public $pattern;
Qiang Xue committed
50
	/**
51
	 * @var string the pattern used to parse and create the host info part of a URL (e.g. `http://example.com`).
Qiang Xue committed
52 53 54
	 * @see pattern
	 */
	public $host;
Qiang Xue committed
55 56 57 58
	/**
	 * @var string the route to the controller action
	 */
	public $route;
Qiang Xue committed
59
	/**
resurtm committed
60
	 * @var array the default GET parameters (name => value) that this rule provides.
Qiang Xue committed
61 62 63
	 * When this rule is used to parse the incoming request, the values declared in this property
	 * will be injected into $_GET.
	 */
Alexander Makarov committed
64
	public $defaults = [];
Qiang Xue committed
65 66 67 68 69 70 71 72 73 74 75 76 77
	/**
	 * @var string the URL suffix used for this rule.
	 * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
	 * If not, the value of [[UrlManager::suffix]] will be used.
	 */
	public $suffix;
	/**
	 * @var string|array the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
	 * Use array to represent multiple verbs that this rule may match.
	 * If this property is not set, the rule can match any verb.
	 * Note that this property is only used when parsing a request. It is ignored for URL creation.
	 */
	public $verb;
Qiang Xue committed
78
	/**
Qiang Xue committed
79
	 * @var integer a value indicating if this rule should be used for both request parsing and URL creation,
Qiang Xue committed
80
	 * parsing only, or creation only.
Qiang Xue committed
81 82
	 * If not set or 0, it means the rule is both request parsing and URL creation.
	 * If it is [[PARSING_ONLY]], the rule is for request parsing only.
Qiang Xue committed
83 84 85
	 * If it is [[CREATION_ONLY]], the rule is for URL creation only.
	 */
	public $mode;
Qiang Xue committed
86

Qiang Xue committed
87 88 89
	/**
	 * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
	 */
Qiang Xue committed
90
	private $_template;
Qiang Xue committed
91 92 93
	/**
	 * @var string the regex for matching the route part. This is used in generating URL.
	 */
Qiang Xue committed
94
	private $_routeRule;
Qiang Xue committed
95 96 97
	/**
	 * @var array list of regex for matching parameters. This is used in generating URL.
	 */
Alexander Makarov committed
98
	private $_paramRules = [];
Qiang Xue committed
99 100 101
	/**
	 * @var array list of parameters used in the route.
	 */
Alexander Makarov committed
102
	private $_routeParams = [];
Qiang Xue committed
103

Qiang Xue committed
104 105 106
	/**
	 * Initializes this rule.
	 */
Qiang Xue committed
107
	public function init()
Qiang Xue committed
108
	{
Qiang Xue committed
109 110 111 112 113 114
		if ($this->pattern === null) {
			throw new InvalidConfigException('UrlRule::pattern must be set.');
		}
		if ($this->route === null) {
			throw new InvalidConfigException('UrlRule::route must be set.');
		}
Qiang Xue committed
115 116 117 118 119 120
		if ($this->verb !== null) {
			if (is_array($this->verb)) {
				foreach ($this->verb as $i => $verb) {
					$this->verb[$i] = strtoupper($verb);
				}
			} else {
Alexander Makarov committed
121
				$this->verb = [strtoupper($this->verb)];
Qiang Xue committed
122 123
			}
		}
Qiang Xue committed
124 125 126
		if ($this->name === null) {
			$this->name = $this->pattern;
		}
Qiang Xue committed
127

Qiang Xue committed
128
		$this->pattern = trim($this->pattern, '/');
129

Qiang Xue committed
130
		if ($this->host !== null) {
131 132
			$this->host = rtrim($this->host, '/');
			$this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
Qiang Xue committed
133
		} elseif ($this->pattern === '') {
Qiang Xue committed
134
			$this->_template = '';
Qiang Xue committed
135 136
			$this->pattern = '#^$#u';
			return;
137 138 139 140 141 142
		} elseif (($pos = strpos($this->pattern, '://')) !== false) {
			if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
				$this->host = substr($this->pattern, 0, $pos2);
			} else {
				$this->host = $this->pattern;
			}
Qiang Xue committed
143 144 145 146 147 148 149
		} else {
			$this->pattern = '/' . $this->pattern . '/';
		}

		$this->route = trim($this->route, '/');
		if (strpos($this->route, '<') !== false && preg_match_all('/<(\w+)>/', $this->route, $matches)) {
			foreach ($matches[1] as $name) {
Qiang Xue committed
150
				$this->_routeParams[$name] = "<$name>";
Qiang Xue committed
151 152 153
			}
		}

154 155 156 157 158 159 160 161 162 163
		$tr = [
			'.' => '\\.',
			'*' => '\\*',
			'$' => '\\$',
			'[' => '\\[',
			']' => '\\]',
			'(' => '\\(',
			')' => '\\)',
		];
		$tr2 = [];
Qiang Xue committed
164 165 166 167
		if (preg_match_all('/<(\w+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
			foreach ($matches as $match) {
				$name = $match[1][0];
				$pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
168
				if (array_key_exists($name, $this->defaults)) {
Qiang Xue committed
169 170
					$length = strlen($match[0][0]);
					$offset = $match[0][1];
171
					if ($offset > 1 && $this->pattern[$offset - 1] === '/' && $this->pattern[$offset + $length] === '/') {
Qiang Xue committed
172
						$tr["/<$name>"] = "(/(?P<$name>$pattern))?";
Qiang Xue committed
173
					} else {
Qiang Xue committed
174
						$tr["<$name>"] = "(?P<$name>$pattern)?";
Qiang Xue committed
175 176 177 178
					}
				} else {
					$tr["<$name>"] = "(?P<$name>$pattern)";
				}
Qiang Xue committed
179
				if (isset($this->_routeParams[$name])) {
Qiang Xue committed
180 181
					$tr2["<$name>"] = "(?P<$name>$pattern)";
				} else {
Qiang Xue committed
182
					$this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#";
Qiang Xue committed
183 184 185 186
				}
			}
		}

Qiang Xue committed
187 188
		$this->_template = preg_replace('/<(\w+):?([^>]+)?>/', '<$1>', $this->pattern);
		$this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
Qiang Xue committed
189

190
		if (!empty($this->_routeParams)) {
Qiang Xue committed
191
			$this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
Qiang Xue committed
192 193 194
		}
	}

Qiang Xue committed
195
	/**
Qiang Xue committed
196
	 * Parses the given request and returns the corresponding route and parameters.
Qiang Xue committed
197
	 * @param UrlManager $manager the URL manager
Qiang Xue committed
198
	 * @param Request $request the request component
Qiang Xue committed
199 200 201
	 * @return array|boolean the parsing result. The route and the parameters are returned as an array.
	 * If false, it means this rule cannot be used to parse this path info.
	 */
Qiang Xue committed
202
	public function parseRequest($manager, $request)
Qiang Xue committed
203
	{
Qiang Xue committed
204 205 206 207
		if ($this->mode === self::CREATION_ONLY) {
			return false;
		}

Qiang Xue committed
208
		if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
Qiang Xue committed
209 210 211
			return false;
		}

212
		$pathInfo = $request->getPathInfo();
Qiang Xue committed
213 214 215 216 217 218 219 220 221
		$suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
		if ($suffix !== '' && $pathInfo !== '') {
			$n = strlen($suffix);
			if (substr($pathInfo, -$n) === $suffix) {
				$pathInfo = substr($pathInfo, 0, -$n);
				if ($pathInfo === '') {
					// suffix alone is not allowed
					return false;
				}
Qiang Xue committed
222
			} else {
Qiang Xue committed
223 224 225 226
				return false;
			}
		}

Qiang Xue committed
227
		if ($this->host !== null) {
228
			$pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
229 230
		}

Qiang Xue committed
231 232 233
		if (!preg_match($this->pattern, $pathInfo, $matches)) {
			return false;
		}
Qiang Xue committed
234 235 236 237 238
		foreach ($this->defaults as $name => $value) {
			if (!isset($matches[$name]) || $matches[$name] === '') {
				$matches[$name] = $value;
			}
		}
Qiang Xue committed
239
		$params = $this->defaults;
Alexander Makarov committed
240
		$tr = [];
Qiang Xue committed
241
		foreach ($matches as $name => $value) {
Qiang Xue committed
242 243
			if (isset($this->_routeParams[$name])) {
				$tr[$this->_routeParams[$name]] = $value;
Qiang Xue committed
244
				unset($params[$name]);
Qiang Xue committed
245
			} elseif (isset($this->_paramRules[$name])) {
Qiang Xue committed
246
				$params[$name] = $value;
Qiang Xue committed
247 248
			}
		}
Qiang Xue committed
249
		if ($this->_routeRule !== null) {
Qiang Xue committed
250 251 252 253
			$route = strtr($this->route, $tr);
		} else {
			$route = $this->route;
		}
254 255 256

		Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);

Alexander Makarov committed
257
		return [$route, $params];
Qiang Xue committed
258 259
	}

Qiang Xue committed
260 261 262 263 264 265 266 267
	/**
	 * Creates a URL according to the given route and parameters.
	 * @param UrlManager $manager the URL manager
	 * @param string $route the route. It should not have slashes at the beginning or the end.
	 * @param array $params the parameters
	 * @return string|boolean the created URL, or false if this rule cannot be used for creating this URL.
	 */
	public function createUrl($manager, $route, $params)
Qiang Xue committed
268
	{
Qiang Xue committed
269
		if ($this->mode === self::PARSING_ONLY) {
Qiang Xue committed
270 271 272
			return false;
		}

Alexander Makarov committed
273
		$tr = [];
Qiang Xue committed
274 275 276

		// match the route part first
		if ($route !== $this->route) {
Qiang Xue committed
277 278
			if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
				foreach ($this->_routeParams as $name => $token) {
Qiang Xue committed
279 280 281 282 283
					if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
						$tr[$token] = '';
					} else {
						$tr[$token] = $matches[$name];
					}
Qiang Xue committed
284 285 286 287 288 289 290 291 292
				}
			} else {
				return false;
			}
		}

		// match default params
		// if a default param is not in the route pattern, its value must also be matched
		foreach ($this->defaults as $name => $value) {
Qiang Xue committed
293
			if (isset($this->_routeParams[$name])) {
Qiang Xue committed
294 295
				continue;
			}
Qiang Xue committed
296 297 298 299
			if (!isset($params[$name])) {
				return false;
			} elseif (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
				unset($params[$name]);
Qiang Xue committed
300
				if (isset($this->_paramRules[$name])) {
Qiang Xue committed
301 302
					$tr["<$name>"] = '';
				}
Qiang Xue committed
303
			} elseif (!isset($this->_paramRules[$name])) {
Qiang Xue committed
304 305 306 307 308
				return false;
			}
		}

		// match params in the pattern
Qiang Xue committed
309
		foreach ($this->_paramRules as $name => $rule) {
310
			if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
Qiang Xue committed
311 312 313 314 315 316 317
				$tr["<$name>"] = urlencode($params[$name]);
				unset($params[$name]);
			} elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
				return false;
			}
		}

Qiang Xue committed
318
		$url = trim(strtr($this->_template, $tr), '/');
Qiang Xue committed
319
		if ($this->host !== null) {
320 321 322 323 324
			$pos = strpos($url, '/', 8);
			if ($pos !== false) {
				$url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
			}
		} elseif (strpos($url, '//') !== false) {
Qiang Xue committed
325 326
			$url = preg_replace('#/+#', '/', $url);
		}
Qiang Xue committed
327 328 329 330 331

		if ($url !== '') {
			$url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
		}

332
		if (!empty($params)) {
Qiang Xue committed
333 334 335 336
			$url .= '?' . http_build_query($params);
		}
		return $url;
	}
Qiang Xue committed
337
}