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

BladeDownProcessor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Hyde\Framework\Modules\Markdown;
4
5
use Illuminate\Support\Facades\Blade;
6
7
/**
8
 * Markdown Processor to render Laravel Blade within Markdown files.
9
 *
10
 * Works on a line-by-line basis by searching for a line starting with the directive.
11
 * The preprocessor expands the directive to an HTML comment. The post-processor parses it.
12
 *
13
 * @example: [Blade]: {{ time() }}
14
 * @example: [Blade]: @include('path/to/view.blade.php')
15
 *
16
 * @see \Hyde\Framework\Testing\Feature\Services\BladeDownProcessorTest
17
 * @phpstan-consistent-constructor
18
 */
19
class BladeDownProcessor
20
{
21
    protected string $html;
22
    protected string $output;
23
24
    protected array $pageData = [];
25
26
    public static function render(string $html, ?array $pageData = []): string
27
    {
28
        return (new static(static::preprocess($html), $pageData))->run()->get();
29
    }
30
31
    public static function preprocess(string $markdown): string
32
    {
33
        return implode("\n", array_map(function ($line) {
34
            return str_starts_with(strtolower($line), strtolower('[Blade]:'))
35
                ? '<!-- HYDE'.trim(htmlentities($line)).' -->'
36
                : $line;
37
        }, explode("\n", $markdown)));
38
    }
39
40
    public static function process(string $html, ?array $pageData = []): string
41
    {
42
        return (new static($html, $pageData))->run()->get();
43
    }
44
45
    public function __construct(string $html, ?array $pageData = [])
46
    {
47
        $this->html = $html;
48
        $this->pageData = $pageData;
49
    }
50
51
    public function run(): static
52
    {
53
        $this->output = implode("\n", array_map(function ($line) {
54
            return $this->lineStartsWithDirective($line)
55
                ? $this->processLine($line)
56
                : $line;
57
        }, explode("\n", $this->html)));
58
59
        return $this;
60
    }
61
62
    public function get(): string
63
    {
64
        return $this->output;
65
    }
66
67
    protected function lineStartsWithDirective(string $line): bool
68
    {
69
        return str_starts_with(strtolower($line), '<!-- hyde[blade]:');
70
    }
71
72
    protected function processLine(string $line): string
73
    {
74
        return Blade::render(
75
            substr(substr(html_entity_decode($line), 18), 0, -4),
76
            $this->pageData
77
        );
78
    }
79
}
80