Passed
Push — master ( 301e3e...f73be1 )
by Caen
03:14 queued 11s
created

BladeDownProcessor::postprocess()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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