LinkConverter   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 65
ccs 28
cts 30
cp 0.9333
rs 10
wmc 15

6 Methods

Rating   Name   Duplication   Size   Complexity  
A isValidEmail() 0 4 1
A getSupportedTags() 0 3 1
B convert() 0 29 9
A setConfig() 0 3 1
A isValidAutolink() 0 5 2
A shouldStrip() 0 3 1
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 LinkConverter implements ConverterInterface, ConfigurationAwareInterface
12
{
13
    /** @var Configuration */
14
    protected $config;
15
16
    public function setConfig(Configuration $config): void
17
    {
18
        $this->config = $config;
19 99
    }
20 99
21 99
    public function convert(ElementInterface $element): string
22
    {
23
        $href  = $element->getAttribute('href');
24
        $title = $element->getAttribute('title');
25
        $text  = \trim($element->getValue(), "\t\n\r\0\x0B");
26
27
        if ($title !== '') {
28 9
            $markdown = '[' . $text . '](' . $href . ' "' . $title . '")';
29
        } elseif ($href === $text && $this->isValidAutolink($href)) {
30 9
            $markdown = '<' . $href . '>';
31 9
        } elseif ($href === 'mailto:' . $text && $this->isValidEmail($text)) {
32 9
            $markdown = '<' . $text . '>';
33
        } else {
34 9
            if (\stristr($href, ' ')) {
35 3
                $href = '<' . $href . '>';
36 9
            }
37 3
38 9
            $markdown = '[' . $text . '](' . $href . ')';
39 3
        }
40 2
41 9
        if (! $href) {
42
            if ($this->shouldStrip()) {
43
                $markdown = $text;
44 9
            } else {
45
                $markdown = \html_entity_decode($element->getChildrenAsString());
46
            }
47 9
        }
48 3
49 3
        return $markdown;
50 2
    }
51 3
52
    /**
53 2
     * @return string[]
54
     */
55 9
    public function getSupportedTags(): array
56
    {
57
        return ['a'];
58
    }
59
60
    private function isValidAutolink(string $href): bool
61 99
    {
62
        $useAutolinks = $this->config->getOption('use_autolinks');
63 99
64
        return $useAutolinks && (\preg_match('/^[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*/i', $href) === 1);
65
    }
66
67
    private function isValidEmail(string $email): bool
68
    {
69
        // Email validation is messy business, but this should cover most cases
70
        return \filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
71 6
    }
72
73 6
    private function shouldStrip(): bool
74 6
    {
75
        return $this->config->getOption('strip_placeholder_links') ?? false;
76
    }
77
}
78