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

MarkdownFileParser   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 50
rs 10
c 1
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 3 1
A __construct() 0 20 4
A parse() 0 3 1
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