Drupal investigation

RouteCompiler.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. 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. 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. const VARIABLE_MAXIMUM_LENGTH = 32;
  33. /**
  34. * {@inheritdoc}
  35. *
  36. * @throws \LogicException If a variable is referenced more than once
  37. * @throws \DomainException If a variable name starts with a digit or if it is too long to be successfully used as
  38. * a PCRE subpattern.
  39. */
  40. public static function compile(Route $route)
  41. {
  42. $hostVariables = array();
  43. $variables = array();
  44. $hostRegex = null;
  45. $hostTokens = array();
  46. if ('' !== $host = $route->getHost()) {
  47. $result = self::compilePattern($route, $host, true);
  48. $hostVariables = $result['variables'];
  49. $variables = $hostVariables;
  50. $hostTokens = $result['tokens'];
  51. $hostRegex = $result['regex'];
  52. }
  53. $path = $route->getPath();
  54. $result = self::compilePattern($route, $path, false);
  55. $staticPrefix = $result['staticPrefix'];
  56. $pathVariables = $result['variables'];
  57. $variables = array_merge($variables, $pathVariables);
  58. $tokens = $result['tokens'];
  59. $regex = $result['regex'];
  60. return new CompiledRoute(
  61. $staticPrefix,
  62. $regex,
  63. $tokens,
  64. $pathVariables,
  65. $hostRegex,
  66. $hostTokens,
  67. $hostVariables,
  68. array_unique($variables)
  69. );
  70. }
  71. private static function compilePattern(Route $route, $pattern, $isHost)
  72. {
  73. $tokens = array();
  74. $variables = array();
  75. $matches = array();
  76. $pos = 0;
  77. $defaultSeparator = $isHost ? '.' : '/';
  78. // Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable
  79. // in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself.
  80. preg_match_all('#\{\w+\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  81. foreach ($matches as $match) {
  82. $varName = substr($match[0][0], 1, -1);
  83. // get all static text preceding the current variable
  84. $precedingText = substr($pattern, $pos, $match[0][1] - $pos);
  85. $pos = $match[0][1] + strlen($match[0][0]);
  86. $precedingChar = strlen($precedingText) > 0 ? substr($precedingText, -1) : '';
  87. $isSeparator = '' !== $precedingChar && false !== strpos(static::SEPARATORS, $precedingChar);
  88. // A PCRE subpattern name must start with a non-digit. Also a PHP variable cannot start with a digit so the
  89. // variable would not be usable as a Controller action argument.
  90. if (preg_match('/^\d/', $varName)) {
  91. throw new \DomainException(sprintf('Variable name "%s" cannot start with a digit in route pattern "%s". Please use a different name.', $varName, $pattern));
  92. }
  93. if (in_array($varName, $variables)) {
  94. throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName));
  95. }
  96. if (strlen($varName) > self::VARIABLE_MAXIMUM_LENGTH) {
  97. throw new \DomainException(sprintf('Variable name "%s" cannot be longer than %s characters in route pattern "%s". Please use a shorter name.', $varName, self::VARIABLE_MAXIMUM_LENGTH, $pattern));
  98. }
  99. if ($isSeparator && strlen($precedingText) > 1) {
  100. $tokens[] = array('text', substr($precedingText, 0, -1));
  101. } elseif (!$isSeparator && strlen($precedingText) > 0) {
  102. $tokens[] = array('text', $precedingText);
  103. }
  104. $regexp = $route->getRequirement($varName);
  105. if (null === $regexp) {
  106. $followingPattern = (string) substr($pattern, $pos);
  107. // Find the next static character after the variable that functions as a separator. By default, this separator and '/'
  108. // are disallowed for the variable. This default requirement makes sure that optional variables can be matched at all
  109. // and that the generating-matching-combination of URLs unambiguous, i.e. the params used for generating the URL are
  110. // the same that will be matched. Example: new Route('/{page}.{_format}', array('_format' => 'html'))
  111. // If {page} would also match the separating dot, {_format} would never match as {page} will eagerly consume everything.
  112. // Also even if {_format} was not optional the requirement prevents that {page} matches something that was originally
  113. // part of {_format} when generating the URL, e.g. _format = 'mobile.html'.
  114. $nextSeparator = self::findNextSeparator($followingPattern);
  115. $regexp = sprintf(
  116. '[^%s%s]+',
  117. preg_quote($defaultSeparator, self::REGEX_DELIMITER),
  118. $defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) : ''
  119. );
  120. if (('' !== $nextSeparator && !preg_match('#^\{\w+\}#', $followingPattern)) || '' === $followingPattern) {
  121. // When we have a separator, which is disallowed for the variable, we can optimize the regex with a possessive
  122. // quantifier. This prevents useless backtracking of PCRE and improves performance by 20% for matching those patterns.
  123. // Given the above example, there is no point in backtracking into {page} (that forbids the dot) when a dot must follow
  124. // after it. This optimization cannot be applied when the next char is no real separator or when the next variable is
  125. // directly adjacent, e.g. '/{x}{y}'.
  126. $regexp .= '+';
  127. }
  128. }
  129. $tokens[] = array('variable', $isSeparator ? $precedingChar : '', $regexp, $varName);
  130. $variables[] = $varName;
  131. }
  132. if ($pos < strlen($pattern)) {
  133. $tokens[] = array('text', substr($pattern, $pos));
  134. }
  135. // find the first optional token
  136. $firstOptional = PHP_INT_MAX;
  137. if (!$isHost) {
  138. for ($i = count($tokens) - 1; $i >= 0; --$i) {
  139. $token = $tokens[$i];
  140. if ('variable' === $token[0] && $route->hasDefault($token[3])) {
  141. $firstOptional = $i;
  142. } else {
  143. break;
  144. }
  145. }
  146. }
  147. // compute the matching regexp
  148. $regexp = '';
  149. for ($i = 0, $nbToken = count($tokens); $i < $nbToken; ++$i) {
  150. $regexp .= self::computeRegexp($tokens, $i, $firstOptional);
  151. }
  152. return array(
  153. 'staticPrefix' => 'text' === $tokens[0][0] ? $tokens[0][1] : '',
  154. 'regex' => self::REGEX_DELIMITER.'^'.$regexp.'$'.self::REGEX_DELIMITER.'s'.($isHost ? 'i' : ''),
  155. 'tokens' => array_reverse($tokens),
  156. 'variables' => $variables,
  157. );
  158. }
  159. /**
  160. * Returns the next static character in the Route pattern that will serve as a separator.
  161. *
  162. * @param string $pattern The route pattern
  163. *
  164. * @return string The next static character that functions as separator (or empty string when none available)
  165. */
  166. private static function findNextSeparator($pattern)
  167. {
  168. if ('' == $pattern) {
  169. // return empty string if pattern is empty or false (false which can be returned by substr)
  170. return '';
  171. }
  172. // first remove all placeholders from the pattern so we can find the next real static character
  173. $pattern = preg_replace('#\{\w+\}#', '', $pattern);
  174. return isset($pattern[0]) && false !== strpos(static::SEPARATORS, $pattern[0]) ? $pattern[0] : '';
  175. }
  176. /**
  177. * Computes the regexp used to match a specific token. It can be static text or a subpattern.
  178. *
  179. * @param array $tokens The route tokens
  180. * @param int $index The index of the current token
  181. * @param int $firstOptional The index of the first optional token
  182. *
  183. * @return string The regexp pattern for a single token
  184. */
  185. private static function computeRegexp(array $tokens, $index, $firstOptional)
  186. {
  187. $token = $tokens[$index];
  188. if ('text' === $token[0]) {
  189. // Text tokens
  190. return preg_quote($token[1], self::REGEX_DELIMITER);
  191. } else {
  192. // Variable tokens
  193. if (0 === $index && 0 === $firstOptional) {
  194. // When the only token is an optional variable token, the separator is required
  195. return sprintf('%s(?P<%s>%s)?', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
  196. } else {
  197. $regexp = sprintf('%s(?P<%s>%s)', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
  198. if ($index >= $firstOptional) {
  199. // Enclose each optional token in a subpattern to make it optional.
  200. // "?:" means it is non-capturing, i.e. the portion of the subject string that
  201. // matched the optional subpattern is not passed back.
  202. $regexp = "(?:$regexp";
  203. $nbTokens = count($tokens);
  204. if ($nbTokens - 1 == $index) {
  205. // Close the optional subpatterns
  206. $regexp .= str_repeat(')?', $nbTokens - $firstOptional - (0 === $firstOptional ? 1 : 0));
  207. }
  208. }
  209. return $regexp;
  210. }
  211. }
  212. }
  213. }