Test Setup Failed
Pull Request — latest (#3)
by Mark
34:19
created

DocumentRenderer::renderNodes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 1
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 League\Configuration\ConfigurationAwareInterface;
20
use UnicornFail\Emoji\Environment\EnvironmentInterface;
21
use UnicornFail\Emoji\Event\DocumentRenderedEvent;
22
use UnicornFail\Emoji\Exception\RenderNodeException;
23
use UnicornFail\Emoji\Node\Document;
24
use UnicornFail\Emoji\Node\Node;
25
26
final class DocumentRenderer implements DocumentRendererInterface
27
{
28
    /** @var EnvironmentInterface */
29
    private $environment;
30
31
    public function __construct(EnvironmentInterface $environment)
32
    {
33
        $this->environment = $environment;
34
    }
35
36
    public function renderDocument(Document $document): string
37
    {
38
        $output = '';
39
40
        foreach ($document->getNodes() as $node) {
41
            $output .= $this->renderNode($node);
42
        }
43
44
        $event = new DocumentRenderedEvent($output);
45
46
        $this->environment->dispatch($event);
47
48
        return $event->getContent();
49
    }
50
51
    /**
52
     * @return \Stringable|string
53
     *
54
     * @throws RenderNodeException
55
     */
56
    private function renderNode(Node $node)
57
    {
58
        $renderers = $this->environment->getRenderersForClass(\get_class($node));
59
60
        /** @var NodeRendererInterface $renderer */
61
        foreach ($renderers as $renderer) {
62
            if ($renderer instanceof ConfigurationAwareInterface) {
63
                $renderer->setConfiguration($this->environment->getConfiguration());
64
            }
65
66
            if (($result = $renderer->render($node)) !== null) {
67
                return $result;
68
            }
69
        }
70
71
        throw new RenderNodeException(\sprintf('Unable to find corresponding renderer for node type %s', \get_class($node)));
72
    }
73
}
74