Code

< 40 %
40-60 %
> 60 %
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 = \preg_replace('/<pre\b[^>]*>/', '', $preContent);
15
        \assert($preContent !== null);
16 9
        $preContent = \str_replace('</pre>', '', $preContent);
17 9
18
        /*
19
         * Checking for the code tag.
20
         * Usually pre tags are used along with code tags. This conditional will check for already converted code tags,
21
         * which use backticks, and if those backticks are at the beginning and at the end of the string it means
22
         * there's no more information to convert.
23
         */
24
25
        $firstBacktick = \strpos(\trim($preContent), '`');
26 9
        $lastBacktick  = \strrpos(\trim($preContent), '`');
27 9
        if ($firstBacktick === 0 && $lastBacktick === \strlen(\trim($preContent)) - 1) {
28 9
            return $preContent . "\n\n";
29 6
        }
30
31
        // If the execution reaches this point it means it's just a pre tag, with no code tag nested
32
33
        // Empty lines are a special case
34
        if ($preContent === '') {
35 3
            return "```\n```\n\n";
36 3
        }
37
38
        // Normalizing new lines
39
        $preContent = \preg_replace('/\r\n|\r|\n/', "\n", $preContent);
40 3
        \assert(\is_string($preContent));
41
42
        // Ensure there's a newline at the end
43 3
        if (\strrpos($preContent, "\n") !== \strlen($preContent) - \strlen("\n")) {
44 3
            $preContent .= "\n";
45 2
        }
46
47
        // Use three backticks
48 3
        return "```\n" . $preContent . "```\n\n";
49
    }
50
51
    /**
52
     * @return string[]
53
     */
54 99
    public function getSupportedTags(): array
55
    {
56 99
        return ['pre'];
57
    }
58
}
59