From 3a9b4a1a0a8827557917a4077b1b048fee1e108c Mon Sep 17 00:00:00 2001 From: bangnokia Date: Thu, 9 May 2024 16:32:09 +0700 Subject: [PATCH] fix parser --- app/ContentFinder.php | 8 ++++++- app/Exceptions/InvalidMarkdownContent.php | 8 +++++++ app/Parser.php | 28 ++++++++++++++++------- 3 files changed, 35 insertions(+), 9 deletions(-) create mode 100644 app/Exceptions/InvalidMarkdownContent.php diff --git a/app/ContentFinder.php b/app/ContentFinder.php index c86dcea..9e051b6 100644 --- a/app/ContentFinder.php +++ b/app/ContentFinder.php @@ -3,6 +3,7 @@ namespace BangNokia\Lina; use BangNokia\Lina\Exceptions\ContentNotFoundException; +use BangNokia\Lina\Exceptions\InvalidMarkdownContent; use BangNokia\Lina\Exceptions\ManyContentFound; use Symfony\Component\Finder\Finder; @@ -47,7 +48,12 @@ public function get(string $filePath, $absolute = false): Content $content = file_get_contents($absolutePath); - $data = (new Parser(new MarkdownParser()))->parse($content); + try { + $data = (new Parser(new MarkdownParser()))->parse($content); + } catch (\Exception $exception) { + throw new InvalidMarkdownContent($filePath); + } + $fileName = basename($filePath, '.md'); if (preg_match('/(\d{4}-\d{2}-\d{2}-)?(.*)/', $fileName, $matches)) { diff --git a/app/Exceptions/InvalidMarkdownContent.php b/app/Exceptions/InvalidMarkdownContent.php new file mode 100644 index 0000000..319c7d1 --- /dev/null +++ b/app/Exceptions/InvalidMarkdownContent.php @@ -0,0 +1,8 @@ + $yaml, 'markdown' => $markdown] = $this->classify($text); - - return [ - 'front_matter' => $this->parseFrontMatter($yaml), - 'content' => $this->markdownParser->parse($markdown) - ]; + try { + ['yaml' => $yaml, 'markdown' => $markdown] = $this->classify($text); + + return [ + 'front_matter' => $this->parseFrontMatter($yaml), + 'content' => $this->markdownParser->parse($markdown) + ]; + } catch (\Exception $exception) { + throw new InvalidMarkdownContent($text); + } } - public function parseFrontMatter(string $text): array + public function parseFrontMatter(string $text): ?array { - return Yaml::parse($text); + return Yaml::parse($text) ?? []; } public function classify(string $text): array { $pos = strpos($text, '---', 1); + if ($pos === false) { + return [ + 'yaml' => '', + 'markdown' => $text, + ]; + } + return [ 'yaml' => trim(substr($text, 4, $pos - 4)), 'markdown' => trim(substr($text, $pos + 4)),