Example #1
0
 /**
  * Builds a regex from a tokens structure array.
  *
  * @param  array $token A tokens structure root node.
  * @return array        An array containing the regex pattern and its associated variable names.
  */
 public static function compile($token)
 {
     $variables = [];
     $regex = '';
     foreach ($token['tokens'] as $child) {
         if (is_string($child)) {
             $regex .= preg_quote($child, '~');
         } elseif (isset($child['tokens'])) {
             $rule = static::compile($child);
             if ($child['repeat']) {
                 if (count($rule[1]) > 1) {
                     throw ParserException::placeholderExceeded();
                 }
                 $regex .= '((?:' . $rule[0] . ')' . $child['greedy'] . ')';
             } elseif ($child['optional']) {
                 $regex .= '(?:' . $rule[0] . ')?';
             }
             foreach ($rule[1] as $name => $pattern) {
                 if (isset($variables[$name])) {
                     throw ParserException::duplicatePlaceholder($name);
                 }
                 $variables[$name] = $pattern;
             }
         } else {
             $name = $child['name'];
             if (isset($variables[$name])) {
                 throw ParserException::duplicatePlaceholder($name);
             }
             if ($token['repeat']) {
                 $variables[$name] = $token['pattern'];
                 $regex .= $child['pattern'];
             } else {
                 $variables[$name] = false;
                 $regex .= '(' . $child['pattern'] . ')';
             }
         }
     }
     return [$regex, $variables];
 }