public static function XBBCodeParser::validateTokens in Extensible BBCode 4.0.x
Same name and namespace in other branches
- 8.3 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 187
Class
- XBBCodeParser
- The standard XBBCode parser.
Namespace
Drupal\xbbcode\ParserCode
public static function validateTokens(array $tokens) : array {
// Initialize the counter for each tag name.
$counter = [];
foreach ($tokens as $token) {
$counter[$token['cname']] = 0;
}
$stack = [];
foreach ($tokens as $i => $token) {
if ($token['closing']) {
if ($counter[$token['cname']] > 0) {
// Pop the stack until a matching token is reached.
do {
$last = array_pop($stack);
$counter[$last['cname']]--;
} while ($last['cname'] !== $token['cname']);
$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['cname']]++;
}
}
// Filter the tokens.
return array_filter($tokens, static function ($token) {
return !empty($token['verified']);
});
}