Convert to regex

@param  string $name route name
@param  string $pattern route pattern
@return string parsed regex
@access protected
342296
protected function convert(
        /*# string */ $name,
        /*# string */ $pattern
    )/*# : string */ {
        $ph = sprintf("\{%s(?:%s)?\}", self::MATCH_GROUP_NAME, self::MATCH_GROUP_TYPE);
        $result = preg_replace([
            '~' . $ph . '(*SKIP)(*FAIL) | \[~x', '~' . $ph . '(*SKIP)(*FAIL) | \]~x',
            '~\{' . self::MATCH_GROUP_NAME . '\}~x', '~' . $ph . '~x',
        ], [
            '(?:', ')?', '{\\1:' . self::MATCH_SEGMENT . '}', '(?<${1}'. $name . '>${2})'
        ], strtr('/' . trim($pattern, '/'), $this->shortcuts));
        return empty($name) ? $result : ("(?<$name>" . $result . ")");
    }
1055744
public function match($pattern) {
        if (!$this->_isValid) {
            return $this;
        }
        if (!preg_match($pattern, $this->_unsafeVar)) {
            $this->_isValid = false;
        }
        return $this;
    }
1155224
public function get(string $name, ?string $pattern = null, array $options = []): RouteData
    {
        return $this->any($name, $pattern, $options)->methods('GET');
    }
1239749
private function setBaseRoute($pattern)
    {
        $pattern = $this->routeBasePath . '/' . trim($pattern, '/');

        return $this->routeBasePath ? rtrim($pattern, '/') : $pattern;
    }
773714
public function trace($pattern, $action, $name =  null)
    {
        return $this->addRoute(['TRACE'], $pattern, $action, $name);
    }
1048954
protected function compile($pattern)
    {
        if (isset($this->compileCache[$pattern])) {
            return $this->compileCache[$pattern];
        }

        $pcre = '(^';

        do {
            switch (true) {
                case preg_match('(^[^{]+)', $pattern, $match):
                    $pattern = substr($pattern, strlen($match[0]));
                    $pcre .= preg_quote($match[0]);
                    break;

                case preg_match('(^' . self::STANDARD_VARIABLE_REGEX . ')', $pattern, $match):
                    $pattern = substr($pattern, strlen($match[0]));
                    $pcre .= '(?P<' . $match[1] . '>[^/]+)';
                    break;

                case preg_match('(^' . self::SLASHES_VARIABLE_REGEX . ')', $pattern, $match):
                    $pattern = substr($pattern, strlen($match[0]));
                    $pcre .= '(?P<' . $match[1] . '>.+)';
                    break;

                default:
                    throw new Exceptions\InvalidArgumentException("Invalid pattern part: '$pattern'.");
            }
        } while ($pattern);

        $pcre .= '$)S';

        $this->compileCache[$pattern] = $pcre;

        return $pcre;
    }
1152576
private static function getPattern(string $pattern)
    {
        $keywords = preg_split("/\\//", $pattern);
        $i = '0';
        $word = "";
        foreach ($keywords as $keyword) {
            $i++;
            if (preg_match("/:/i", $keyword)) {
                $word .= "([a-zA-Z0-9-._]+)";
            } else {
                $word .= $keyword;
            }
            if (count($keywords) != $i) {
                $word .= "/";
            }
        }

        return $word;
    }
500021
protected function splitRoutePattern($pattern)
    {
        if (strpos($pattern, ' ') !== false && preg_match_all('/\s+\+(\w+)\b|\s+\-(\w+)\b/', $pattern, $matches)) {
            list($path) = preg_split('/\s+/', $pattern, 2);
            $inc = isset($matches[1]) ? array_filter($matches[1]) : [];
            $excl = isset($matches[2]) ? array_filter($matches[2]) : [];
        } else {
            $path = $pattern;
            $inc = [];
            $excl = [];
        }
        
        return [$path, $inc, $excl];
    }
526549
protected function regexifyPattern($pattern)
    {
        preg_match_all('/(\/?)\(:([^)]*)\)(\??)/', $pattern, $regExPatterns, PREG_SET_ORDER, 0);

        $pattern = preg_quote($pattern, '/');

        foreach ($regExPatterns as $regExPattern) {
            if (!empty($regExPattern[2]) && key_exists($regExPattern[2], $this->patterns)) {
                $replacement = sprintf(
                    '(%s%s)%s',
                    empty($regExPattern[1]) ? '' : '\/',
                    $this->patterns[$regExPattern[2]],
                    $regExPattern[3]
                );

                $pattern     = str_replace(preg_quote($regExPattern[0], '/'), $replacement, $pattern);
            }
        }

        return "/^$pattern$/";
    }
