LinkConverter::shouldStrip()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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 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 \boolval($this->config->getOption('strip_placeholder_links') ?? false);
76
    }
77
}
78