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
|
90 |
|
public function setConfig(Configuration $config) { |
20
|
90 |
|
$this->config = $config; |
21
|
90 |
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param ElementInterface $element |
25
|
|
|
* |
26
|
|
|
* @return string |
27
|
|
|
*/ |
28
|
6 |
|
public function convert(ElementInterface $element) |
29
|
|
|
{ |
30
|
6 |
|
$href = $element->getAttribute('href'); |
31
|
6 |
|
$title = $element->getAttribute('title'); |
32
|
6 |
|
$text = trim($element->getValue(), "\t\n\r\0\x0B"); |
33
|
|
|
|
34
|
6 |
|
if ($title !== '') { |
35
|
3 |
|
$markdown = '[' . $text . '](' . $href . ' "' . $title . '")'; |
36
|
6 |
|
} elseif ($href === $text && $this->isValidAutolink($href)) { |
37
|
3 |
|
$markdown = '<' . $href . '>'; |
38
|
6 |
|
} elseif ($href === 'mailto:' . $text && $this->isValidEmail($text)) { |
39
|
3 |
|
$markdown = '<' . $text . '>'; |
40
|
2 |
|
} else { |
41
|
6 |
|
if (stristr($href, ' ')) { |
42
|
|
|
$href = '<'.$href.'>'; |
43
|
|
|
} |
44
|
6 |
|
$markdown = '[' . $text . '](' . $href . ')'; |
45
|
|
|
} |
46
|
|
|
|
47
|
6 |
|
if (!$href) { |
48
|
3 |
|
$markdown = html_entity_decode($element->getChildrenAsString()); |
49
|
2 |
|
} |
50
|
|
|
|
51
|
6 |
|
return $markdown; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @return string[] |
56
|
|
|
*/ |
57
|
90 |
|
public function getSupportedTags() |
58
|
|
|
{ |
59
|
90 |
|
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
|
|
|
|