annotate vendor/symfony/routing/RouteCompiler.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 129ea1e6d783
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Symfony\Component\Routing;
Chris@0 13
Chris@0 14 /**
Chris@0 15 * RouteCompiler compiles Route instances to CompiledRoute instances.
Chris@0 16 *
Chris@0 17 * @author Fabien Potencier <fabien@symfony.com>
Chris@0 18 * @author Tobias Schultze <http://tobion.de>
Chris@0 19 */
Chris@0 20 class RouteCompiler implements RouteCompilerInterface
Chris@0 21 {
Chris@0 22 const REGEX_DELIMITER = '#';
Chris@0 23
Chris@0 24 /**
Chris@0 25 * This string defines the characters that are automatically considered separators in front of
Chris@0 26 * optional placeholders (with default and no static text following). Such a single separator
Chris@0 27 * can be left out together with the optional placeholder from matching and generating URLs.
Chris@0 28 */
Chris@0 29 const SEPARATORS = '/,;.:-_~+*=@|';
Chris@0 30
Chris@0 31 /**
Chris@0 32 * The maximum supported length of a PCRE subpattern name
Chris@0 33 * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16.
Chris@0 34 *
Chris@0 35 * @internal
Chris@0 36 */
Chris@0 37 const VARIABLE_MAXIMUM_LENGTH = 32;
Chris@0 38
Chris@0 39 /**
Chris@0 40 * {@inheritdoc}
Chris@0 41 *
Chris@14 42 * @throws \InvalidArgumentException if a path variable is named _fragment
Chris@14 43 * @throws \LogicException if a variable is referenced more than once
Chris@14 44 * @throws \DomainException if a variable name starts with a digit or if it is too long to be successfully used as
Chris@14 45 * a PCRE subpattern
Chris@0 46 */
Chris@0 47 public static function compile(Route $route)
Chris@0 48 {
Chris@17 49 $hostVariables = [];
Chris@17 50 $variables = [];
Chris@0 51 $hostRegex = null;
Chris@17 52 $hostTokens = [];
Chris@0 53
Chris@0 54 if ('' !== $host = $route->getHost()) {
Chris@0 55 $result = self::compilePattern($route, $host, true);
Chris@0 56
Chris@0 57 $hostVariables = $result['variables'];
Chris@0 58 $variables = $hostVariables;
Chris@0 59
Chris@0 60 $hostTokens = $result['tokens'];
Chris@0 61 $hostRegex = $result['regex'];
Chris@0 62 }
Chris@0 63
Chris@0 64 $path = $route->getPath();
Chris@0 65
Chris@0 66 $result = self::compilePattern($route, $path, false);
Chris@0 67
Chris@0 68 $staticPrefix = $result['staticPrefix'];
Chris@0 69
Chris@0 70 $pathVariables = $result['variables'];
Chris@0 71
Chris@0 72 foreach ($pathVariables as $pathParam) {
Chris@0 73 if ('_fragment' === $pathParam) {
Chris@0 74 throw new \InvalidArgumentException(sprintf('Route pattern "%s" cannot contain "_fragment" as a path parameter.', $route->getPath()));
Chris@0 75 }
Chris@0 76 }
Chris@0 77
Chris@0 78 $variables = array_merge($variables, $pathVariables);
Chris@0 79
Chris@0 80 $tokens = $result['tokens'];
Chris@0 81 $regex = $result['regex'];
Chris@0 82
Chris@0 83 return new CompiledRoute(
Chris@0 84 $staticPrefix,
Chris@0 85 $regex,
Chris@0 86 $tokens,
Chris@0 87 $pathVariables,
Chris@0 88 $hostRegex,
Chris@0 89 $hostTokens,
Chris@0 90 $hostVariables,
Chris@0 91 array_unique($variables)
Chris@0 92 );
Chris@0 93 }
Chris@0 94
Chris@0 95 private static function compilePattern(Route $route, $pattern, $isHost)
Chris@0 96 {
Chris@17 97 $tokens = [];
Chris@17 98 $variables = [];
Chris@17 99 $matches = [];
Chris@0 100 $pos = 0;
Chris@0 101 $defaultSeparator = $isHost ? '.' : '/';
Chris@0 102 $useUtf8 = preg_match('//u', $pattern);
Chris@0 103 $needsUtf8 = $route->getOption('utf8');
Chris@0 104
Chris@0 105 if (!$needsUtf8 && $useUtf8 && preg_match('/[\x80-\xFF]/', $pattern)) {
Chris@0 106 $needsUtf8 = true;
Chris@0 107 @trigger_error(sprintf('Using UTF-8 route patterns without setting the "utf8" option is deprecated since Symfony 3.2 and will throw a LogicException in 4.0. Turn on the "utf8" route option for pattern "%s".', $pattern), E_USER_DEPRECATED);
Chris@0 108 }
Chris@0 109 if (!$useUtf8 && $needsUtf8) {
Chris@0 110 throw new \LogicException(sprintf('Cannot mix UTF-8 requirements with non-UTF-8 pattern "%s".', $pattern));
Chris@0 111 }
Chris@0 112
Chris@0 113 // Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable
Chris@0 114 // in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself.
Chris@0 115 preg_match_all('#\{\w+\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
Chris@0 116 foreach ($matches as $match) {
Chris@0 117 $varName = substr($match[0][0], 1, -1);
Chris@0 118 // get all static text preceding the current variable
Chris@0 119 $precedingText = substr($pattern, $pos, $match[0][1] - $pos);
Chris@17 120 $pos = $match[0][1] + \strlen($match[0][0]);
Chris@0 121
Chris@17 122 if (!\strlen($precedingText)) {
Chris@0 123 $precedingChar = '';
Chris@0 124 } elseif ($useUtf8) {
Chris@0 125 preg_match('/.$/u', $precedingText, $precedingChar);
Chris@0 126 $precedingChar = $precedingChar[0];
Chris@0 127 } else {
Chris@0 128 $precedingChar = substr($precedingText, -1);
Chris@0 129 }
Chris@0 130 $isSeparator = '' !== $precedingChar && false !== strpos(static::SEPARATORS, $precedingChar);
Chris@0 131
Chris@0 132 // A PCRE subpattern name must start with a non-digit. Also a PHP variable cannot start with a digit so the
Chris@0 133 // variable would not be usable as a Controller action argument.
Chris@0 134 if (preg_match('/^\d/', $varName)) {
Chris@0 135 throw new \DomainException(sprintf('Variable name "%s" cannot start with a digit in route pattern "%s". Please use a different name.', $varName, $pattern));
Chris@0 136 }
Chris@17 137 if (\in_array($varName, $variables)) {
Chris@0 138 throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $pattern, $varName));
Chris@0 139 }
Chris@0 140
Chris@17 141 if (\strlen($varName) > self::VARIABLE_MAXIMUM_LENGTH) {
Chris@0 142 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));
Chris@0 143 }
Chris@0 144
Chris@0 145 if ($isSeparator && $precedingText !== $precedingChar) {
Chris@17 146 $tokens[] = ['text', substr($precedingText, 0, -\strlen($precedingChar))];
Chris@17 147 } elseif (!$isSeparator && \strlen($precedingText) > 0) {
Chris@17 148 $tokens[] = ['text', $precedingText];
Chris@0 149 }
Chris@0 150
Chris@0 151 $regexp = $route->getRequirement($varName);
Chris@0 152 if (null === $regexp) {
Chris@0 153 $followingPattern = (string) substr($pattern, $pos);
Chris@0 154 // Find the next static character after the variable that functions as a separator. By default, this separator and '/'
Chris@0 155 // are disallowed for the variable. This default requirement makes sure that optional variables can be matched at all
Chris@0 156 // and that the generating-matching-combination of URLs unambiguous, i.e. the params used for generating the URL are
Chris@17 157 // the same that will be matched. Example: new Route('/{page}.{_format}', ['_format' => 'html'])
Chris@0 158 // If {page} would also match the separating dot, {_format} would never match as {page} will eagerly consume everything.
Chris@0 159 // Also even if {_format} was not optional the requirement prevents that {page} matches something that was originally
Chris@0 160 // part of {_format} when generating the URL, e.g. _format = 'mobile.html'.
Chris@0 161 $nextSeparator = self::findNextSeparator($followingPattern, $useUtf8);
Chris@0 162 $regexp = sprintf(
Chris@0 163 '[^%s%s]+',
Chris@0 164 preg_quote($defaultSeparator, self::REGEX_DELIMITER),
Chris@0 165 $defaultSeparator !== $nextSeparator && '' !== $nextSeparator ? preg_quote($nextSeparator, self::REGEX_DELIMITER) : ''
Chris@0 166 );
Chris@0 167 if (('' !== $nextSeparator && !preg_match('#^\{\w+\}#', $followingPattern)) || '' === $followingPattern) {
Chris@0 168 // When we have a separator, which is disallowed for the variable, we can optimize the regex with a possessive
Chris@0 169 // quantifier. This prevents useless backtracking of PCRE and improves performance by 20% for matching those patterns.
Chris@0 170 // Given the above example, there is no point in backtracking into {page} (that forbids the dot) when a dot must follow
Chris@0 171 // after it. This optimization cannot be applied when the next char is no real separator or when the next variable is
Chris@0 172 // directly adjacent, e.g. '/{x}{y}'.
Chris@0 173 $regexp .= '+';
Chris@0 174 }
Chris@0 175 } else {
Chris@0 176 if (!preg_match('//u', $regexp)) {
Chris@0 177 $useUtf8 = false;
Chris@0 178 } elseif (!$needsUtf8 && preg_match('/[\x80-\xFF]|(?<!\\\\)\\\\(?:\\\\\\\\)*+(?-i:X|[pP][\{CLMNPSZ]|x\{[A-Fa-f0-9]{3})/', $regexp)) {
Chris@0 179 $needsUtf8 = true;
Chris@0 180 @trigger_error(sprintf('Using UTF-8 route requirements without setting the "utf8" option is deprecated since Symfony 3.2 and will throw a LogicException in 4.0. Turn on the "utf8" route option for variable "%s" in pattern "%s".', $varName, $pattern), E_USER_DEPRECATED);
Chris@0 181 }
Chris@0 182 if (!$useUtf8 && $needsUtf8) {
Chris@0 183 throw new \LogicException(sprintf('Cannot mix UTF-8 requirement with non-UTF-8 charset for variable "%s" in pattern "%s".', $varName, $pattern));
Chris@0 184 }
Chris@0 185 }
Chris@0 186
Chris@17 187 $tokens[] = ['variable', $isSeparator ? $precedingChar : '', $regexp, $varName];
Chris@0 188 $variables[] = $varName;
Chris@0 189 }
Chris@0 190
Chris@17 191 if ($pos < \strlen($pattern)) {
Chris@17 192 $tokens[] = ['text', substr($pattern, $pos)];
Chris@0 193 }
Chris@0 194
Chris@0 195 // find the first optional token
Chris@0 196 $firstOptional = PHP_INT_MAX;
Chris@0 197 if (!$isHost) {
Chris@17 198 for ($i = \count($tokens) - 1; $i >= 0; --$i) {
Chris@0 199 $token = $tokens[$i];
Chris@0 200 if ('variable' === $token[0] && $route->hasDefault($token[3])) {
Chris@0 201 $firstOptional = $i;
Chris@0 202 } else {
Chris@0 203 break;
Chris@0 204 }
Chris@0 205 }
Chris@0 206 }
Chris@0 207
Chris@0 208 // compute the matching regexp
Chris@0 209 $regexp = '';
Chris@17 210 for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) {
Chris@0 211 $regexp .= self::computeRegexp($tokens, $i, $firstOptional);
Chris@0 212 }
Chris@14 213 $regexp = self::REGEX_DELIMITER.'^'.$regexp.'$'.self::REGEX_DELIMITER.'sD'.($isHost ? 'i' : '');
Chris@0 214
Chris@0 215 // enable Utf8 matching if really required
Chris@0 216 if ($needsUtf8) {
Chris@0 217 $regexp .= 'u';
Chris@17 218 for ($i = 0, $nbToken = \count($tokens); $i < $nbToken; ++$i) {
Chris@0 219 if ('variable' === $tokens[$i][0]) {
Chris@0 220 $tokens[$i][] = true;
Chris@0 221 }
Chris@0 222 }
Chris@0 223 }
Chris@0 224
Chris@17 225 return [
Chris@14 226 'staticPrefix' => self::determineStaticPrefix($route, $tokens),
Chris@0 227 'regex' => $regexp,
Chris@0 228 'tokens' => array_reverse($tokens),
Chris@0 229 'variables' => $variables,
Chris@17 230 ];
Chris@0 231 }
Chris@0 232
Chris@0 233 /**
Chris@14 234 * Determines the longest static prefix possible for a route.
Chris@14 235 *
Chris@14 236 * @return string The leading static part of a route's path
Chris@14 237 */
Chris@14 238 private static function determineStaticPrefix(Route $route, array $tokens)
Chris@14 239 {
Chris@14 240 if ('text' !== $tokens[0][0]) {
Chris@14 241 return ($route->hasDefault($tokens[0][3]) || '/' === $tokens[0][1]) ? '' : $tokens[0][1];
Chris@14 242 }
Chris@14 243
Chris@14 244 $prefix = $tokens[0][1];
Chris@14 245
Chris@14 246 if (isset($tokens[1][1]) && '/' !== $tokens[1][1] && false === $route->hasDefault($tokens[1][3])) {
Chris@14 247 $prefix .= $tokens[1][1];
Chris@14 248 }
Chris@14 249
Chris@14 250 return $prefix;
Chris@14 251 }
Chris@14 252
Chris@14 253 /**
Chris@0 254 * Returns the next static character in the Route pattern that will serve as a separator.
Chris@0 255 *
Chris@0 256 * @param string $pattern The route pattern
Chris@0 257 * @param bool $useUtf8 Whether the character is encoded in UTF-8 or not
Chris@0 258 *
Chris@0 259 * @return string The next static character that functions as separator (or empty string when none available)
Chris@0 260 */
Chris@0 261 private static function findNextSeparator($pattern, $useUtf8)
Chris@0 262 {
Chris@0 263 if ('' == $pattern) {
Chris@0 264 // return empty string if pattern is empty or false (false which can be returned by substr)
Chris@0 265 return '';
Chris@0 266 }
Chris@0 267 // first remove all placeholders from the pattern so we can find the next real static character
Chris@0 268 if ('' === $pattern = preg_replace('#\{\w+\}#', '', $pattern)) {
Chris@0 269 return '';
Chris@0 270 }
Chris@0 271 if ($useUtf8) {
Chris@0 272 preg_match('/^./u', $pattern, $pattern);
Chris@0 273 }
Chris@0 274
Chris@0 275 return false !== strpos(static::SEPARATORS, $pattern[0]) ? $pattern[0] : '';
Chris@0 276 }
Chris@0 277
Chris@0 278 /**
Chris@0 279 * Computes the regexp used to match a specific token. It can be static text or a subpattern.
Chris@0 280 *
Chris@0 281 * @param array $tokens The route tokens
Chris@0 282 * @param int $index The index of the current token
Chris@0 283 * @param int $firstOptional The index of the first optional token
Chris@0 284 *
Chris@0 285 * @return string The regexp pattern for a single token
Chris@0 286 */
Chris@0 287 private static function computeRegexp(array $tokens, $index, $firstOptional)
Chris@0 288 {
Chris@0 289 $token = $tokens[$index];
Chris@0 290 if ('text' === $token[0]) {
Chris@0 291 // Text tokens
Chris@0 292 return preg_quote($token[1], self::REGEX_DELIMITER);
Chris@0 293 } else {
Chris@0 294 // Variable tokens
Chris@0 295 if (0 === $index && 0 === $firstOptional) {
Chris@0 296 // When the only token is an optional variable token, the separator is required
Chris@0 297 return sprintf('%s(?P<%s>%s)?', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
Chris@0 298 } else {
Chris@0 299 $regexp = sprintf('%s(?P<%s>%s)', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
Chris@0 300 if ($index >= $firstOptional) {
Chris@0 301 // Enclose each optional token in a subpattern to make it optional.
Chris@0 302 // "?:" means it is non-capturing, i.e. the portion of the subject string that
Chris@0 303 // matched the optional subpattern is not passed back.
Chris@0 304 $regexp = "(?:$regexp";
Chris@17 305 $nbTokens = \count($tokens);
Chris@0 306 if ($nbTokens - 1 == $index) {
Chris@0 307 // Close the optional subpatterns
Chris@0 308 $regexp .= str_repeat(')?', $nbTokens - $firstOptional - (0 === $firstOptional ? 1 : 0));
Chris@0 309 }
Chris@0 310 }
Chris@0 311
Chris@0 312 return $regexp;
Chris@0 313 }
Chris@0 314 }
Chris@0 315 }
Chris@0 316 }