xref: /plugin/commonmark/src/Dokuwiki/Plugin/Commonmark/Extension/Renderer/Block/FencedCodeRenderer.php (revision 8ec9a8f2fa8d03e80395a040a2626880092b4ddf)
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\Extension\Renderer\Block;
17
18use League\CommonMark\Block\Element\AbstractBlock;
19use League\CommonMark\Block\Element\FencedCode;
20use League\CommonMark\ElementRendererInterface;
21use League\CommonMark\HtmlElement;
22use League\CommonMark\Util\Xml;
23use League\CommonMark\Block\Renderer\BlockRendererInterface;
24
25final class FencedCodeRenderer implements BlockRendererInterface
26{
27    /**
28     * @param FencedCode               $block
29     * @param ElementRendererInterface $htmlRenderer
30     * @param bool                     $inTightList
31     *
32     * @return HtmlElement
33     */
34    public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false)
35    {
36        if (!($block instanceof FencedCode)) {
37            throw new \InvalidArgumentException('Incompatible block type: ' . \get_class($block));
38        }
39
40        $attrs = $block->getData('attributes', []);
41
42        $infoWords = $block->getInfoWords();
43
44        if (\count($infoWords) !== 0 && \strlen($infoWords[0]) !== 0) {
45            if ($infoWords[0] == 'html') {
46                # only supports html block; it is not possible for express html inline span in Commonmark syntax
47                $entertag = 'HTML';
48                $exittag = 'HTML';
49            }
50            elseif ($infoWords[0] == 'nowiki' || $infoWords[0] == 'dokuwiki' ) {
51                # support DW <nowiki> syntax & passing DW codes (e.g. tag, struct, etc.)
52                $entertag = $infoWords[0];
53                $exittag = $infoWords[0];
54            }
55            else {
56                $entertag = 'code ' . $infoWords[0];
57                $exittag = 'code';
58            }
59        }
60
61        $result = '<' . $entertag . ">\n" .
62        Xml::escape($block->getStringContent()) . "</" . $exittag . ">";
63        return $result;
64
65    }
66}
67