PreformattedConverter   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 15
c 5
b 1
f 0
dl 0
loc 46
ccs 15
cts 15
cp 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A convert() 0 36 5
A getSupportedTags() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\HTMLToMarkdown\Converter;
6
7
use League\HTMLToMarkdown\ElementInterface;
8
9
class PreformattedConverter implements ConverterInterface
10
{
11
    public function convert(ElementInterface $element): string
12
    {
13
        $preContent = \html_entity_decode($element->getChildrenAsString());
14 9
        $preContent = \str_replace(['<pre>', '</pre>'], '', $preContent);
15
16 9
        /*
17 9
         * Checking for the code tag.
18
         * Usually pre tags are used along with code tags. This conditional will check for already converted code tags,
19
         * which use backticks, and if those backticks are at the beginning and at the end of the string it means
20
         * there's no more information to convert.
21
         */
22
23
        $firstBacktick = \strpos(\trim($preContent), '`');
24
        $lastBacktick  = \strrpos(\trim($preContent), '`');
25
        if ($firstBacktick === 0 && $lastBacktick === \strlen(\trim($preContent)) - 1) {
26 9
            return $preContent . "\n\n";
27 9
        }
28 9
29 6
        // If the execution reaches this point it means it's just a pre tag, with no code tag nested
30
31
        // Empty lines are a special case
32
        if ($preContent === '') {
33
            return "```\n```\n\n";
34
        }
35 3
36 3
        // Normalizing new lines
37
        $preContent = \preg_replace('/\r\n|\r|\n/', "\n", $preContent);
38
        \assert(\is_string($preContent));
39
40 3
        // Ensure there's a newline at the end
41
        if (\strrpos($preContent, "\n") !== \strlen($preContent) - \strlen("\n")) {
42
            $preContent .= "\n";
43 3
        }
44 3
45 2
        // Use three backticks
46
        return "```\n" . $preContent . "```\n\n";
47
    }
48 3
49
    /**
50
     * @return string[]
51
     */
52
    public function getSupportedTags(): array
53
    {
54 99
        return ['pre'];
55
    }
56
}
57