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