Completed
Push — master ( a5d47a...489c7c )
by Colin
25:01 queued 01:34
created

EmphasisConverter::getNormTag()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 5
cts 5
cp 1
rs 8.8333
c 0
b 0
f 0
cc 7
nc 4
nop 1
crap 7
1
<?php
2
3
namespace League\HTMLToMarkdown\Converter;
4
5
use League\HTMLToMarkdown\Configuration;
6
use League\HTMLToMarkdown\ConfigurationAwareInterface;
7
use League\HTMLToMarkdown\ElementInterface;
8
9
class EmphasisConverter implements ConverterInterface, ConfigurationAwareInterface
10
{
11
    /**
12
     * @var Configuration
13
     */
14
    protected $config;
15
16
    /**
17
     * @param ElementInterface|null $element
18
     *
19 93
     * @return string
20
     */
21 93
    protected function getNormTag($element)
22 93
    {
23
        if ($element !== null && !$element->isText()) {
24
            $tag = $element->getTagName();
25
            if ($tag === 'i' || $tag === 'em') {
26
                return 'em';
27
            } else if ($tag === 'b' || $tag === 'strong') {
28
                return 'strong';
29 15
            }
30
        }
31 15
        return '';
32 15
    }
33
34 15
    /**
35 3
     * @param Configuration $config
36
     */
37
    public function setConfig(Configuration $config)
38 15
    {
39 12
        $this->config = $config;
40
    }
41 9
42
    /**
43
     * @param ElementInterface $element
44 15
     *
45 15
     * @return string
46
     */
47 15
    public function convert(ElementInterface $element)
48
    {
49
        $tag = $this->getNormTag($element);
50
        $value = $element->getValue();
51
52
        if (!trim($value)) {
53 93
            return $value;
54
        }
55 93
56
        if ($tag === 'em') {
57
            $style = $this->config->getOption('italic_style');
58
        } else {
59
            $style = $this->config->getOption('bold_style');
60
        }
61
62
        $prefix = ltrim($value) !== $value ? ' ' : '';
63
        $suffix = rtrim($value) !== $value ? ' ' : '';
64
65
        /* If this node is immediately preceded or followed by one of the same type don't emit
66
         * the start or end $style, respectively. This prevents <em>foo</em><em>bar</em> from
67
         * being converted to *foo**bar* which is incorrect. We want *foobar* instead.
68
         */
69
        $pre_style = $this->getNormTag($element->getPreviousSibling()) === $tag ? '' : $style;
70
        $post_style = $this->getNormTag($element->getNextSibling()) === $tag ? '' : $style;
71
72
        return $prefix . $pre_style . trim($value) . $post_style . $suffix;
73
    }
74
75
    /**
76
     * @return string[]
77
     */
78
    public function getSupportedTags()
79
    {
80
        return array('em', 'i', 'strong', 'b');
81
    }
82
}
83