Completed
Push — master ( 0868ae...a5d47a )
by Colin
03:35
created

LinkConverter   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 96.15%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 2
dl 0
loc 75
ccs 25
cts 26
cp 0.9615
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setConfig() 0 3 1
A getSupportedTags() 0 4 1
A isValidAutolink() 0 5 2
A isValidEmail() 0 5 1
B convert() 0 25 8
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