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