|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Hyde\Framework\Models\Markdown; |
|
4
|
|
|
|
|
5
|
|
|
use Hyde\Framework\Modules\Markdown\MarkdownConverter; |
|
6
|
|
|
use Hyde\Framework\Services\MarkdownService; |
|
7
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* A simple object representation of a Markdown file, with helpful methods to interact with it. |
|
11
|
|
|
* |
|
12
|
|
|
* @see \Hyde\Framework\Testing\Unit\MarkdownDocumentTest |
|
13
|
|
|
*/ |
|
14
|
|
|
class Markdown implements Arrayable, \Stringable |
|
15
|
|
|
{ |
|
16
|
|
|
public string $body; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct(string $body = '') |
|
19
|
|
|
{ |
|
20
|
|
|
$this->body = $body; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
public function __toString(): string |
|
24
|
|
|
{ |
|
25
|
|
|
return $this->body; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function body(): string |
|
29
|
|
|
{ |
|
30
|
|
|
return $this->body; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function compile(?string $sourceModel = null): string |
|
34
|
|
|
{ |
|
35
|
|
|
return static::render($this->body, $sourceModel); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Return the Markdown document body explored by line into an array. |
|
40
|
|
|
* |
|
41
|
|
|
* @return string[] |
|
42
|
|
|
*/ |
|
43
|
|
|
public function toArray(): array |
|
44
|
|
|
{ |
|
45
|
|
|
return explode("\n", $this->body); |
|
|
|
|
|
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public static function fromFile(string $localFilepath): static |
|
49
|
|
|
{ |
|
50
|
|
|
return MarkdownDocument::parse($localFilepath)->markdown(); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Render a Markdown string into HTML. |
|
55
|
|
|
* |
|
56
|
|
|
* If a source model is provided, the Markdown will be converted using the dynamic MarkdownService, |
|
57
|
|
|
* otherwise, the pre-configured singleton from the service container will be used instead. |
|
58
|
|
|
* |
|
59
|
|
|
* @return string $html |
|
60
|
|
|
*/ |
|
61
|
|
|
public static function render(string $markdown, ?string $sourceModel = null): string |
|
62
|
|
|
{ |
|
63
|
|
|
return $sourceModel !== null |
|
64
|
|
|
? (new MarkdownService($markdown, $sourceModel))->parse() |
|
65
|
|
|
: app(MarkdownConverter::class)->convert($markdown); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: