From 889cca12b5d4eac1308a33ab7088b4f63cfb663a Mon Sep 17 00:00:00 2001 From: yggverse Date: Mon, 24 Jun 2024 04:46:15 +0300 Subject: [PATCH] implement Header entity support --- src/Document.php | 14 +++++++++ src/Entity/Header.php | 73 +++++++++++++++++++++++++++++++++++++++++++ src/Parser/Header.php | 63 +++++++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 src/Entity/Header.php create mode 100644 src/Parser/Header.php diff --git a/src/Document.php b/src/Document.php index f75a6be..2b703eb 100644 --- a/src/Document.php +++ b/src/Document.php @@ -32,6 +32,20 @@ class Document break; + // Header + case Parser\Header::match($line): + + $this->_entities[] = new Entity\Header( + Parser\Header::getLevel( + $line + ), + Parser\Header::getText( + $line + ) + ); + + break; + // Link case Parser\Link::match($line): diff --git a/src/Entity/Header.php b/src/Entity/Header.php new file mode 100644 index 0000000..df3b830 --- /dev/null +++ b/src/Entity/Header.php @@ -0,0 +1,73 @@ +setLevel( + $level + ); + + $this->setText( + $text + ); + } + + public function setLevel( + int $level + ): void + { + if (!in_array($level, [1, 2, 3])) + { + throw new \Exception( + _('Incorrect header level') + ); + } + + $this->_level = $level; + } + + public function getLevel(): int + { + return $this->_level; + } + + public function setText( + ?string $text + ): void + { + if ($text) + { + $text = trim( + $text + ); + } + + $this->_text = $text; + } + + public function getText(): ?string + { + return $this->_text; + } + + public function toString(): string + { + return str_repeat( + self::TAG, + $this->_level + ) . $this->_text; + } +} \ No newline at end of file diff --git a/src/Parser/Header.php b/src/Parser/Header.php new file mode 100644 index 0000000..89e9c0e --- /dev/null +++ b/src/Parser/Header.php @@ -0,0 +1,63 @@ +#{1,3})(?.*)$/m', + $line, + $matches + ); + } + + public static function getLevel( + string $line + ): ?int + { + $matches = []; + + if (self::match($line, $matches)) + { + if (isset($matches['level'])) + { + return (int) strlen( + $matches['level'] + ); + } + } + + return null; + } + + public static function getText( + string $line + ): ?string + { + $matches = []; + + if (self::match($line, $matches)) + { + if (isset($matches['text'])) + { + $text = trim( + $matches['text'] + ); + + if ($text) + { + return $text; + } + } + } + + return null; + } +} \ No newline at end of file