public static function XBBCodeParser::buildTree in Extensible BBCode 4.0.x
Same name and namespace in other branches
- 8.3 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 237
Class
- XBBCodeParser
- The standard XBBCode parser.
Namespace
Drupal\xbbcode\ParserCode
public static function buildTree(string $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.
/** @var \Drupal\xbbcode\Parser\Tree\TagElementInterface $element */
$element = array_pop($stack);
$element
->setClosingName($token['name']);
end($stack)
->append($element);
}
}
$final = substr($text, $index);
if ($final) {
end($stack)
->append(new TextElement($final));
}
return array_pop($stack);
}