1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the league/commonmark package. |
5
|
|
|
* |
6
|
|
|
* (c) Colin O'Dell <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace League\CommonMark\Extension\Autolink; |
13
|
|
|
|
14
|
|
|
use League\CommonMark\Event\DocumentParsedEvent; |
15
|
|
|
use League\CommonMark\Inline\Element\Link; |
16
|
|
|
use League\CommonMark\Inline\Element\Text; |
17
|
|
|
|
18
|
|
|
final class EmailAutolinkProcessor |
19
|
|
|
{ |
20
|
|
|
const REGEX = '/([A-Za-z0-9.\-_+]+@[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_.]+)/'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param DocumentParsedEvent $e |
24
|
|
|
* |
25
|
|
|
* @return void |
26
|
|
|
*/ |
27
|
177 |
|
public function __invoke(DocumentParsedEvent $e) |
28
|
|
|
{ |
29
|
177 |
|
$walker = $e->getDocument()->walker(); |
30
|
|
|
|
31
|
177 |
|
while ($event = $walker->next()) { |
32
|
177 |
|
$node = $event->getNode(); |
33
|
177 |
|
if ($node instanceof Text && !($node->parent() instanceof Link)) { |
34
|
171 |
|
self::processAutolinks($node); |
35
|
|
|
} |
36
|
|
|
} |
37
|
177 |
|
} |
38
|
|
|
|
39
|
171 |
|
private static function processAutolinks(Text $node) |
40
|
|
|
{ |
41
|
171 |
|
$contents = \preg_split(self::REGEX, $node->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE); |
42
|
|
|
|
43
|
171 |
|
if ($contents === false || \count($contents) === 1) { |
44
|
138 |
|
return; |
45
|
|
|
} |
46
|
|
|
|
47
|
33 |
|
$leftovers = ''; |
48
|
33 |
|
foreach ($contents as $i => $content) { |
49
|
33 |
|
if ($i % 2 === 0) { |
50
|
33 |
|
$text = $leftovers . $content; |
51
|
33 |
|
if ($text !== '') { |
52
|
18 |
|
$node->insertBefore(new Text($leftovers . $content)); |
53
|
|
|
} |
54
|
|
|
|
55
|
33 |
|
$leftovers = ''; |
56
|
33 |
|
continue; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
// Does the URL end with punctuation that should be stripped? |
60
|
33 |
|
if (\substr($content, -1) === '.') { |
61
|
|
|
// Add the punctuation later |
62
|
6 |
|
$content = \substr($content, 0, -1); |
63
|
6 |
|
$leftovers = '.'; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// The last character cannot be - or _ |
67
|
33 |
|
if (\in_array(\substr($content, -1), ['-', '_'])) { |
68
|
9 |
|
$node->insertBefore(new Text($content . $leftovers)); |
69
|
9 |
|
$leftovers = ''; |
70
|
9 |
|
continue; |
71
|
|
|
} |
72
|
|
|
|
73
|
27 |
|
$node->insertBefore(new Link('mailto:' . $content, $content)); |
74
|
|
|
} |
75
|
|
|
|
76
|
33 |
|
$node->detach(); |
77
|
33 |
|
} |
78
|
|
|
} |
79
|
|
|
|