xref: /plugin/commonmark/src/Dokuwiki/Plugin/Commonmark/Extension/Renderer/Block/FencedCodeRenderer.php (revision 1adb3ebefb90af6f365426740ef114014c847a10)
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        $entertag = '';
44        if (\count($infoWords) !== 0 && \strlen($infoWords[0]) !== 0) {
45            switch($infoWords[0]) {
46                case 'html':
47                    # only supports html block; it is not possible for express html inline span in Commonmark syntax
48                    $entertag = 'HTML';
49                    $exittag = 'HTML';
50                    break;
51                case 'nowiki':
52                    # DW <nowiki> syntax
53                    $entertag = $infoWords[0];
54                    $exittag = $infoWords[0];
55                    break;
56                case 'dokuwiki':
57                    # passing DW codes (e.g. tag, struct, etc.)
58                    $entertag = '';
59                    $exittag = '';
60                    break;
61                default:
62                    $entertag = 'code ' . $infoWords[0];
63                    $exittag = 'code';
64            }
65        }
66        $result = Xml::escape($block->getStringContent());
67        if ($entertag):
68            $result = '<' . $entertag . ">\n" . $result . "</" . $exittag . ">";
69        endif;
70        return $result;
71    }
72}
73