UrlRule.php 9.01 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 10
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

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

/**
Qiang Xue committed
14
 * UrlRule represents a rule used for parsing and generating URLs.
Qiang Xue committed
15 16 17 18 19 20
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class UrlRule extends Object
{
Qiang Xue committed
21 22 23 24 25 26 27 28 29
	/**
	 * 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
30 31 32 33
	/**
	 * @var string the name of this rule. If not set, it will use [[pattern]] as the name.
	 */
	public $name;
Qiang Xue committed
34
	/**
Qiang Xue committed
35 36
	 * @var string the pattern used to parse and create the path info part of a URL.
	 * @see host
Qiang Xue committed
37
	 */
Qiang Xue committed
38
	public $pattern;
Qiang Xue committed
39 40 41 42 43
	/**
	 * @var string the pattern used to parse and create the host info part of a URL.
	 * @see pattern
	 */
	public $host;
Qiang Xue committed
44 45 46 47
	/**
	 * @var string the route to the controller action
	 */
	public $route;
Qiang Xue committed
48
	/**
resurtm committed
49
	 * @var array the default GET parameters (name => value) that this rule provides.
Qiang Xue committed
50 51 52
	 * When this rule is used to parse the incoming request, the values declared in this property
	 * will be injected into $_GET.
	 */
Qiang Xue committed
53
	public $defaults = array();
Qiang Xue committed
54 55 56 57 58 59 60 61 62 63 64 65 66
	/**
	 * @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
67
	/**
Qiang Xue committed
68
	 * @var integer a value indicating if this rule should be used for both request parsing and URL creation,
Qiang Xue committed
69
	 * parsing only, or creation only.
Qiang Xue committed
70 71
	 * 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
72 73 74
	 * If it is [[CREATION_ONLY]], the rule is for URL creation only.
	 */
	public $mode;
Qiang Xue committed
75

Qiang Xue committed
76 77 78
	/**
	 * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
	 */
Qiang Xue committed
79
	private $_template;
Qiang Xue committed
80 81 82
	/**
	 * @var string the regex for matching the route part. This is used in generating URL.
	 */
Qiang Xue committed
83
	private $_routeRule;
Qiang Xue committed
84 85 86
	/**
	 * @var array list of regex for matching parameters. This is used in generating URL.
	 */
Qiang Xue committed
87
	private $_paramRules = array();
Qiang Xue committed
88 89 90
	/**
	 * @var array list of parameters used in the route.
	 */
Qiang Xue committed
91
	private $_routeParams = array();
Qiang Xue committed
92

Qiang Xue committed
93 94 95
	/**
	 * Initializes this rule.
	 */
Qiang Xue committed
96
	public function init()
Qiang Xue committed
97
	{
Qiang Xue committed
98 99 100 101 102 103
		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
104 105 106 107 108 109 110 111 112
		if ($this->verb !== null) {
			if (is_array($this->verb)) {
				foreach ($this->verb as $i => $verb) {
					$this->verb[$i] = strtoupper($verb);
				}
			} else {
				$this->verb = array(strtoupper($this->verb));
			}
		}
Qiang Xue committed
113 114 115
		if ($this->name === null) {
			$this->name = $this->pattern;
		}
Qiang Xue committed
116

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

Qiang Xue committed
119 120 121
		if ($this->host !== null) {
			$this->pattern = rtrim($this->host, '/') . rtrim('/' . $this->pattern, '/') . '/';
		} elseif ($this->pattern === '') {
Qiang Xue committed
122
			$this->_template = '';
Qiang Xue committed
123 124 125 126 127 128 129 130 131
			$this->pattern = '#^$#u';
			return;
		} 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
132
				$this->_routeParams[$name] = "<$name>";
Qiang Xue committed
133 134 135 136 137 138 139 140 141 142 143
			}
		}

		$tr = $tr2 = array();
		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] : '[^\/]+';
				if (isset($this->defaults[$name])) {
					$length = strlen($match[0][0]);
					$offset = $match[0][1];
144
					if ($offset > 1 && $this->pattern[$offset - 1] === '/' && $this->pattern[$offset + $length] === '/') {
Qiang Xue committed
145
						$tr["/<$name>"] = "(/(?P<$name>$pattern))?";
Qiang Xue committed
146
					} else {
Qiang Xue committed
147
						$tr["<$name>"] = "(?P<$name>$pattern)?";
Qiang Xue committed
148 149 150 151
					}
				} else {
					$tr["<$name>"] = "(?P<$name>$pattern)";
				}
Qiang Xue committed
152
				if (isset($this->_routeParams[$name])) {
Qiang Xue committed
153 154
					$tr2["<$name>"] = "(?P<$name>$pattern)";
				} else {
Qiang Xue committed
155
					$this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#";
Qiang Xue committed
156 157 158 159
				}
			}
		}

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

