Test Failed
Push — master ( ac7470...82dec8 )
by Caen
14:29 queued 12s
created

MarkdownFileParser::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Hyde\Framework\Modules\Markdown;
4
5
use Hyde\Framework\Models\MarkdownDocument;
6
use Spatie\YamlFrontMatter\YamlFrontMatter;
7
8
/**
9
 * Prepares a Markdown file for further usage by extracting the Front Matter and creating MarkdownDocument object.
10
 *
11
 * @see \Hyde\Framework\Testing\Feature\MarkdownFileParserTest
12
 */
13
class MarkdownFileParser
14
{
15
    /**
16
     * The extracted Front Matter.
17
     *
18
     * @var array
19
     */
20
    public array $matter = [];
21
22
    /**
23
     * The extracted Markdown body.
24
     *
25
     * @var string
26
     */
27
    public string $body = '';
28
29
    public function __construct(string $filepath)
30
    {
31
        $stream = file_get_contents($filepath);
32
33
        // Check if the file has Front Matter.
34
        if (str_starts_with($stream, '---')) {
35
            $object = YamlFrontMatter::markdownCompatibleParse($stream);
36
37
            if ($object->matter()) {
38
                $this->matter = $object->matter();
39
40
                // Unset the slug from the matter, as it can cause problems if it exists.
41
                unset($this->matter['slug']);
42
            }
43
44
            if ($object->body()) {
45
                $this->body = $object->body();
46
            }
47
        } else {
48
            $this->body = $stream;
49
        }
50
    }
51
52
    /**
53
     * Get the processed Markdown file as a MarkdownDocument.
54
     */
55
    public function get(): MarkdownDocument
56
    {
57
        return new MarkdownDocument($this->matter, $this->body);
58
    }
59
60
    public static function parse(string $filepath): MarkdownDocument
61
    {
62
        return (new self($filepath))->get();
63
    }
64
}
65