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\Extension\CommonMark\Node\Block\ListItem;
19use League\CommonMark\Extension\TaskList\TaskListItemMarker;
20use League\CommonMark\Node\Block\Paragraph;
21use League\CommonMark\Node\Node;
22use League\CommonMark\Renderer\ChildNodeRendererInterface;
23use League\CommonMark\Renderer\NodeRendererInterface;
24use League\CommonMark\Xml\XmlNodeRendererInterface;
25
26final class ListItemRenderer implements NodeRendererInterface
27{
28    /**
29     * @param ListItem                 $block
30     * @param ChildNodeRendererInterface $DWRenderer
31     * @param bool                     $inTightList
32     *
33     * @return string
34     */
35    public function render(Node $node, ChildNodeRendererInterface $DWRenderer): string
36    {
37        ListItem::assertInstanceOf($node);
38
39        $result = $DWRenderer->renderNodes($node->children());
40        if (\substr($result, 0, 1) === '<' && \substr($result, 0, 5) !== '<del>' && !$this->startsTaskListItem($node)) {
41            $result = "\n" . $result;
42        }
43        if (\substr($result, -1, 1) === '>') {
44            $result .= "\n";
45        }
46
47        $result = preg_replace('/\n\n/', "\n", $result); # remove unwanted newline for DW
48
49        return "<li>" . $result;
50    }
51
52    private function startsTaskListItem(Node $node): bool
53    {
54        $firstChild = $node->firstChild();
55
56        return $firstChild instanceof Paragraph && $firstChild->firstChild() instanceof TaskListItemMarker;
57    }
58}
59