You are here

public static function XBBCodeParser::buildTree in Extensible BBCode 8.3

Same name and namespace in other branches
  1. 4.0.x src/Parser/XBBCodeParser.php \Drupal\xbbcode\Parser\XBBCodeParser::buildTree()

Convert a well-formed list of tokens into a tree.

Parameters

string $text: The source text.

array[] $tokens: The tokens.

Return value

\Drupal\xbbcode\Parser\Tree\NodeElementInterface The element representing the tree.

1 call to XBBCodeParser::buildTree()
XBBCodeParser::parse in src/Parser/XBBCodeParser.php
Parse a text and build an element tree.

File

src/Parser/XBBCodeParser.php, line 235

Class

XBBCodeParser
The standard XBBCode parser.

Namespace

Drupal\xbbcode\Parser

Code

public static function buildTree($text, array $tokens) : NodeElementInterface {

  /** @var \Drupal\xbbcode\Parser\Tree\NodeElement[] $stack */
  $stack = [
    new RootElement(),
  ];

  // Tracks the current position in the text.
  $index = 0;
  foreach ($tokens as $token) {

    // Append any text before the token to the parent.
    $leading = substr($text, $index, $token['start'] - $index);
    if ($leading) {
      end($stack)
        ->append(new TextElement($leading));
    }

    // Advance to the end of the token.
    $index = $token['end'];
    if (!$token['closing']) {

      // Push the element on the stack.
      $stack[] = new TagElement($token['name'], $token['argument'], substr($text, $token['end'], $token['length']));
    }
    else {

      // Pop the closed element.
      $element = array_pop($stack);
      end($stack)
        ->append($element);
    }
  }
  $final = substr($text, $index);
  if ($final) {
    end($stack)
      ->append(new TextElement($final));
  }
  return array_pop($stack);
}