You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

345 lines
12KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\Object;
  10. use yii\base\InvalidConfigException;
  11. /**
  12. * UrlRule represents a rule used by [[UrlManager]] for parsing and generating URLs.
  13. *
  14. * To define your own URL parsing and creation logic you can extend from this class
  15. * and add it to [[UrlManager::rules]] like this:
  16. *
  17. * ~~~
  18. * 'rules' => [
  19. * ['class' => 'MyUrlRule', 'pattern' => '...', 'route' => 'site/index', ...],
  20. * // ...
  21. * ]
  22. * ~~~
  23. *
  24. * @author Qiang Xue <qiang.xue@gmail.com>
  25. * @since 2.0
  26. */
  27. class UrlRule extends Object implements UrlRuleInterface
  28. {
  29. /**
  30. * Set [[mode]] with this value to mark that this rule is for URL parsing only
  31. */
  32. const PARSING_ONLY = 1;
  33. /**
  34. * Set [[mode]] with this value to mark that this rule is for URL creation only
  35. */
  36. const CREATION_ONLY = 2;
  37. /**
  38. * @var string the name of this rule. If not set, it will use [[pattern]] as the name.
  39. */
  40. public $name;
  41. /**
  42. * @var string the pattern used to parse and create the path info part of a URL.
  43. * @see host
  44. */
  45. public $pattern;
  46. /**
  47. * @var string the pattern used to parse and create the host info part of a URL (e.g. `http://example.com`).
  48. * @see pattern
  49. */
  50. public $host;
  51. /**
  52. * @var string the route to the controller action
  53. */
  54. public $route;
  55. /**
  56. * @var array the default GET parameters (name => value) that this rule provides.
  57. * When this rule is used to parse the incoming request, the values declared in this property
  58. * will be injected into $_GET.
  59. */
  60. public $defaults = [];
  61. /**
  62. * @var string the URL suffix used for this rule.
  63. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  64. * If not, the value of [[UrlManager::suffix]] will be used.
  65. */
  66. public $suffix;
  67. /**
  68. * @var string|array the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
  69. * Use array to represent multiple verbs that this rule may match.
  70. * If this property is not set, the rule can match any verb.
  71. * Note that this property is only used when parsing a request. It is ignored for URL creation.
  72. */
  73. public $verb;
  74. /**
  75. * @var integer a value indicating if this rule should be used for both request parsing and URL creation,
  76. * parsing only, or creation only.
  77. * If not set or 0, it means the rule is both request parsing and URL creation.
  78. * If it is [[PARSING_ONLY]], the rule is for request parsing only.
  79. * If it is [[CREATION_ONLY]], the rule is for URL creation only.
  80. */
  81. public $mode;
  82. /**
  83. * @var boolean a value indicating if parameters should be url encoded.
  84. */
  85. public $encodeParams = true;
  86. /**
  87. * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
  88. */
  89. private $_template;
  90. /**
  91. * @var string the regex for matching the route part. This is used in generating URL.
  92. */
  93. private $_routeRule;
  94. /**
  95. * @var array list of regex for matching parameters. This is used in generating URL.
  96. */
  97. private $_paramRules = [];
  98. /**
  99. * @var array list of parameters used in the route.
  100. */
  101. private $_routeParams = [];
  102. /**
  103. * Initializes this rule.
  104. */
  105. public function init()
  106. {
  107. if ($this->pattern === null) {
  108. throw new InvalidConfigException('UrlRule::pattern must be set.');
  109. }
  110. if ($this->route === null) {
  111. throw new InvalidConfigException('UrlRule::route must be set.');
  112. }
  113. if ($this->verb !== null) {
  114. if (is_array($this->verb)) {
  115. foreach ($this->verb as $i => $verb) {
  116. $this->verb[$i] = strtoupper($verb);
  117. }
  118. } else {
  119. $this->verb = [strtoupper($this->verb)];
  120. }
  121. }
  122. if ($this->name === null) {
  123. $this->name = $this->pattern;
  124. }
  125. $this->pattern = trim($this->pattern, '/');
  126. $this->route = trim($this->route, '/');
  127. if ($this->host !== null) {
  128. $this->host = rtrim($this->host, '/');
  129. $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
  130. } elseif ($this->pattern === '') {
  131. $this->_template = '';
  132. $this->pattern = '#^$#u';
  133. return;
  134. } elseif (($pos = strpos($this->pattern, '://')) !== false) {
  135. if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
  136. $this->host = substr($this->pattern, 0, $pos2);
  137. } else {
  138. $this->host = $this->pattern;
  139. }
  140. } else {
  141. $this->pattern = '/' . $this->pattern . '/';
  142. }
  143. if (strpos($this->route, '<') !== false && preg_match_all('/<(\w+)>/', $this->route, $matches)) {
  144. foreach ($matches[1] as $name) {
  145. $this->_routeParams[$name] = "<$name>";
  146. }
  147. }
  148. $tr = [
  149. '.' => '\\.',
  150. '*' => '\\*',
  151. '$' => '\\$',
  152. '[' => '\\[',
  153. ']' => '\\]',
  154. '(' => '\\(',
  155. ')' => '\\)',
  156. ];
  157. $tr2 = [];
  158. if (preg_match_all('/<(\w+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
  159. foreach ($matches as $match) {
  160. $name = $match[1][0];
  161. $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
  162. if (array_key_exists($name, $this->defaults)) {
  163. $length = strlen($match[0][0]);
  164. $offset = $match[0][1];
  165. if ($offset > 1 && $this->pattern[$offset - 1] === '/' && $this->pattern[$offset + $length] === '/') {
  166. $tr["/<$name>"] = "(/(?P<$name>$pattern))?";
  167. } else {
  168. $tr["<$name>"] = "(?P<$name>$pattern)?";
  169. }
  170. } else {
  171. $tr["<$name>"] = "(?P<$name>$pattern)";
  172. }
  173. if (isset($this->_routeParams[$name])) {
  174. $tr2["<$name>"] = "(?P<$name>$pattern)";
  175. } else {
  176. $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
  177. }
  178. }
  179. }
  180. $this->_template = preg_replace('/<(\w+):?([^>]+)?>/', '<$1>', $this->pattern);
  181. $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
  182. if (!empty($this->_routeParams)) {
  183. $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
  184. }
  185. }
  186. /**
  187. * Parses the given request and returns the corresponding route and parameters.
  188. * @param UrlManager $manager the URL manager
  189. * @param Request $request the request component
  190. * @return array|boolean the parsing result. The route and the parameters are returned as an array.
  191. * If false, it means this rule cannot be used to parse this path info.
  192. */
  193. public function parseRequest($manager, $request)
  194. {
  195. if ($this->mode === self::CREATION_ONLY) {
  196. return false;
  197. }
  198. if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
  199. return false;
  200. }
  201. $pathInfo = $request->getPathInfo();
  202. $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix);
  203. if ($suffix !== '' && $pathInfo !== '') {
  204. $n = strlen($suffix);
  205. if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
  206. $pathInfo = substr($pathInfo, 0, -$n);
  207. if ($pathInfo === '') {
  208. // suffix alone is not allowed
  209. return false;
  210. }
  211. } else {
  212. return false;
  213. }
  214. }
  215. if ($this->host !== null) {
  216. $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
  217. }
  218. if (!preg_match($this->pattern, $pathInfo, $matches)) {
  219. return false;
  220. }
  221. foreach ($this->defaults as $name => $value) {
  222. if (!isset($matches[$name]) || $matches[$name] === '') {
  223. $matches[$name] = $value;
  224. }
  225. }
  226. $params = $this->defaults;
  227. $tr = [];
  228. foreach ($matches as $name => $value) {
  229. if (isset($this->_routeParams[$name])) {
  230. $tr[$this->_routeParams[$name]] = $value;
  231. unset($params[$name]);
  232. } elseif (isset($this->_paramRules[$name])) {
  233. $params[$name] = $value;
  234. }
  235. }
  236. if ($this->_routeRule !== null) {
  237. $route = strtr($this->route, $tr);
  238. } else {
  239. $route = $this->route;
  240. }
  241. Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);
  242. return [$route, $params];
  243. }
  244. /**
  245. * Creates a URL according to the given route and parameters.
  246. * @param UrlManager $manager the URL manager
  247. * @param string $route the route. It should not have slashes at the beginning or the end.
  248. * @param array $params the parameters
  249. * @return string|boolean the created URL, or false if this rule cannot be used for creating this URL.
  250. */
  251. public function createUrl($manager, $route, $params)
  252. {
  253. if ($this->mode === self::PARSING_ONLY) {
  254. return false;
  255. }
  256. $tr = [];
  257. // match the route part first
  258. if ($route !== $this->route) {
  259. if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
  260. foreach ($this->_routeParams as $name => $token) {
  261. if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
  262. $tr[$token] = '';
  263. } else {
  264. $tr[$token] = $matches[$name];
  265. }
  266. }
  267. } else {
  268. return false;
  269. }
  270. }
  271. // match default params
  272. // if a default param is not in the route pattern, its value must also be matched
  273. foreach ($this->defaults as $name => $value) {
  274. if (isset($this->_routeParams[$name])) {
  275. continue;
  276. }
  277. if (!isset($params[$name])) {
  278. return false;
  279. } elseif (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
  280. unset($params[$name]);
  281. if (isset($this->_paramRules[$name])) {
  282. $tr["<$name>"] = '';
  283. }
  284. } elseif (!isset($this->_paramRules[$name])) {
  285. return false;
  286. }
  287. }
  288. // match params in the pattern
  289. foreach ($this->_paramRules as $name => $rule) {
  290. if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
  291. $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
  292. unset($params[$name]);
  293. } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
  294. return false;
  295. }
  296. }
  297. $url = trim(strtr($this->_template, $tr), '/');
  298. if ($this->host !== null) {
  299. $pos = strpos($url, '/', 8);
  300. if ($pos !== false) {
  301. $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
  302. }
  303. } elseif (strpos($url, '//') !== false) {
  304. $url = preg_replace('#/+#', '/', $url);
  305. }
  306. if ($url !== '') {
  307. $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
  308. }
  309. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  310. $url .= '?' . $query;
  311. }
  312. return $url;
  313. }
  314. }