1<?php
2
3/*
4 * This file is part of the clockoon/dokuwiki-commonmark-plugin package.
5 *
6 * (c) Sungbin Jeon <clockoon@gmail.com>
7 *
8 * Original code based on the followings:
9 * - CommonMark JS reference parser (https://bitly.com/commonmark-js) (c) John MacFarlane
10 * - league/commonmark (https://github.com/thephpleague/commonmark) (c) Colin O'Dell <colinodell@gmail.com>
11 *
12 * For the full copyright and license information, please view the LICENSE
13 * file that was distributed with this source code.
14 */
15
16namespace Dokuwiki\Plugin\Commonmark;
17
18use League\CommonMark\Node\Block\AbstractBlock;
19use League\CommonMark\Renderer\NodeRendererInterface;
20use League\CommonMark\Node\Inline\AbstractInline;
21use League\CommonMark\Renderer\ChildNodeRendererInterface;
22use League\CommonMark\Environment\EnvironmentInterface;
23use League\CommonMark\Node\Block\Document;
24use League\CommonMark\Node\Node;
25
26/**
27 * Renders a parsed AST to DW
28 */
29final class DWRenderer implements ChildNodeRendererInterface
30{
31    /**
32     * @var EnvironmentInterface
33     */
34    protected $environment;
35
36    /**
37     * @param EnvironmentInterface $environment
38     */
39    public function __construct(EnvironmentInterface $environment)
40    {
41        $this->environment = $environment;
42    }
43
44    public function getBlockSeparator(): string
45    {
46        return $this->environment->getConfiguration()->get('renderer/block_separator');
47    }
48
49    public function getInnerSeparator(): string
50    {
51        return $this->environment->getConfiguration()->get('renderer/inner_separator');
52    }
53
54    /**
55     * @param string $option
56     * @param mixed  $default
57     *
58     * @return mixed|null
59     */
60    public function getOption(string $option, $default = null)
61    {
62        return $this->environment->getConfiguration()->get('renderer/' . $option, $default);
63    }
64
65    public function renderNodes(iterable $nodes): string
66    {
67        $output = '';
68
69        $isFirstItem = true;
70
71        foreach ($nodes as $node) {
72            if (! $isFirstItem && $node instanceof AbstractBlock) {
73                $output .= $this->getBlockSeparator();
74            }
75
76            $output .= $this->renderNode($node);
77
78            $isFirstItem = false;
79        }
80
81        return $output;
82    }
83
84    public function renderNode(Node $node)
85    {
86        $renderers = $this->environment->getRenderersForClass(\get_class($node));
87
88        foreach ($renderers as $renderer) {
89            \assert($renderer instanceof NodeRendererInterface);
90            if (($result = $renderer->render($node, $this)) !== null) {
91                return $result;
92            }
93        }
94
95        throw new \RuntimeException('Unable to find corresponding renderer for node type ' . \get_class($node));
96
97    }
98
99
100}