Passed
Push — master ( 246ca5...f72f04 )
by Caen
03:27 queued 14s
created

MarkdownFileParser::__construct()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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