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