private function RouteCompiler::computeRegexp

Same name in this branch
  1. 9.x drupal/core/lib/Drupal/Core/Routing/RouteCompiler.php \Drupal\Core\Routing\RouteCompiler::computeRegexp()
  2. 9.x drupal/core/vendor/symfony/routing/Symfony/Component/Routing/RouteCompiler.php \Symfony\Component\Routing\RouteCompiler::computeRegexp()

Computes the regexp used to match a specific token. It can be static text or a subpattern.

Parameters

array $tokens: The route tokens

integer $index: The index of the current token

integer $first_optional: The index of the first optional token

Return value

string The regexp pattern for a single token

1 call to RouteCompiler::computeRegexp()
RouteCompiler::getRegex in drupal/core/lib/Drupal/Core/Routing/RouteCompiler.php
Generates a regular expression that will match this pattern.

File

drupal/core/lib/Drupal/Core/Routing/RouteCompiler.php, line 145
Definition of Drupal\Core\Routing\RouteCompiler.

Class

RouteCompiler
Compiler to generate derived information from a Route necessary for matching.

Namespace

Drupal\Core\Routing

Code

private function computeRegexp(array $tokens, $index, $first_optional) {
  $token = $tokens[$index];
  if ('text' === $token[0]) {

    // Text tokens
    return preg_quote($token[1], self::REGEX_DELIMITER);
  }
  else {

    // Variable tokens
    if (0 === $index && 0 === $first_optional) {

      // When the only token is an optional variable token, the separator is
      // required.
      return sprintf('%s(?<%s>%s)?', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
    }
    else {
      $regexp = sprintf('%s(?<%s>%s)', preg_quote($token[1], self::REGEX_DELIMITER), $token[3], $token[2]);
      if ($index >= $first_optional) {

        // Enclose each optional token in a subpattern to make it optional.
        // "?:" means it is non-capturing, i.e. the portion of the subject
        // string that matched the optional subpattern is not passed back.
        $regexp = "(?:{$regexp}";
        $nbTokens = count($tokens);
        if ($nbTokens - 1 == $index) {

          // Close the optional subpatterns.
          $regexp .= str_repeat(")?", $nbTokens - $first_optional - (0 === $first_optional ? 1 : 0));
        }
      }
      return $regexp;
    }
  }
}