You are here

public static function XBBCodeParser::validateTokens in Extensible BBCode 8.3

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

Validate the nesting, and remove tokens that are not nested.

Parameters

array[] $tokens: The tokens.

Return value

array[] A well-formed list of tokens.

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

File

src/Parser/XBBCodeParser.php, line 185

Class

XBBCodeParser
The standard XBBCode parser.

Namespace

Drupal\xbbcode\Parser

Code

public static function validateTokens(array $tokens) : array {

  // Initialize the counter for each tag name.
  $counter = [];
  foreach ($tokens as $token) {
    $counter[$token['name']] = 0;
  }
  $stack = [];
  foreach ($tokens as $i => $token) {
    if ($token['closing']) {
      if ($counter[$token['name']] > 0) {

        // Pop the stack until a matching token is reached.
        do {
          $last = array_pop($stack);
          $counter[$last['name']]--;
        } while ($last['name'] !== $token['name']);
        $tokens[$last['id']] += [
          'length' => $token['start'] - $last['end'],
          'verified' => TRUE,
        ];
        $tokens[$i]['verified'] = TRUE;
      }
    }
    else {

      // Stack this token together with its position.
      $stack[] = $token + [
        'id' => $i,
      ];
      $counter[$token['name']]++;
    }
  }

  // Filter the tokens.
  return array_filter($tokens, static function ($token) {
    return !empty($token['verified']);
  });
}