ListItemConverter   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 24
c 2
b 0
f 0
dl 0
loc 58
ccs 25
cts 25
cp 1
rs 10
wmc 16

3 Methods

Rating   Name   Duplication   Size   Complexity  
C convert() 0 37 14
A setConfig() 0 3 1
A getSupportedTags() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\HTMLToMarkdown\Converter;
6
7
use League\HTMLToMarkdown\Configuration;
8
use League\HTMLToMarkdown\ConfigurationAwareInterface;
9
use League\HTMLToMarkdown\ElementInterface;
10
11
class ListItemConverter implements ConverterInterface, ConfigurationAwareInterface
12
{
13
    /** @var Configuration */
14
    protected $config;
15
16
    /** @var string|null */
17
    protected $listItemStyle;
18
19
    public function setConfig(Configuration $config): void
20
    {
21
        $this->config = $config;
22
    }
23
24 99
    public function convert(ElementInterface $element): string
25
    {
26 99
        // If parent is an ol, use numbers, otherwise, use dashes
27 99
        $listType = ($parent = $element->getParent()) ? $parent->getTagName() : 'ul';
28
29
        // Add spaces to start for nested list items
30
        $level = $element->getListItemLevel();
31
32
        $value = \trim(\implode("\n" . '    ', \explode("\n", \trim($element->getValue()))));
33
34 12
        // If list item is the first in a nested list, add a newline before it
35
        $prefix = '';
36
        if ($level > 0 && $element->getSiblingPosition() === 1) {
37 12
            $prefix = "\n";
38
        }
39
40 12
        if ($listType === 'ul') {
41
            $listItemStyle          = $this->config->getOption('list_item_style', '-');
42 12
            $listItemStyleAlternate = $this->config->getOption('list_item_style_alternate');
43
            if (! isset($this->listItemStyle)) {
44
                $this->listItemStyle = $listItemStyleAlternate ?: $listItemStyle;
45 12
            }
46 12
47 6
            if ($listItemStyleAlternate && $level === 0 && $element->getSiblingPosition() === 1) {
48 4
                $this->listItemStyle = $this->listItemStyle === $listItemStyle ? $listItemStyleAlternate : $listItemStyle;
49
            }
50 12
51 12
            return $prefix . $this->listItemStyle . ' ' . $value . "\n";
52 12
        }
53 12
54 12
        if ($listType === 'ol' && ($parent = $element->getParent()) && ($start = \intval($parent->getAttribute('start')))) {
55 8
            $number = $start + $element->getSiblingPosition() - 1;
56
        } else {
57 12
            $number = $element->getSiblingPosition();
58 3
        }
59 2
60
        return $prefix . $number . '. ' . $value . "\n";
61 12
    }
62
63
    /**
64 6
     * @return string[]
65 3
     */
66 2
    public function getSupportedTags(): array
67 6
    {
68
        return ['li'];
69
    }
70
}
71