No Description

RouteCompiler.php 9.8KB

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