Passed
Branch refactor-markdown-helper (02b3eb)
by Caen
04:15
created

MarkdownFileParser::__construct()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 17
rs 9.9666
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\MarkdownFileServiceTest
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
41
            if ($object->body()) {
42
                $this->body = $object->body();
43
            }
44
        } else {
45
            $this->body = $stream;
46
        }
47
    }
48
49
    /**
50
     * Get the processed Markdown file as a MarkdownDocument.
51
     */
52
    public function get(): MarkdownDocument
53
    {
54
        return new MarkdownDocument($this->matter, $this->body);
55
    }
56
}
57