Skip to content

Commit

Permalink
fix parser
Browse files Browse the repository at this point in the history
  • Loading branch information
bangnokia committed May 9, 2024
1 parent 2d32236 commit 3a9b4a1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
8 changes: 7 additions & 1 deletion app/ContentFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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)) {
Expand Down
8 changes: 8 additions & 0 deletions app/Exceptions/InvalidMarkdownContent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace BangNokia\Lina\Exceptions;

class InvalidMarkdownContent extends \Exception
{

}
28 changes: 20 additions & 8 deletions app/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace BangNokia\Lina;

use BangNokia\Lina\Contracts\MarkdownParser;
use BangNokia\Lina\Exceptions\InvalidMarkdownContent;
use Symfony\Component\Yaml\Yaml;

class Parser
Expand All @@ -16,23 +17,34 @@ public function __construct(MarkdownParser $markdownParser)

public function parse(string $text): array
{
['yaml' => $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)),
Expand Down

0 comments on commit 3a9b4a1

Please sign in to comment.