1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file was originally part of the league/commonmark package. |
7
|
|
|
* |
8
|
|
|
* (c) Colin O'Dell <[email protected]> |
9
|
|
|
* |
10
|
|
|
* Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) |
11
|
|
|
* - (c) John MacFarlane |
12
|
|
|
* |
13
|
|
|
* For the full copyright and license information, please view the LICENSE |
14
|
|
|
* file that was distributed with this source code. |
15
|
|
|
*/ |
16
|
|
|
|
17
|
|
|
namespace UnicornFail\Emoji\Renderer; |
18
|
|
|
|
19
|
|
|
use UnicornFail\Emoji\Environment\EnvironmentInterface; |
20
|
|
|
use UnicornFail\Emoji\Event\DocumentRenderedEvent; |
21
|
|
|
use UnicornFail\Emoji\Node\Block\Document; |
22
|
|
|
use UnicornFail\Emoji\Node\Node; |
23
|
|
|
use UnicornFail\Emoji\Output\RenderedContent; |
24
|
|
|
use UnicornFail\Emoji\Output\RenderedContentInterface; |
25
|
|
|
|
26
|
|
|
final class Renderer implements RendererInterface, ChildNodeRendererInterface |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
|
|
* @var EnvironmentInterface |
30
|
|
|
* |
31
|
|
|
* @psalm-readonly |
32
|
|
|
*/ |
33
|
|
|
private $environment; |
34
|
|
|
|
35
|
|
|
public function __construct(EnvironmentInterface $environment) |
36
|
|
|
{ |
37
|
|
|
$this->environment = $environment; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function renderDocument(Document $document): RenderedContentInterface |
41
|
|
|
{ |
42
|
|
|
$output = new RenderedContent($document, (string) $this->renderNode($document)); |
43
|
|
|
|
44
|
|
|
$event = new DocumentRenderedEvent($output); |
45
|
|
|
$this->environment->dispatch($event); |
46
|
|
|
|
47
|
|
|
return $event->getContent(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
|
|
public function renderNodes(iterable $nodes): string |
54
|
|
|
{ |
55
|
|
|
$output = ''; |
56
|
|
|
|
57
|
|
|
foreach ($nodes as $node) { |
58
|
|
|
$output .= $this->renderNode($node); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $output; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @return \Stringable|string |
66
|
|
|
* |
67
|
|
|
* @throws \RuntimeException |
68
|
|
|
*/ |
69
|
|
|
private function renderNode(Node $node) |
70
|
|
|
{ |
71
|
|
|
$renderers = $this->environment->getRenderersForClass(\get_class($node)); |
72
|
|
|
|
73
|
|
|
/** @var NodeRendererInterface $renderer */ |
74
|
|
|
foreach ($renderers as $renderer) { |
75
|
|
|
if (($result = $renderer->render($node, $this)) !== null) { |
76
|
|
|
return $result; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
throw new \RuntimeException('Unable to find corresponding renderer for node type ' . \get_class($node)); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|