From 9d407c370605fa29bc77efd0db1dcc2da5b8a30e Mon Sep 17 00:00:00 2001 From: Michael Ochmann Date: Thu, 18 Aug 2022 17:19:36 +0200 Subject: [PATCH] now parsing `id` and `class` annotations on paragraphs --- src/Parser.php | 53 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/Parser.php b/src/Parser.php index 208db2e..ff48133 100644 --- a/src/Parser.php +++ b/src/Parser.php @@ -2,6 +2,7 @@ namespace parkdown; +use Attribute; use DOMDocument; use DOMElement; use DOMNode; @@ -11,6 +12,11 @@ enum ListType { case UNORDERED; } +class Attributes { + public array $classes = []; + public ?string $id = null; +} + class Parser { const MAGIC_CHAR = "*"; @@ -148,8 +154,8 @@ class Parser { } private function parseText($paragraph = false) : array { - $elms = []; - $buffer = ""; + $elms = []; + $buffer = ""; $clearBuffer = function() use (&$elms, &$buffer) { array_push($elms, $this->document->createTextNode($buffer)); @@ -228,6 +234,41 @@ class Parser { $clearBuffer(); array_push($elms, $elm); continue; + } elseif ($this->current()->type === TokenType::LBRACE) { + $lbrace = $this->consume(); + assert($lbrace->type === TokenType::LBRACE, "expected left brace, got ".$lbrace->type->name); + + $content = ""; + while ($this->current()->type !== TokenType::EOF && + $this->current()->type !== TokenType::EOL && + $this->current()->type !== TokenType::RBRACE) { + $content .= $this->consume()->data; + } + $rbrace = $this->consume(); + assert($rbrace->type === TokenType::RBRACE, "expected right brace, got ".$rbrace->type->name); + + $attributes = array_map(function($element) { + return trim($element); + }, explode(',', $content)); + + $obj = new Attributes(); + + foreach($attributes as $attribute) { + if (!in_array($attribute[0], [".", "#"])) + continue; + switch ($attribute[0]) { + case ".": + array_push($obj->classes, substr($attribute, 1)); + break; + case "#": + $obj->id = substr($attribute, 1); + break; + default: + continue 2; + } + } + + array_push($elms, $obj); } else $buffer .= self::StripBackslashes($this->consume()->data); } @@ -307,6 +348,14 @@ class Parser { $elm = $this->document->createElement("p"); $i = 0; foreach ($elms as $node) { + if ($node instanceof Attributes) { + if (count($node->classes) > 0) + $elm->setAttribute("class", join(" ", $node->classes)); + if ($node->id) + $elm->setAttribute("id", $node->id); + + continue; + } if ($node->nodeName === "#text" && trim($node->textContent) === "") continue; $elm->appendChild($node);