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