Nenhuma descrição

RouteCompiler.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Routing;
  11. /**
  12. * RouteCompiler compiles Route instances to CompiledRoute instances.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. * @author Tobias Schultze <http://tobion.de>
  16. */
  17. class RouteCompiler implements RouteCompilerInterface
  18. {
  19. public const REGEX_DELIMITER = '#';
  20. /**
  21. * This string defines the characters that are automatically considered separators in front of
  22. * optional placeholders (with default and no static text following). Such a single separator
  23. * can be left out together with the optional placeholder from matching and generating URLs.
  24. */
  25. public const SEPARATORS = '/,;.:-_~+*=@|';
  26. /**
  27. * The maximum supported length of a PCRE subpattern name
  28. * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16.
  29. *
  30. * @internal
  31. */
  32. public const VARIABLE_MAXIMUM_LENGTH = 32;
  33. /**
  34. * {@inheritdoc}
  35. *
  36. * @throws \InvalidArgumentException if a path variable is named _fragment
  37. * @throws \LogicException if a variable is referenced more than once
  38. * @throws \DomainException if a variable name starts with a digit or if it is too long to be successfully used as
  39. * a PCRE subpattern
  40. */
  41. public static function compile(Route $route)
  42. {
  43. $hostVariables = [];
  44. $variables = [];
  45. $hostRegex = null;
  46. $hostTokens = [];
  47. if ('' !== $host = $route->getHost()) {
  48. $result = self::compilePattern($route, $host, true);
  49. $hostVariables = $result['variables'];
  50. $variables = $hostVariables;
  51. $hostTokens = $result['tokens'];
  52. $hostRegex = $result['regex'];
  53. }
  54. $locale = $route->getDefault('_locale');
  55. if (null !== $locale && null !== $route->getDefault('_canonical_route') && preg_quote($locale, self::REGEX_DELIMITER) === $route->getRequirement('_locale')) {
  56. $requirements = $route->getRequirements();
  57. unset($requirements['_locale']);
  58. $route->setRequirements($requirements);
  59. $route->setPath(str_replace('{_locale}', $locale, $route->getPath()));
  60. }
  61. $path = $route->getPath();
  62. $result = self::compilePattern($route, $path, false);
  63. $staticPrefix = $result['staticPrefix'];
  64. $pathVariables = $result['variables'];
  65. foreach ($pathVariables as $pathParam) {
  66. if ('_fragment' === $pathParam) {
  67. throw new \InvalidArgumentException(sprintf('Route pattern "%s" cannot contain "_fragment" as a path parameter.', $route->getPath()));
  68. }
  69. }
  70. $variables = array_merge($variables, $pathVariables);
  71. $tokens = $result['tokens'];
  72. $regex = $result['regex'];
  73. return new CompiledRoute(
  74. $staticPrefix,
  75. $regex,
  76. $tokens,
  77. $pathVariables,
  78. $hostRegex,
  79. $hostTokens,
  80. $hostVariables,
  81. array_unique($variables)
  82. );
  83. }
  84. private static function compilePattern(Route $route, string $pattern, bool $isHost): array
  85. {
  86. $tokens = [];
  87. $variables = [];
  88. $matches = [];
  89. $pos = 0;
  90. $defaultSeparator = $isHost ? '.' : '/';
  91. $useUtf8 = preg_match('//u', $pattern);
  92. $needsUtf8 = $route->getOption('utf8');
  93. if (!$needsUtf8 && $useUtf8 && preg_match('/[\x80-\xFF]/', $pattern)) {
  94. throw new \LogicException(sprintf('Cannot use UTF-8 route patterns without setting the "utf8" option for route "%s".', $route->getPath()));
  95. }
  96. if (!$useUtf8 && $needsUtf8) {
  97. throw new \LogicException(sprintf('Cannot mix UTF-8 requirements with non-UTF-8 pattern "%s".', $pattern));
  98. }
  99. // Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable
  100. // in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself.
  101. preg_match_all('#\{(!)?(\w+)\}#', $pattern, $matches, \PREG_OFFSET_CAPTURE | \PREG_SET_ORDER);
  102. foreach ($matches as $match) {
  103. $important = $match[1][1] >= 0;
  104. $varName = $match[2][0];
  105. // get all static text preceding the current variable
  106. $precedingText = substr($pattern, $pos, $match[0][1] - $pos);
  107. $pos = $match[0][1] + \strlen($match[0][0]);
  108. if (!\strlen($precedingText)) {
  109. $precedingChar = '';
  110. } elseif ($useUtf8) {
  111. preg_match('/.$/u', $precedingText, $precedingChar);
  112. $precedingChar = $precedingChar[0];
  113. } else {
  114. $precedingChar = substr($precedingText, -1);
  115. }
  116. $isSeparator = '' !== $precedingChar && str_contains(static::SEPARATORS, $precedingChar);
  117. // A PCRE subpattern name must start with a non-digit. Also a PHP variable cannot start with a digit so the
  118. // variable would not be usable as a Controller action argument.
  119. if (preg_match('/^\d/', $varName)) {
  120. throw new \DomainException(sprintf('Variable name "%s" cannot start with a digit in route pattern "%s". Please use a different name.', $varName, $pattern));
  121. }
  122. if (\in_array($varName, $variables)) {
  123. throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName));
  124. }
  125. if (\strlen($varName) > self::VARIABLE_MAXIMUM_LENGTH) {
  126. throw new \DomainException(sprintf('Variable name "%s" cannot be longer than %d characters in route pattern "%s". Please use a shorter name.', $varName, self::VARIABLE_MAXIMUM_LENGTH, $pattern));
  127. }
  128. if ($isSeparator && $precedingText !== $precedingChar) {
  129. $tokens[] = ['text', substr($precedingText, 0, -\strlen($precedingChar))];
  130. } elseif (!$isSeparator && '' !== $precedingText) {
  131. $tokens[] = ['text', $precedingText];
  132. }
  133. $regexp = $route->getRequirement($varName);
  134. if (null === $regexp) {
  135. $followingPattern = (string) substr($pattern, $pos);
  136. // Find the next static character after the variable that functions as a separator. By default, this separator and '/'
  137. // are disallowed for the variable. This default requirement makes sure that optional variables can be matched at all
  138. // and that the generating-matching-combination of URLs unambiguous, i.e. the params used for generating the URL are
  139. // the same that will be matched. Example: new Route('/{page}.{_format}', ['_format' => 'html'])
  140. // If {page} would also match the separating dot, {_format} would never match as {page} will eagerly consume everything.
  141. // Also even if {_format} was not optional the requirement prevents that {page} matches something that was originally
  142. // part of {_format} when generating the URL, e.g. _format = 'mobile.html'.
  143. $nextSeparator = self::findNextSeparator($followingPattern, $useUtf8);
  144. $regexp = sprintf(
  145. '[^%s%s]+',
  146. preg_quote($defaultSeparator, self::REGEX_DELIMITER),
  147. $defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) : ''
  148. );
  149. if (('' !== $nextSeparator && !preg_match('#^\{\w+\}#', $followingPattern)) || '' === $followingPattern) {
  150. // When we have a separator, which is disallowed for the variable, we can optimize the regex with a possessive
  151. // quantifier. This prevents useless backtracking of PCRE and improves performance by 20% for matching those patterns.
  152. // Given the above example, there is no point in backtracking into {page} (that forbids the dot) when a dot must follow
  153. // after it. This optimization cannot be applied when the next char is no real separator or when the next variable is
  154. // directly adjacent, e.g. '/{x}{y}'.
  155. $regexp .= '+';
  156. }
  157. } else {
  158. if (!preg_match('//u', $regexp)) {
  159. $useUtf8 = false;
  160. } elseif (!$needsUtf8 && preg_match('/[\x80-\xFF]|(?<!\\\\)\\\\(?:\\\\\\\\)*+(?-i:X|[pP][\{CLMNPSZ]|x\{[A-Fa-f0-9]{3})/', $regexp)) {
  161. throw new \LogicException(sprintf('Cannot use UTF-8 route requirements without setting the "utf8" option for variable "%s" in pattern "%s".', $varName, $pattern));
  162. }
  163. if (!$useUtf8 && $needsUtf8) {
  164. throw new \LogicException(sprintf('Cannot mix UTF-8 requirement with non-UTF-8 charset for variable "%s" in pattern "%s".', $varName, $pattern));
  165. }
  166. $regexp = self::transformCapturingGroupsToNonCapturings($regexp);
  167. }
  168. if ($important) {
  169. $token = ['variable', $isSeparator ? $precedingChar : '', $regexp, $varName, false, true];
  170. } else {
  171. $token = ['variable', $isSeparator ? $precedingChar : '', $regexp, $varName];
  172. }
  173. $tokens[] = $token;
  174. $variables[] = $varName;
  175. }
  176. if ($pos < \strlen($pattern)) {
  177. $tokens[] = ['text', substr($pattern, $pos)];
  178. }
  179. // find the first optional token
  180. $firstOptional = \PHP_INT_MAX;
  181. if (!$isHost) {
  182. for ($i = \count($tokens) - 1; $i >= 0; --$i) {
  183. $token = $tokens[$i];
  184. // variable is optional when it is not important and has a default value
  185. if ('variable' === $token[0] && !($token[5] ?? false) && $route->hasDefault($token[3])) {
  186. $firstOptional = $i;
  187. } else {
  188. break;
  189. }
  190. }
  191. }
  192. // compute the matching regexp
  193. $regexp = '';
  194. for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) {
  195. $regexp .= self::computeRegexp($tokens, $i, $firstOptional);
  196. }
  197. $regexp = self::REGEX_DELIMITER.'^'.$regexp.'$'.self::REGEX_DELIMITER.'sD'.($isHost ? 'i' : '');
  198. // enable Utf8 matching if really required
  199. if ($needsUtf8) {
  200. $regexp .= 'u';
  201. for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) {
  202. if ('variable' === $tokens[$i][0]) {
  203. $tokens[$i][4] = true;
  204. }
  205. }
  206. }
  207. return [
  208. 'staticPrefix' => self::determineStaticPrefix($route, $tokens),
  209. 'regex' => $regexp,
  210. 'tokens' => array_reverse($tokens),
  211. 'variables' => $variables,
  212. ];
  213. }
  214. /**
  215. * Determines the longest static prefix possible for a route.
  216. */
  217. private static function determineStaticPrefix(Route $route, array $tokens): string
  218. {
  219. if ('text' !== $tokens[0][0]) {
  220. return ($route->hasDefault($tokens[0][3]) || '/' === $tokens[0][1]) ? '' : $tokens[0][1];
  221. }
  222. $prefix = $tokens[0][1];
  223. if (isset($tokens[1][1]) && '/' !== $tokens[1][1] && false === $route->hasDefault($tokens[1][3])) {
  224. $prefix .= $tokens[1][1];
  225. }
  226. return $prefix;
  227. }
  228. /**
  229. * Returns the next static character in the Route pattern that will serve as a separator (or the empty string when none available).
  230. */
  231. private static function findNextSeparator(string $pattern, bool $useUtf8): string
  232. {
  233. if ('' == $pattern) {
  234. // return empty string if pattern is empty or false (false which can be returned by substr)
  235. return '';
  236. }
  237. // first remove all placeholders from the pattern so we can find the next real static character
  238. if ('' === $pattern = preg_replace('#\{\w+\}#', '', $pattern)) {
  239. return '';
  240. }
  241. if ($useUtf8) {
  242. preg_match('/^./u', $pattern, $pattern);
  243. }
  244. return str_contains(static::SEPARATORS, $pattern[0]) ? $pattern[0] : '';
  245. }
  246. /**
  247. * Computes the regexp used to match a specific token. It can be static text or a subpattern.
  248. *
  249. * @param array $tokens The route tokens
  250. * @param int $index The index of the current token
  251. * @param int $firstOptional The index of the first optional token
  252. *
  253. * @return string The regexp pattern for a single token
  254. */
  255. private static function computeRegexp(array $tokens, int $index, int $firstOptional): string
  256. {
  257. $token = $tokens[$index];
  258. if ('text' === $token[0]) {
  259. // Text tokens
  260. return preg_quote($token[1], self::REGEX_DELIMITER);
  261. } else {
  262. // Variable tokens
  263. if (0 === $index && 0 === $firstOptional) {
  264. // When the only token is an optional variable token, the separator is required
  265. return sprintf('%s(?P<%s>%s)?', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
  266. } else {
  267. $regexp = sprintf('%s(?P<%s>%s)', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
  268. if ($index >= $firstOptional) {
  269. // Enclose each optional token in a subpattern to make it optional.
  270. // "?:" means it is non-capturing, i.e. the portion of the subject string that
  271. // matched the optional subpattern is not passed back.
  272. $regexp = "(?:$regexp";
  273. $nbTokens = \count($tokens);
  274. if ($nbTokens - 1 == $index) {
  275. // Close the optional subpatterns
  276. $regexp .= str_repeat(')?', $nbTokens - $firstOptional - (0 === $firstOptional ? 1 : 0));
  277. }
  278. }
  279. return $regexp;
  280. }
  281. }
  282. }
  283. private static function transformCapturingGroupsToNonCapturings(string $regexp): string
  284. {
  285. for ($i = 0; $i < \strlen($regexp); ++$i) {
  286. if ('\\' === $regexp[$i]) {
  287. ++$i;
  288. continue;
  289. }
  290. if ('(' !== $regexp[$i] || !isset($regexp[$i + 2])) {
  291. continue;
  292. }
  293. if ('*' === $regexp[++$i] || '?' === $regexp[$i]) {
  294. ++$i;
  295. continue;
  296. }
  297. $regexp = substr_replace($regexp, '?:', $i, 0);
  298. ++$i;
  299. }
  300. return $regexp;
  301. }
  302. }