163
		if (!empty($this->_routeParams)) {
Qiang Xue committed
164
			$this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
Qiang Xue committed
165 166 167
		}
	}

Qiang Xue committed
168
	/**
Qiang Xue committed
169
	 * Parses the given request and returns the corresponding route and parameters.
Qiang Xue committed
170
	 * @param UrlManager $manager the URL manager
Qiang Xue committed
171
	 * @param Request $request the request component
Qiang Xue committed
172 173 174
	 * @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
175
	public function parseRequest($manager, $request)
Qiang Xue committed
176
	{
Qiang Xue committed
177 178 179 180
		if ($this->mode === self::CREATION_ONLY) {
			return false;
		}

181
		if ($this->verb !== null && !in_array($request->getMethod(), $this->verb, true)) {
Qiang Xue committed
182 183 184
			return false;
		}

185
		$pathInfo = $request->getPathInfo();
Qiang Xue committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
		$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;
				}
			} elseif ($suffix !== '/') {
				// we allow the ending '/' to be optional if it is a suffix
				return false;
			}
		}

Qiang Xue committed
201
		if ($this->host !== null) {
202 203 204
			$pathInfo = strtolower($request->getHostInfo()) . '/' . $pathInfo;
		}

Qiang Xue committed
205 206 207
		if (!preg_match($this->pattern, $pathInfo, $matches)) {
			return false;
		}
Qiang Xue committed
208 209 210 211 212
		foreach ($this->defaults as $name => $value) {
			if (!isset($matches[$name]) || $matches[$name] === '') {
				$matches[$name] = $value;
			}
		}
Qiang Xue committed
213 214 215
		$params = $this->defaults;
		$tr = array();
		foreach ($matches as $name => $value) {
Qiang Xue committed
216 217
			if (isset($this->_routeParams[$name])) {
				$tr[$this->_routeParams[$name]] = $value;
Qiang Xue committed
218
				unset($params[$name]);
Qiang Xue committed
219
			} elseif (isset($this->_paramRules[$name])) {
Qiang Xue committed
220
				$params[$name] = $value;
Qiang Xue committed
221 222
			}
		}
Qiang Xue committed
223
		if ($this->_routeRule !== null) {
Qiang Xue committed
224 225 226 227 228
			$route = strtr($this->route, $tr);
		} else {
			$route = $this->route;
		}
		return array($route, $params);
Qiang Xue committed
229 230
	}

Qiang Xue committed
231 232 233 234 235 236 237 238
	/**
	 * 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
239
	{
Qiang Xue committed
240
		if ($this->mode === self::PARSING_ONLY) {
Qiang Xue committed
241 242 243
			return false;
		}

Qiang Xue committed
244 245 246 247
		$tr = array();

		// match the route part first
		if ($route !== $this->route) {
Qiang Xue committed
248 249
			if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
				foreach ($this->_routeParams as $name => $token) {
Qiang Xue committed
250 251 252 253 254
					if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
						$tr[$token] = '';
					} else {
						$tr[$token] = $matches[$name];
					}
Qiang Xue committed
255 256 257 258 259 260 261 262 263
				}
			} 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
264
			if (isset($this->_routeParams[$name])) {
Qiang Xue committed
265 266
				continue;
			}
Qiang Xue committed
267 268 269 270
			if (!isset($params[$name])) {
				return false;
			} elseif (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
				unset($params[$name]);
Qiang Xue committed
271
				if (isset($this->_paramRules[$name])) {
Qiang Xue committed
272 273
					$tr["<$name>"] = '';
				}
Qiang Xue committed
274
			} elseif (!isset($this->_paramRules[$name])) {
Qiang Xue committed
275 276 277 278 279
				return false;
			}
		}

		// match params in the pattern
Qiang Xue committed
280
		foreach ($this->_paramRules as $name => $rule) {
Qiang Xue committed
281 282 283 284 285 286 287 288
			if (isset($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
				$tr["<$name>"] = urlencode($params[$name]);
				unset($params[$name]);
			} elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
				return false;
			}
		}

Qiang Xue committed
289
		$url = trim(strtr($this->_template, $tr), '/');
Qiang Xue committed
290
		if ($this->host !== null) {
291 292 293 294 295
			$pos = strpos($url, '/', 8);
			if ($pos !== false) {
				$url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
			}
		} elseif (strpos($url, '//') !== false) {
Qiang Xue committed
296 297
			$url = preg_replace('#/+#', '/', $url);
		}
Qiang Xue committed
298 299 300 301 302

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

303
		if (!empty($params)) {
Qiang Xue committed
304 305 306 307
			$url .= '?' . http_build_query($params);
		}
		return $url;
	}
Qiang Xue committed
308
}