RouteCompiler.php 15 KB

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