1: <?php
2:
3: /*
4: * This file is part of the Symfony package.
5: *
6: * (c) Fabien Potencier <[email protected]>
7: *
8: * For the full copyright and license information, please view the LICENSE
9: * file that was distributed with this source code.
10: */
11:
12: namespace Symfony\Component\Routing;
13:
14: /**
15: * RouteCompiler compiles Route instances to CompiledRoute instances.
16: *
17: * @author Fabien Potencier <[email protected]>
18: * @author Tobias Schultze <http://tobion.de>
19: */
20: class RouteCompiler implements RouteCompilerInterface
21: {
22: const REGEX_DELIMITER = '#';
23:
24: /**
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.
28: */
29: const SEPARATORS = '/,;.:-_~+*=@|';
30:
31: /**
32: * The maximum supported length of a PCRE subpattern name
33: * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16.
34: *
35: * @internal
36: */
37: const VARIABLE_MAXIMUM_LENGTH = 32;
38:
39: /**
40: * {@inheritdoc}
41: *
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
44: * a PCRE subpattern.
45: */
46: public static function compile(Route $route)
47: {
48: $hostVariables = array();
49: $variables = array();
50: $hostRegex = null;
51: $hostTokens = array();
52:
53: if ('' !== $host = $route->getHost()) {
54: $result = self::compilePattern($route, $host, true);
55:
56: $hostVariables = $result['variables'];
57: $variables = $hostVariables;
58:
59: $hostTokens = $result['tokens'];
60: $hostRegex = $result['regex'];
61: }
62:
63: $path = $route->getPath();
64:
65: $result = self::compilePattern($route, $path, false);
66:
67: $staticPrefix = $result['staticPrefix'];
68:
69: $pathVariables = $result['variables'];
70: $variables = array_merge($variables, $pathVariables);
71:
72: $tokens = $result['tokens'];
73: $regex = $result['regex'];
74:
75: return new CompiledRoute(
76: $staticPrefix,
77: $regex,
78: $tokens,
79: $pathVariables,
80: $hostRegex,
81: $hostTokens,
82: $hostVariables,
83: array_unique($variables)
84: );
85: }
86:
87: private static function compilePattern(Route $route, $pattern, $isHost)
88: {
89: $tokens = array();
90: $variables = array();
91: $matches = array();
92: $pos = 0;
93: $defaultSeparator = $isHost ? '.' : '/';
94:
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);
105:
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));
110: }
111: if (in_array($varName, $variables)) {
112: throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName));
113: }
114:
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));
117: }
118:
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);
123: }
124:
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);
136: $regexp = sprintf(
137: '[^%s%s]+',
138: preg_quote($defaultSeparator, self::REGEX_DELIMITER),
139: $defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) : ''
140: );
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}'.
147: $regexp .= '+';
148: }
149: }
150:
151: $tokens[] = array('variable', $isSeparator ? $precedingChar : '', $regexp, $varName);
152: $variables[] = $varName;
153: }
154:
155: if ($pos < strlen($pattern)) {
156: $tokens[] = array('text', substr($pattern, $pos));
157: }
158:
159: // find the first optional token
160: $firstOptional = PHP_INT_MAX;
161: if (!$isHost) {
162: for ($i = count($tokens) - 1; $i >= 0; --$i) {
163: $token = $tokens[$i];
164: if ('variable' === $token[0] && $route->hasDefault($token[3])) {
165: $firstOptional = $i;
166: } else {
167: break;
168: }
169: }
170: }
171:
172: // compute the matching regexp
173: $regexp = '';
174: for ($i = 0, $nbToken = count($tokens); $i < $nbToken; ++$i) {
175: $regexp .= self::computeRegexp($tokens, $i, $firstOptional);
176: }
177:
178: return array(
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,
183: );
184: }
185:
186: /**
187: * Returns the next static character in the Route pattern that will serve as a separator.
188: *
189: * @param string $pattern The route pattern
190: *
191: * @return string The next static character that functions as separator (or empty string when none available)
192: */
193: private static function findNextSeparator($pattern)
194: {
195: if ('' == $pattern) {
196: // return empty string if pattern is empty or false (false which can be returned by substr)
197: return '';
198: }
199: // first remove all placeholders from the pattern so we can find the next real static character
200: $pattern = preg_replace('#\{\w+\}#', '', $pattern);
201:
202: return isset($pattern[0]) && false !== strpos(static::SEPARATORS, $pattern[0]) ? $pattern[0] : '';
203: }
204:
205: /**
206: * Computes the regexp used to match a specific token. It can be static text or a subpattern.
207: *
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
211: *
212: * @return string The regexp pattern for a single token
213: */
214: private static function computeRegexp(array $tokens, $index, $firstOptional)
215: {
216: $token = $tokens[$index];
217: if ('text' === $token[0]) {
218: // Text tokens
219: return preg_quote($token[1], self::REGEX_DELIMITER);
220: } else {
221: // Variable tokens
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]);
225: } else {
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));
236: }
237: }
238:
239: return $regexp;
240: }
241: }
242: }
243: }
244: