Completed
Push — master ( 63adb9...1faad8 )
by Colin
02:08
created

LinkConverter::convert()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 8.0155

Importance

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