4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Routing;
15 * RouteCompiler compiles Route instances to CompiledRoute instances.
17 * @author Fabien Potencier <fabien@symfony.com>
18 * @author Tobias Schultze <http://tobion.de>
20 class RouteCompiler implements RouteCompilerInterface
22 const REGEX_DELIMITER = '#';
25 * This string defines the characters that are automatically considered separators in front of
26 * optional placeholders (with default and no static text following). Such a single separator
27 * can be left out together with the optional placeholder from matching and generating URLs.
29 const SEPARATORS = '/,;.:-_~+*=@|';
32 * The maximum supported length of a PCRE subpattern name
33 * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16.
37 const VARIABLE_MAXIMUM_LENGTH = 32;
42 * @throws \LogicException If a variable is referenced more than once
43 * @throws \DomainException If a variable name starts with a digit or if it is too long to be successfully used as
46 public static function compile(Route $route)
48 $hostVariables = array();
51 $hostTokens = array();
53 if ('' !== $host = $route->getHost()) {
54 $result = self::compilePattern($route, $host, true);
56 $hostVariables = $result['variables'];
57 $variables = $hostVariables;
59 $hostTokens = $result['tokens'];
60 $hostRegex = $result['regex'];
63 $path = $route->getPath();
65 $result = self::compilePattern($route, $path, false);
67 $staticPrefix = $result['staticPrefix'];
69 $pathVariables = $result['variables'];
70 $variables = array_merge($variables, $pathVariables);
72 $tokens = $result['tokens'];
73 $regex = $result['regex'];
75 return new CompiledRoute(
83 array_unique($variables)
87 private static function compilePattern(Route $route, $pattern, $isHost)
93 $defaultSeparator = $isHost ? '.' : '/';
95 // Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable
96 // in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself.
97 preg_match_all('#\{\w+\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
98 foreach ($matches as $match) {
99 $varName = substr($match[0][0], 1, -1);
100 // get all static text preceding the current variable
101 $precedingText = substr($pattern, $pos, $match[0][1] - $pos);
102 $pos = $match[0][1] + strlen($match[0][0]);
103 $precedingChar = strlen($precedingText) > 0 ? substr($precedingText, -1) : '';
104 $isSeparator = '' !== $precedingChar && false !== strpos(static::SEPARATORS, $precedingChar);
106 // A PCRE subpattern name must start with a non-digit. Also a PHP variable cannot start with a digit so the
107 // variable would not be usable as a Controller action argument.
108 if (preg_match('/^\d/', $varName)) {
109 throw new \DomainException(sprintf('Variable name "%s" cannot start with a digit in route pattern "%s". Please use a different name.', $varName, $pattern));
111 if (in_array($varName, $variables)) {
112 throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName));
115 if (strlen($varName) > self::VARIABLE_MAXIMUM_LENGTH) {
116 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));
119 if ($isSeparator && strlen($precedingText) > 1) {
120 $tokens[] = array('text', substr($precedingText, 0, -1));
121 } elseif (!$isSeparator && strlen($precedingText) > 0) {
122 $tokens[] = array('text', $precedingText);
125 $regexp = $route->getRequirement($varName);
126 if (null === $regexp) {
127 $followingPattern = (string) substr($pattern, $pos);
128 // Find the next static character after the variable that functions as a separator. By default, this separator and '/'
129 // are disallowed for the variable. This default requirement makes sure that optional variables can be matched at all
130 // and that the generating-matching-combination of URLs unambiguous, i.e. the params used for generating the URL are
131 // the same that will be matched. Example: new Route('/{page}.{_format}', array('_format' => 'html'))
132 // If {page} would also match the separating dot, {_format} would never match as {page} will eagerly consume everything.
133 // Also even if {_format} was not optional the requirement prevents that {page} matches something that was originally
134 // part of {_format} when generating the URL, e.g. _format = 'mobile.html'.
135 $nextSeparator = self::findNextSeparator($followingPattern);
138 preg_quote($defaultSeparator, self::REGEX_DELIMITER),
139 $defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) : ''
141 if (('' !== $nextSeparator && !preg_match('#^\{\w+\}#', $followingPattern)) || '' === $followingPattern) {
142 // When we have a separator, which is disallowed for the variable, we can optimize the regex with a possessive
143 // quantifier. This prevents useless backtracking of PCRE and improves performance by 20% for matching those patterns.
144 // Given the above example, there is no point in backtracking into {page} (that forbids the dot) when a dot must follow
145 // after it. This optimization cannot be applied when the next char is no real separator or when the next variable is
146 // directly adjacent, e.g. '/{x}{y}'.
151 $tokens[] = array('variable', $isSeparator ? $precedingChar : '', $regexp, $varName);
152 $variables[] = $varName;
155 if ($pos < strlen($pattern)) {
156 $tokens[] = array('text', substr($pattern, $pos));
159 // find the first optional token
160 $firstOptional = PHP_INT_MAX;
162 for ($i = count($tokens) - 1; $i >= 0; --$i) {
163 $token = $tokens[$i];
164 if ('variable' === $token[0] && $route->hasDefault($token[3])) {
172 // compute the matching regexp
174 for ($i = 0, $nbToken = count($tokens); $i < $nbToken; ++$i) {
175 $regexp .= self::computeRegexp($tokens, $i, $firstOptional);
179 'staticPrefix' => 'text' === $tokens[0][0] ? $tokens[0][1] : '',
180 'regex' => self::REGEX_DELIMITER.'^'.$regexp.'$'.self::REGEX_DELIMITER.'s'.($isHost ? 'i' : ''),
181 'tokens' => array_reverse($tokens),
182 'variables' => $variables,
187 * Returns the next static character in the Route pattern that will serve as a separator.
189 * @param string $pattern The route pattern
191 * @return string The next static character that functions as separator (or empty string when none available)
193 private static function findNextSeparator($pattern)
195 if ('' == $pattern) {
196 // return empty string if pattern is empty or false (false which can be returned by substr)
199 // first remove all placeholders from the pattern so we can find the next real static character
200 $pattern = preg_replace('#\{\w+\}#', '', $pattern);
202 return isset($pattern[0]) && false !== strpos(static::SEPARATORS, $pattern[0]) ? $pattern[0] : '';
206 * Computes the regexp used to match a specific token. It can be static text or a subpattern.
208 * @param array $tokens The route tokens
209 * @param int $index The index of the current token
210 * @param int $firstOptional The index of the first optional token
212 * @return string The regexp pattern for a single token
214 private static function computeRegexp(array $tokens, $index, $firstOptional)
216 $token = $tokens[$index];
217 if ('text' === $token[0]) {
219 return preg_quote($token[1], self::REGEX_DELIMITER);
222 if (0 === $index && 0 === $firstOptional) {
223 // When the only token is an optional variable token, the separator is required
224 return sprintf('%s(?P<%s>%s)?', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
226 $regexp = sprintf('%s(?P<%s>%s)', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
227 if ($index >= $firstOptional) {
228 // Enclose each optional token in a subpattern to make it optional.
229 // "?:" means it is non-capturing, i.e. the portion of the subject string that
230 // matched the optional subpattern is not passed back.
231 $regexp = "(?:$regexp";
232 $nbTokens = count($tokens);
233 if ($nbTokens - 1 == $index) {
234 // Close the optional subpatterns
235 $regexp .= str_repeat(')?', $nbTokens - $firstOptional - (0 === $firstOptional ? 1 : 0));