xref: /plugin/commonmark/src/Dokuwiki/Plugin/Commonmark/Extension/Renderer/Block/FencedCodeRenderer.php (revision 36bc9d521533aae096a27d463e209dcb9e0b5e33)
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\Util\Xml;
22use League\CommonMark\Block\Renderer\BlockRendererInterface;
23
24final class FencedCodeRenderer implements BlockRendererInterface
25{
26    /**
27     * @param FencedCode               $block
28     * @param ElementRendererInterface $DWRenderer
29     * @param bool                     $inTightList
30     *
31     * @return string
32     */
33    public function render(AbstractBlock $block, ElementRendererInterface $DWRenderer, bool $inTightList = false)
34    {
35        if (!($block instanceof FencedCode)) {
36            throw new \InvalidArgumentException('Incompatible block type: ' . \get_class($block));
37        }
38
39        $attrs = $block->getData('attributes', []);
40
41        $infoWords = $block->getInfoWords();
42
43        if (\count($infoWords) !== 0 && \strlen($infoWords[0]) !== 0) {
44            switch($infoWords[0]) {
45                case '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                    break;
50                case 'nowiki':
51                    # DW <nowiki> syntax
52                    $entertag = $infoWords[0];
53                    $exittag = $infoWords[0];
54                    break;
55                case 'dokuwiki':
56                    # passing DW codes (e.g. tag, struct, etc.)
57                    $entertag = '';
58                    $exittag = '';
59                    break;
60                default:
61                    $entertag = 'code ' . $infoWords[0];
62                    $exittag = 'code';
63            }
64        }
65        $result = Xml::escape($block->getStringContent());
66        if ($entertag):
67            $result = '<' . $entertag . ">\n" . $result . "</" . $exittag . ">";
68        endif;
69        return $result;
70    }
71}
72