|
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\Extension\CommonMark\Node\Inline\Link; |
|
16
|
|
|
use League\CommonMark\Node\Inline\Text; |
|
17
|
|
|
|
|
18
|
|
|
final class EmailAutolinkProcessor |
|
19
|
|
|
{ |
|
20
|
|
|
const REGEX = '/([A-Za-z0-9.\-_+]+@[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_.]+)/'; |
|
21
|
|
|
|
|
22
|
|
|
public function __invoke(DocumentParsedEvent $e): void |
|
23
|
|
|
{ |
|
24
|
|
|
$walker = $e->getDocument()->walker(); |
|
25
|
|
|
|
|
26
|
|
|
while ($event = $walker->next()) { |
|
27
|
|
|
$node = $event->getNode(); |
|
28
|
|
|
if ($node instanceof Text && !($node->parent() instanceof Link)) { |
|
29
|
|
|
self::processAutolinks($node); |
|
30
|
|
|
} |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
private static function processAutolinks(Text $node): void |
|
35
|
|
|
{ |
|
36
|
|
|
$contents = \preg_split(self::REGEX, $node->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE); |
|
37
|
|
|
|
|
38
|
|
|
if ($contents === false || \count($contents) === 1) { |
|
39
|
|
|
return; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$leftovers = ''; |
|
43
|
|
|
foreach ($contents as $i => $content) { |
|
44
|
|
|
if ($i % 2 === 0) { |
|
45
|
|
|
$text = $leftovers . $content; |
|
46
|
|
|
if ($text !== '') { |
|
47
|
|
|
$node->insertBefore(new Text($leftovers . $content)); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
$leftovers = ''; |
|
51
|
|
|
continue; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
// Does the URL end with punctuation that should be stripped? |
|
55
|
|
|
if (\substr($content, -1) === '.') { |
|
56
|
|
|
// Add the punctuation later |
|
57
|
|
|
$content = \substr($content, 0, -1); |
|
58
|
|
|
$leftovers = '.'; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
// The last character cannot be - or _ |
|
62
|
|
|
if (\in_array(\substr($content, -1), ['-', '_'])) { |
|
63
|
|
|
$node->insertBefore(new Text($content . $leftovers)); |
|
64
|
|
|
$leftovers = ''; |
|
65
|
|
|
continue; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
$node->insertBefore(new Link('mailto:' . $content, $content)); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
$node->detach(); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|