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