Completed
Pull Request — master (#100)
by
unknown
21:51 queued 19:53
created

HeaderConverter   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 72.21%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 11
lcom 1
cbo 2
dl 0
loc 70
ccs 13
cts 18
cp 0.7221
rs 10
c 2
b 1
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setConfig() 0 4 1
A getSupportedTags() 0 4 1
A createAtxHeader() 0 6 1
B convert() 0 11 5
A createSetextHeader() 0 7 3
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 HeaderConverter implements ConverterInterface, ConfigurationAwareInterface
10
{
11
    const STYLE_ATX = 'atx';
12
    const STYLE_SETEXT = 'setext';
13
14
    /**
15
     * @var Configuration
16
     */
17
    protected $config;
18
19
    /**
20
     * @param Configuration $config
21
     */
22 78
    public function setConfig(Configuration $config)
23
    {
24 78
        $this->config = $config;
25 78
    }
26
27
    /**
28
     * @param ElementInterface $element
29
     *
30
     * @return string
31
     */
32 3
    public function convert(ElementInterface $element)
33
    {
34 3
        $level = (int) substr($element->getTagName(), 1, 1);
35 3
        $style = $this->config->getOption('header_style', self::STYLE_SETEXT);
36
37 3
        if (($level === 1 || $level === 2) && !$element->isDescendantOf('blockquote') && $style === self::STYLE_SETEXT) {
38
            return $this->createSetextHeader($level, $element->getValue());
39
        } else {
40 3
            return $this->createAtxHeader($level, $element->getValue());
41
        }
42
    }
43
44
    /**
45
     * @return string[]
46
     */
47 78
    public function getSupportedTags()
48
    {
49 78
        return array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
50
    }
51
52
    /**
53
     * @param int    $level
54
     * @param string $content
55
     *
56
     * @return string
57
     */
58
    private function createSetextHeader($level, $content)
59
    {
60
        $length = (function_exists('mb_strlen')) ? mb_strlen($content, 'utf-8') : strlen($content);
61
        $underline = ($level === 1) ? '=' : '-';
62
63
        return $content . "\n" . str_repeat($underline, $length) . "\n\n";
64
    }
65
66
    /**
67
     * @param int    $level
68
     * @param string $content
69
     *
70
     * @return string
71
     */
72 3
    private function createAtxHeader($level, $content)
73
    {
74 3
        $prefix = str_repeat('#', $level) . ' ';
75
76 3
        return $prefix . $content . "\n\n";
77
    }
78
}
79