Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
MarkdownFileParser
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
3 / 3
6
100.00% covered (success)
100.00%
1 / 1
 parse
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 get
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Hyde\Framework\Actions;
6
7use Hyde\Facades\Filesystem;
8use Hyde\Markdown\Models\MarkdownDocument;
9use Spatie\YamlFrontMatter\YamlFrontMatter;
10
11use function str_starts_with;
12
13/**
14 * Prepares a Markdown file for further usage by extracting the Front Matter
15 * and Markdown body, and creating MarkdownDocument object from them.
16 */
17class MarkdownFileParser
18{
19    /**
20     * @param  string  $path  The path to the Markdown file tp parse.
21     * @return MarkdownDocument The processed Markdown file as a MarkdownDocument.
22     */
23    public static function parse(string $path): MarkdownDocument
24    {
25        return (new static($path))->get();
26    }
27
28    /**
29     * The extracted Front Matter.
30     */
31    protected array $matter = [];
32
33    /**
34     * The extracted Markdown body.
35     */
36    protected string $markdown = '';
37
38    protected function __construct(string $path)
39    {
40        $stream = Filesystem::getContents($path);
41
42        // Check if the file has Front Matter.
43        if (str_starts_with($stream, '---')) {
44            $document = YamlFrontMatter::markdownCompatibleParse($stream);
45
46            if ($document->matter()) {
47                $this->matter = (array) $document->matter();
48            }
49
50            if ($document->body()) {
51                $this->markdown = $document->body();
52            }
53        } else {
54            $this->markdown = $stream;
55        }
56    }
57
58    protected function get(): MarkdownDocument
59    {
60        return new MarkdownDocument($this->matter, $this->markdown);
61    }
62}