/** * Constructs the parse tree from a string of bbcode markup. * * @param string $str the bbcode markup to parse */ public function parse($str) { $this->reset(); $parent = $this->treeRoot; $tokenManager = new TokenManager($str); $nodeid = 1; $inTag = false; while ($tokenManager->hasCurrent()) { // tokens are either "[", "]" or a string that contains neither a opening bracket nor a closing bracket if ($inTag) { // this token should be a tag name // explode by = in case there's an attribute $pieces = explode('=', $tokenManager->getCurrent(), 2); // check if it's a closing tag if (substr($pieces[0], 0, 1) == "/") { $tagName = substr($pieces[0], 1); $closing = true; } else { $tagName = $pieces[0]; $closing = false; } if (($this->codeExists($tagName, isset($pieces[1])) || $closing && $this->codeExists($tagName, true)) && $tokenManager->hasNext() && $tokenManager->next() == "]") { if ($closing) { $closestParent = $parent->closestParentOfType($tagName); if ($closestParent != null && $closestParent->hasParent()) { // closing an element... move to this element's parent $parent->getCodeDefinition()->decrementCounter(); $parent = $closestParent->getParent(); $tokenManager->advance(); $tokenManager->advance(); $inTag = false; continue; } } else { // new element $el = new ElementNode(); $code = $this->getCode($tagName, isset($pieces[1])); $code->incrementCounter(); $el->setNestDepth($code->getCounter()); $el->setCodeDefinition($code); $el->setTagName($tagName); $el->setNodeId($nodeid++); if (isset($pieces[1])) { $el->setAttribute($pieces[1]); } $parent->addChild($el); $parent = $el; $tokenManager->advance(); $tokenManager->advance(); $inTag = false; continue; } } // the opening bracket that sent us in here was really just plain text $node = new TextNode("["); $node->setNodeId($nodeid++); $parent->addChild($node); $inTag = false; // treat this token as regular text, and let the next if...else structure handle it as regular text } if ($tokenManager->getCurrent() == "[") { $inTag = true; } else { $node = new TextNode($tokenManager->getCurrent()); $node->setNodeId($nodeid++); $parent->addChild($node); } $tokenManager->advance(); } }