UrlRule.php 21 KB

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