UrlRule.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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\BaseObject;
  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. * @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 BaseObject 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 (strncmp($this->pattern, '//', 2) === 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 (strncmp($this->host, '//', 2) === 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. }
  333. return $this->normalizer;
  334. }
  335. /**
  336. * @param UrlManager $manager the URL manager
  337. * @return bool
  338. * @since 2.0.10
  339. */
  340. protected function hasNormalizer($manager)
  341. {
  342. return $this->getNormalizer($manager) instanceof UrlNormalizer;
  343. }
  344. /**
  345. * Parses the given request and returns the corresponding route and parameters.
  346. * @param UrlManager $manager the URL manager
  347. * @param Request $request the request component
  348. * @return array|bool the parsing result. The route and the parameters are returned as an array.
  349. * If `false`, it means this rule cannot be used to parse this path info.
  350. */
  351. public function parseRequest($manager, $request)
  352. {
  353. if ($this->mode === self::CREATION_ONLY) {
  354. return false;
  355. }
  356. if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
  357. return false;
  358. }
  359. $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix);
  360. $pathInfo = $request->getPathInfo();
  361. $normalized = false;
  362. if ($this->hasNormalizer($manager)) {
  363. $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
  364. }
  365. if ($suffix !== '' && $pathInfo !== '') {
  366. $n = strlen($suffix);
  367. if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
  368. $pathInfo = substr($pathInfo, 0, -$n);
  369. if ($pathInfo === '') {
  370. // suffix alone is not allowed
  371. return false;
  372. }
  373. } else {
  374. return false;
  375. }
  376. }
  377. if ($this->host !== null) {
  378. $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
  379. }
  380. if (!preg_match($this->pattern, $pathInfo, $matches)) {
  381. return false;
  382. }
  383. $matches = $this->substitutePlaceholderNames($matches);
  384. foreach ($this->defaults as $name => $value) {
  385. if (!isset($matches[$name]) || $matches[$name] === '') {
  386. $matches[$name] = $value;
  387. }
  388. }
  389. $params = $this->defaults;
  390. $tr = [];
  391. foreach ($matches as $name => $value) {
  392. if (isset($this->_routeParams[$name])) {
  393. $tr[$this->_routeParams[$name]] = $value;
  394. unset($params[$name]);
  395. } elseif (isset($this->_paramRules[$name])) {
  396. $params[$name] = $value;
  397. }
  398. }
  399. if ($this->_routeRule !== null) {
  400. $route = strtr($this->route, $tr);
  401. } else {
  402. $route = $this->route;
  403. }
  404. Yii::debug("Request parsed with URL rule: {$this->name}", __METHOD__);
  405. if ($normalized) {
  406. // pathInfo was changed by normalizer - we need also normalize route
  407. return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
  408. }
  409. return [$route, $params];
  410. }
  411. /**
  412. * Creates a URL according to the given route and parameters.
  413. * @param UrlManager $manager the URL manager
  414. * @param string $route the route. It should not have slashes at the beginning or the end.
  415. * @param array $params the parameters
  416. * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL.
  417. */
  418. public function createUrl($manager, $route, $params)
  419. {
  420. if ($this->mode === self::PARSING_ONLY) {
  421. $this->createStatus = self::CREATE_STATUS_PARSING_ONLY;
  422. return false;
  423. }
  424. $tr = [];
  425. // match the route part first
  426. if ($route !== $this->route) {
  427. if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
  428. $matches = $this->substitutePlaceholderNames($matches);
  429. foreach ($this->_routeParams as $name => $token) {
  430. if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
  431. $tr[$token] = '';
  432. } else {
  433. $tr[$token] = $matches[$name];
  434. }
  435. }
  436. } else {
  437. $this->createStatus = self::CREATE_STATUS_ROUTE_MISMATCH;
  438. return false;
  439. }
  440. }
  441. // match default params
  442. // if a default param is not in the route pattern, its value must also be matched
  443. foreach ($this->defaults as $name => $value) {
  444. if (isset($this->_routeParams[$name])) {
  445. continue;
  446. }
  447. if (!isset($params[$name])) {
  448. // allow omit empty optional params
  449. // @see https://github.com/yiisoft/yii2/issues/10970
  450. if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
  451. $params[$name] = '';
  452. } else {
  453. $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
  454. return false;
  455. }
  456. }
  457. if (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
  458. unset($params[$name]);
  459. if (isset($this->_paramRules[$name])) {
  460. $tr["<$name>"] = '';
  461. }
  462. } elseif (!isset($this->_paramRules[$name])) {
  463. $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
  464. return false;
  465. }
  466. }
  467. // match params in the pattern
  468. foreach ($this->_paramRules as $name => $rule) {
  469. if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
  470. $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
  471. unset($params[$name]);
  472. } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
  473. $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
  474. return false;
  475. }
  476. }
  477. $url = $this->trimSlashes(strtr($this->_template, $tr));
  478. if ($this->host !== null) {
  479. $pos = strpos($url, '/', 8);
  480. if ($pos !== false) {
  481. $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
  482. }
  483. } elseif (strpos($url, '//') !== false) {
  484. $url = preg_replace('#/+#', '/', trim($url, '/'));
  485. }
  486. if ($url !== '') {
  487. $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
  488. }
  489. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  490. $url .= '?' . $query;
  491. }
  492. $this->createStatus = self::CREATE_STATUS_SUCCESS;
  493. return $url;
  494. }
  495. /**
  496. * Returns status of the URL creation after the last [[createUrl()]] call.
  497. *
  498. * @return null|int Status of the URL creation after the last [[createUrl()]] call. `null` if rule does not provide
  499. * info about create status.
  500. * @see $createStatus
  501. * @since 2.0.12
  502. */
  503. public function getCreateUrlStatus()
  504. {
  505. return $this->createStatus;
  506. }
  507. /**
  508. * Returns list of regex for matching parameter.
  509. * @return array parameter keys and regexp rules.
  510. *
  511. * @since 2.0.6
  512. */
  513. protected function getParamRules()
  514. {
  515. return $this->_paramRules;
  516. }
  517. /**
  518. * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
  519. * When found - replaces this placeholder key with a appropriate name of matching parameter.
  520. * Used in [[parseRequest()]], [[createUrl()]].
  521. *
  522. * @param array $matches result of `preg_match()` call
  523. * @return array input array with replaced placeholder keys
  524. * @see placeholders
  525. * @since 2.0.7
  526. */
  527. protected function substitutePlaceholderNames(array $matches)
  528. {
  529. foreach ($this->placeholders as $placeholder => $name) {
  530. if (isset($matches[$placeholder])) {
  531. $matches[$name] = $matches[$placeholder];
  532. unset($matches[$placeholder]);
  533. }
  534. }
  535. return $matches;
  536. }
  537. /**
  538. * Trim slashes in passed string. If string begins with '//', two slashes are left as is
  539. * in the beginning of a string.
  540. *
  541. * @param string $string
  542. * @return string
  543. */
  544. private function trimSlashes($string)
  545. {
  546. if (strncmp($string, '//', 2) === 0) {
  547. return '//' . trim($string, '/');
  548. }
  549. return trim($string, '/');
  550. }
  551. }