1<?php 2 3/* 4 * This file is part of the league/commonmark package. 5 * 6 * (c) Colin O'Dell <colinodell@gmail.com> 7 * 8 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) 9 * - (c) John MacFarlane 10 * 11 * For the full copyright and license information, please view the LICENSE 12 * file that was distributed with this source code. 13 */ 14 15namespace League\CommonMark\Block\Renderer; 16 17use League\CommonMark\Block\Element\AbstractBlock; 18use League\CommonMark\Block\Element\ListItem; 19use League\CommonMark\Block\Element\Paragraph; 20use League\CommonMark\ElementRendererInterface; 21use League\CommonMark\Extension\TaskList\TaskListItemMarker; 22use League\CommonMark\HtmlElement; 23 24final class ListItemRenderer implements BlockRendererInterface 25{ 26 /** 27 * @param ListItem $block 28 * @param ElementRendererInterface $htmlRenderer 29 * @param bool $inTightList 30 * 31 * @return string 32 */ 33 public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false) 34 { 35 if (!($block instanceof ListItem)) { 36 throw new \InvalidArgumentException('Incompatible block type: ' . \get_class($block)); 37 } 38 39 $contents = $htmlRenderer->renderBlocks($block->children(), $inTightList); 40 if (\substr($contents, 0, 1) === '<' && !$this->startsTaskListItem($block)) { 41 $contents = "\n" . $contents; 42 } 43 if (\substr($contents, -1, 1) === '>') { 44 $contents .= "\n"; 45 } 46 47 $attrs = $block->getData('attributes', []); 48 49 $li = new HtmlElement('li', $attrs, $contents); 50 51 return $li; 52 } 53 54 private function startsTaskListItem(ListItem $block): bool 55 { 56 $firstChild = $block->firstChild(); 57 58 return $firstChild instanceof Paragraph && $firstChild->firstChild() instanceof TaskListItemMarker; 59 } 60} 61