Completed
Push — master ( f21c84...d19842 )
by Colin
03:11
created

LinkConverter::convert()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 16
cts 16
cp 1
rs 8.6346
c 0
b 0
f 0
cc 7
nc 8
nop 1
crap 7
1
<?php
2
3
namespace League\HTMLToMarkdown\Converter;
4
5
use League\HTMLToMarkdown\ElementInterface;
6
7
class LinkConverter implements ConverterInterface
8
{
9
    /**
10
     * @param ElementInterface $element
11
     *
12
     * @return string
13
     */
14 3
    public function convert(ElementInterface $element)
15
    {
16 3
        $href = $element->getAttribute('href');
17 3
        $title = $element->getAttribute('title');
18 3
        $text = trim($element->getValue(), "\t\n\r\0\x0B");
19
20 3
        if ($title !== '') {
21 3
            $markdown = '[' . $text . '](' . $href . ' "' . $title . '")';
22 3
        } elseif ($href === $text && $this->isValidAutolink($href)) {
23 3
            $markdown = '<' . $href . '>';
24 3
        } elseif ($href === 'mailto:' . $text && $this->isValidEmail($text)) {
25 3
            $markdown = '<' . $text . '>';
26 2
        } else {
27 3
            $markdown = '[' . $text . '](' . $href . ')';
28
        }
29
30 3
        if (!$href) {
31 3
            $markdown = html_entity_decode($element->getChildrenAsString());
32 2
        }
33
34 3
        return $markdown;
35
    }
36
37
    /**
38
     * @return string[]
39
     */
40 84
    public function getSupportedTags()
41
    {
42 84
        return array('a');
43
    }
44
45
    /**
46
     * @param string $href
47
     *
48
     * @return bool
49
     */
50 3
    private function isValidAutolink($href)
51
    {
52 3
        return preg_match('/^[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*/i', $href) === 1;
53
    }
54
55
    /**
56
     * @param string $email
57
     *
58
     * @return bool
59
     */
60 3
    private function isValidEmail($email)
61
    {
62
        // Email validation is messy business, but this should cover most cases
63 3
        return filter_var($email, FILTER_VALIDATE_EMAIL);
64
    }
65
}
66