Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
9 / 9 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| MarkdownFileService | |
100.00% |
9 / 9 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
4 | |||
| get | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Hyde\Framework\Services; |
| 4 | |
| 5 | use Hyde\Framework\Models\MarkdownDocument; |
| 6 | use JetBrains\PhpStorm\Pure; |
| 7 | use Spatie\YamlFrontMatter\YamlFrontMatter; |
| 8 | |
| 9 | /** |
| 10 | * Prepares a Markdown file for further usage. |
| 11 | * The service splits the Front Matter and creates a Markdown Document Object. |
| 12 | */ |
| 13 | class MarkdownFileService |
| 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 | * @return MarkdownDocument |
| 53 | */ |
| 54 | #[Pure] |
| 55 | public function get(): MarkdownDocument |
| 56 | { |
| 57 | return new MarkdownDocument($this->matter, $this->body); |
| 58 | } |
| 59 | } |