RouteCompiler.php 10.0 KB

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