ListItemConverter::setConfig()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
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