UrlRule.php 9.3 KB

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