Completed
Pull Request — master (#188)
by
unknown
22:06
created

LinkConverter::isValidAutolink()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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