DocumentRenderer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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