579228
protected function convert(/*# string */ $pattern)/*# : array */
    {
        $ph = sprintf("\{%s(?:%s)?\}", self::MATCH_GROUP_NAME, self::MATCH_GROUP_TYPE);

        // count placeholders
        $map = $m = [];
        if (preg_match_all('~'. $ph .'~x', $pattern, $m)) {
            $map = $m[1];
        }

        $result = preg_replace(
            [
            '~' . $ph . '(*SKIP)(*FAIL) | \[~x', '~' . $ph . '(*SKIP)(*FAIL) | \]~x',
            '~\{' . self::MATCH_GROUP_NAME . '\}~x', '~' . $ph . '~x',
            ],
            ['(?:', ')?', '{\\1:' . self::MATCH_SEGMENT . '}', '(\\2)'],
            strtr('/' . trim($pattern, '/'), $this->shortcuts)
        );

        return [$result, $map];
    }
394315
public function getRegexp($name = null)
    {
        if ($name === null) {
            return $this->regexps;
        }
        return isset($this->regexps[$name]) ? $this->regexps[$name] : '[^/]+';
    }
321581
public static function url(string $name, ?array $parameters = [])
  {
    $url = null;

    foreach (Swish::$routes as $route) {
      if ($route['name'] == $name) {
        $url = $route['pattern'];

        if ($route['required'] > 0 && ($route['required'] == count($parameters))) {
          foreach ($parameters as $name => $parameter) {
            $url = str_replace('{' . $name . '}', $parameter, $url);
          }
        }
      }
    }

    if (str_contains($url, ['{', '}'])) $url = null;

    return $url;
  }
1086813
public function _as($name)
    {
        if (empty($name)) return $this;
        $name = rtrim($this->getGroupAs() . str_replace('/', '.', strtolower($name)), '.');
//        if (array_key_exists($name, $this->routes)) {
//            throw new \Exception("Route name ($name) already registered.");
//        }

        $patt = $this->patt;
        $pram = $this->prams;
        // Merge group parameters with route parameters.
        if ($this->isGroup) {
            $patt = array_merge($this->pattGroup, $patt);
            if (count($patt) > count($pram)) {
                $pram = array_merge($this->pramsGroup, $pram);
            }
        }

        // :param
        if (count($pram)) {
            foreach ($pram as $k => $v) {
                $pram[$k] = '/:' . $v;
            }
        }

        // Replace pattern to named parameters.
        $replaced = $this->group . $this->currentUri;
        foreach ($patt as $k => $v) {
            $pos = strpos($replaced, $v);
            if ($pos !== false) {
                $replaced = substr_replace($replaced, $pram[$k], $pos, strlen($v));
            }
        }

        $this->routes[$name] = ltrim($this->removeDuplSlash(strtolower($replaced)), '/');

        return $this;
    }
1161709
protected function generateRegex(
        string $regex,
        ?NodeInterface $parent,
        ?string $name
    ): NodeInterface{
        $node   = new RegexNode($this, $parent, $name);

        $node->setRegex($regex);

        return $node;
    }
722884
private function IsValidFormat($Name, $Pattern, $Value)
        {
            if (! empty($Value)) {
                if (! preg_match($Pattern, $Value)) {
                    throw new Exception('Invalid '.$Name.'.');
                }
            }
        }
880056
protected function convert(/*# string */ $pattern)/*# : array */
    {
        // regex
        $groupname   = "\s*([a-zA-Z][a-zA-Z0-9_]*)\s*";
        $grouptype   = ":\s*([^{}]*(?:\{(?-1)\}[^{}]*)*)";
        $placeholder = sprintf("\{%s(?:%s)?\}", $groupname, $grouptype);
        $segmenttype = "[^/]++";

        // count placeholders
        $map = $m = [];
        if (preg_match_all('~'. $placeholder .'~x', $pattern, $m)) {
            $map = $m[1];
        }

        // full regex
        $result = preg_replace([
                '~' . $placeholder . '(*SKIP)(*FAIL) | \[~x',
                '~' . $placeholder . '(*SKIP)(*FAIL) | \]~x',
                '~\{' . $groupname . '\}~x',
                '~' . $placeholder . '~x',
            ], [
                '(?:',  // replace '['
                ')?',   // replace ']'
                '{\\1:' . $segmenttype . '}',   // add segementtype
                '(\\2)'                         // group it
            ], strtr('/' . trim($pattern, '/'), $this->shortcuts)
        );
        return [ $result, $map ];
    }
1349238
public function setConstraint($name, $regex)
    {
        foreach ($this->routes as $route)
            $route->setConstraint($name, $regex);
        return $this;
    }