aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/league/html-to-markdown/src/Converter/ListItemConverter.php
blob: c56ab89cdf78d1535228a0d2ae8aaafe6d67c2a5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php

namespace League\HTMLToMarkdown\Converter;

use League\HTMLToMarkdown\Configuration;
use League\HTMLToMarkdown\ConfigurationAwareInterface;
use League\HTMLToMarkdown\ElementInterface;

class ListItemConverter implements ConverterInterface, ConfigurationAwareInterface
{
    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @var string
     */
    protected $listItemStyle;

    /**
     * @param Configuration $config
     */
    public function setConfig(Configuration $config)
    {
        $this->config = $config;
    }

    /**
     * @param ElementInterface $element
     *
     * @return string
     */
    public function convert(ElementInterface $element)
    {
        // If parent is an ol, use numbers, otherwise, use dashes
        $list_type = $element->getParent()->getTagName();

        // Add spaces to start for nested list items
        $level = $element->getListItemLevel($element);

        $prefixForParagraph = str_repeat('  ', $level + 1);
        $value = trim(implode("\n" . $prefixForParagraph, explode("\n", trim($element->getValue()))));

        // If list item is the first in a nested list, add a newline before it
        $prefix = '';
        if ($level > 0 && $element->getSiblingPosition() === 1) {
            $prefix = "\n";
        }

        if ($list_type === 'ul') {
            $list_item_style = $this->config->getOption('list_item_style', '-');
            $list_item_style_alternate = $this->config->getOption('list_item_style_alternate');
            if (!isset($this->listItemStyle)) {
                $this->listItemStyle = $list_item_style_alternate ? $list_item_style_alternate : $list_item_style;
            }

            if ($list_item_style_alternate && $level == 0 && $element->getSiblingPosition() === 1) {
                $this->listItemStyle = $this->listItemStyle == $list_item_style ? $list_item_style_alternate : $list_item_style;
            }

            return $prefix . $this->listItemStyle . ' ' . $value . "\n";
        }

        if ($list_type === 'ol' && $start = $element->getParent()->getAttribute('start')) {
            $number = $start + $element->getSiblingPosition() - 1;
        } else {
            $number = $element->getSiblingPosition();
        }

        return $prefix . $number . '. ' . $value . "\n";
    }

    /**
     * @return string[]
     */
    public function getSupportedTags()
    {
        return array('li');
    }
}