UrlRule.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. * ```php
  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. * On the rule initialization, the [[pattern]] matching parameters names will be replaced with [[placeholders]].
  43. * @var string the pattern used to parse and create the path info part of a URL.
  44. * @see host
  45. * @see placeholders
  46. */
  47. public $pattern;
  48. /**
  49. * @var string the pattern used to parse and create the host info part of a URL (e.g. `http://example.com`).
  50. * @see pattern
  51. */
  52. public $host;
  53. /**
  54. * @var string the route to the controller action
  55. */
  56. public $route;
  57. /**
  58. * @var array the default GET parameters (name => value) that this rule provides.
  59. * When this rule is used to parse the incoming request, the values declared in this property
  60. * will be injected into $_GET.
  61. */
  62. public $defaults = [];
  63. /**
  64. * @var string the URL suffix used for this rule.
  65. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  66. * If not set, the value of [[UrlManager::suffix]] will be used.
  67. */
  68. public $suffix;
  69. /**
  70. * @var string|array the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
  71. * Use array to represent multiple verbs that this rule may match.
  72. * If this property is not set, the rule can match any verb.
  73. * Note that this property is only used when parsing a request. It is ignored for URL creation.
  74. */
  75. public $verb;
  76. /**
  77. * @var int a value indicating if this rule should be used for both request parsing and URL creation,
  78. * parsing only, or creation only.
  79. * If not set or 0, it means the rule is both request parsing and URL creation.
  80. * If it is [[PARSING_ONLY]], the rule is for request parsing only.
  81. * If it is [[CREATION_ONLY]], the rule is for URL creation only.
  82. */
  83. public $mode;
  84. /**
  85. * @var bool a value indicating if parameters should be url encoded.
  86. */
  87. public $encodeParams = true;
  88. /**
  89. * @var UrlNormalizer|array|false|null the configuration for [[UrlNormalizer]] used by this rule.
  90. * If `null`, [[UrlManager::normalizer]] will be used, if `false`, normalization will be skipped
  91. * for this rule.
  92. * @since 2.0.10
  93. */
  94. public $normalizer;
  95. /**
  96. * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]].
  97. * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders.
  98. * This array contains relations between the original parameters names and their placeholders.
  99. * The array keys are the placeholders and the values are the original names.
  100. *
  101. * @see parseRequest()
  102. * @see createUrl()
  103. * @since 2.0.7
  104. */
  105. protected $placeholders = [];
  106. /**
  107. * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
  108. */
  109. private $_template;
  110. /**
  111. * @var string the regex for matching the route part. This is used in generating URL.
  112. */
  113. private $_routeRule;
  114. /**
  115. * @var array list of regex for matching parameters. This is used in generating URL.
  116. */
  117. private $_paramRules = [];
  118. /**
  119. * @var array list of parameters used in the route.
  120. */
  121. private $_routeParams = [];
  122. /**
  123. * @return string
  124. * @since 2.0.11
  125. */
  126. public function __toString()
  127. {
  128. $str = '';
  129. if ($this->verb !== null) {
  130. $str .= implode(',', $this->verb) . ' ';
  131. }
  132. if ($this->host !== null && strrpos($this->name, $this->host) === false) {
  133. $str .= $this->host . '/';
  134. }
  135. $str .= $this->name;
  136. if ($str === '') {
  137. return '/';
  138. }
  139. return $str;
  140. }
  141. /**
  142. * Initializes this rule.
  143. */
  144. public function init()
  145. {
  146. if ($this->pattern === null) {
  147. throw new InvalidConfigException('UrlRule::pattern must be set.');
  148. }
  149. if ($this->route === null) {
  150. throw new InvalidConfigException('UrlRule::route must be set.');
  151. }
  152. if (is_array($this->normalizer)) {
  153. $normalizerConfig = array_merge(['class' => UrlNormalizer::className()], $this->normalizer);
  154. $this->normalizer = Yii::createObject($normalizerConfig);
  155. }
  156. if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
  157. throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
  158. }
  159. if ($this->verb !== null) {
  160. if (is_array($this->verb)) {
  161. foreach ($this->verb as $i => $verb) {
  162. $this->verb[$i] = strtoupper($verb);
  163. }
  164. } else {
  165. $this->verb = [strtoupper($this->verb)];
  166. }
  167. }
  168. if ($this->name === null) {
  169. $this->name = $this->pattern;
  170. }
  171. $this->pattern = $this->trimSlashes($this->pattern);
  172. $this->route = trim($this->route, '/');
  173. if ($this->host !== null) {
  174. $this->host = rtrim($this->host, '/');
  175. $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
  176. } elseif ($this->pattern === '') {
  177. $this->_template = '';
  178. $this->pattern = '#^$#u';
  179. return;
  180. } elseif (($pos = strpos($this->pattern, '://')) !== false) {
  181. if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
  182. $this->host = substr($this->pattern, 0, $pos2);
  183. } else {
  184. $this->host = $this->pattern;
  185. }
  186. } elseif (strpos($this->pattern, '//') === 0) {
  187. if (($pos2 = strpos($this->pattern, '/', $pos + 2)) !== false) {
  188. $this->host = substr($this->pattern, 0, $pos2);
  189. } else {
  190. $this->host = $this->pattern;
  191. }
  192. } else {
  193. $this->pattern = '/' . $this->pattern . '/';
  194. }
  195. if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
  196. foreach ($matches[1] as $name) {
  197. $this->_routeParams[$name] = "<$name>";
  198. }
  199. }
  200. $tr = [
  201. '.' => '\\.',
  202. '*' => '\\*',
  203. '$' => '\\$',
  204. '[' => '\\[',
  205. ']' => '\\]',
  206. '(' => '\\(',
  207. ')' => '\\)',
  208. ];
  209. $tr2 = [];
  210. if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
  211. foreach ($matches as $match) {
  212. $name = $match[1][0];
  213. $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
  214. $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
  215. $this->placeholders[$placeholder] = $name;
  216. if (array_key_exists($name, $this->defaults)) {
  217. $length = strlen($match[0][0]);
  218. $offset = $match[0][1];
  219. if ($offset > 1 && $this->pattern[$offset - 1] === '/' && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')) {
  220. $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
  221. } else {
  222. $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
  223. }
  224. } else {
  225. $tr["<$name>"] = "(?P<$placeholder>$pattern)";
  226. }
  227. if (isset($this->_routeParams[$name])) {
  228. $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
  229. } else {
  230. $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
  231. }
  232. }
  233. }
  234. $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
  235. $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
  236. // if host starts with relative scheme, then insert pattern to match any
  237. if (strpos($this->host, '//') === 0) {
  238. $this->pattern = substr_replace($this->pattern, '[\w]+://', 2, 0);
  239. }
  240. if (!empty($this->_routeParams)) {
  241. $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
  242. }
  243. }
  244. /**
  245. * @param UrlManager $manager the URL manager
  246. * @return UrlNormalizer|null
  247. * @since 2.0.10
  248. */
  249. protected function getNormalizer($manager)
  250. {
  251. if ($this->normalizer === null) {
  252. return $manager->normalizer;
  253. } else {
  254. return $this->normalizer;
  255. }
  256. }
  257. /**
  258. * @param UrlManager $manager the URL manager
  259. * @return bool
  260. * @since 2.0.10
  261. */
  262. protected function hasNormalizer($manager)
  263. {
  264. return $this->getNormalizer($manager) instanceof UrlNormalizer;
  265. }
  266. /**
  267. * Parses the given request and returns the corresponding route and parameters.
  268. * @param UrlManager $manager the URL manager
  269. * @param Request $request the request component
  270. * @return array|bool the parsing result. The route and the parameters are returned as an array.
  271. * If `false`, it means this rule cannot be used to parse this path info.
  272. */
  273. public function parseRequest($manager, $request)
  274. {
  275. if ($this->mode === self::CREATION_ONLY) {
  276. return false;
  277. }
  278. if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
  279. return false;
  280. }
  281. $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
  282. $pathInfo = $request->getPathInfo();
  283. $normalized = false;
  284. if ($this->hasNormalizer($manager)) {
  285. $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
  286. }
  287. if ($suffix !== '' && $pathInfo !== '') {
  288. $n = strlen($suffix);
  289. if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
  290. $pathInfo = substr($pathInfo, 0, -$n);
  291. if ($pathInfo === '') {
  292. // suffix alone is not allowed
  293. return false;
  294. }
  295. } else {
  296. return false;
  297. }
  298. }
  299. if ($this->host !== null) {
  300. $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
  301. }
  302. if (!preg_match($this->pattern, $pathInfo, $matches)) {
  303. return false;
  304. }
  305. $matches = $this->substitutePlaceholderNames($matches);
  306. foreach ($this->defaults as $name => $value) {
  307. if (!isset($matches[$name]) || $matches[$name] === '') {
  308. $matches[$name] = $value;
  309. }
  310. }
  311. $params = $this->defaults;
  312. $tr = [];
  313. foreach ($matches as $name => $value) {
  314. if (isset($this->_routeParams[$name])) {
  315. $tr[$this->_routeParams[$name]] = $value;
  316. unset($params[$name]);
  317. } elseif (isset($this->_paramRules[$name])) {
  318. $params[$name] = $value;
  319. }
  320. }
  321. if ($this->_routeRule !== null) {
  322. $route = strtr($this->route, $tr);
  323. } else {
  324. $route = $this->route;
  325. }
  326. Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);
  327. if ($normalized) {
  328. // pathInfo was changed by normalizer - we need also normalize route
  329. return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
  330. } else {
  331. return [$route, $params];
  332. }
  333. }
  334. /**
  335. * Creates a URL according to the given route and parameters.
  336. * @param UrlManager $manager the URL manager
  337. * @param string $route the route. It should not have slashes at the beginning or the end.
  338. * @param array $params the parameters
  339. * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL.
  340. */
  341. public function createUrl($manager, $route, $params)
  342. {
  343. if ($this->mode === self::PARSING_ONLY) {
  344. return false;
  345. }
  346. $tr = [];
  347. // match the route part first
  348. if ($route !== $this->route) {
  349. if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
  350. $matches = $this->substitutePlaceholderNames($matches);
  351. foreach ($this->_routeParams as $name => $token) {
  352. if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
  353. $tr[$token] = '';
  354. } else {
  355. $tr[$token] = $matches[$name];
  356. }
  357. }
  358. } else {
  359. return false;
  360. }
  361. }
  362. // match default params
  363. // if a default param is not in the route pattern, its value must also be matched
  364. foreach ($this->defaults as $name => $value) {
  365. if (isset($this->_routeParams[$name])) {
  366. continue;
  367. }
  368. if (!isset($params[$name])) {
  369. // allow omit empty optional params
  370. // @see https://github.com/yiisoft/yii2/issues/10970
  371. if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
  372. $params[$name] = '';
  373. } else {
  374. return false;
  375. }
  376. }
  377. if (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
  378. unset($params[$name]);
  379. if (isset($this->_paramRules[$name])) {
  380. $tr["<$name>"] = '';
  381. }
  382. } elseif (!isset($this->_paramRules[$name])) {
  383. return false;
  384. }
  385. }
  386. // match params in the pattern
  387. foreach ($this->_paramRules as $name => $rule) {
  388. if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
  389. $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
  390. unset($params[$name]);
  391. } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
  392. return false;
  393. }
  394. }
  395. $url = $this->trimSlashes(strtr($this->_template, $tr));
  396. if ($this->host !== null) {
  397. $pos = strpos($url, '/', 8);
  398. if ($pos !== false) {
  399. $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
  400. }
  401. } elseif (strpos($url, '//') !== false) {
  402. $url = preg_replace('#/+#', '/', $url);
  403. }
  404. if ($url !== '') {
  405. $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
  406. }
  407. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  408. $url .= '?' . $query;
  409. }
  410. return $url;
  411. }
  412. /**
  413. * Returns list of regex for matching parameter.
  414. * @return array parameter keys and regexp rules.
  415. *
  416. * @since 2.0.6
  417. */
  418. protected function getParamRules()
  419. {
  420. return $this->_paramRules;
  421. }
  422. /**
  423. * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
  424. * When found - replaces this placeholder key with a appropriate name of matching parameter.
  425. * Used in [[parseRequest()]], [[createUrl()]].
  426. *
  427. * @param array $matches result of `preg_match()` call
  428. * @return array input array with replaced placeholder keys
  429. * @see placeholders
  430. * @since 2.0.7
  431. */
  432. protected function substitutePlaceholderNames(array $matches)
  433. {
  434. foreach ($this->placeholders as $placeholder => $name) {
  435. if (isset($matches[$placeholder])) {
  436. $matches[$name] = $matches[$placeholder];
  437. unset($matches[$placeholder]);
  438. }
  439. }
  440. return $matches;
  441. }
  442. /**
  443. * Trim slashes in passed string. If string begins with '//', two slashes are left as is
  444. * in the beginning of a string.
  445. *
  446. * @param string $string
  447. * @return string
  448. */
  449. private function trimSlashes($string) {
  450. if (strpos($string, '//') === 0) {
  451. return '//' . trim($string, '/');
  452. }
  453. return trim($string, '/');
  454. }
  455. }