Completed
Push — master ( 45070b...de2ce9 )
by Colin
02:22
created

EmailAutolinkProcessor   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 6
dl 0
loc 60
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 10 3
B processAutolinks() 0 39 7
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark-ext-autolink 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\Ext\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 96
    public function __invoke(DocumentParsedEvent $e)
28
    {
29 96
        $walker = $e->getDocument()->walker();
30
31 96
        while ($event = $walker->next()) {
32 96
            if ($event->getNode() instanceof Text) {
33 96
                self::processAutolinks($event->getNode());
34
            }
35
        }
36 96
    }
37
38 96
    private static function processAutolinks(Text $node)
39
    {
40 96
        $contents = \preg_split(self::REGEX, $node->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE);
41
42 96
        if (\count($contents) === 1) {
43 72
            return;
44
        }
45
46 24
        $leftovers = '';
47 24
        foreach ($contents as $i => $content) {
48 24
            if ($i % 2 === 0) {
49 24
                $text = $leftovers . $content;
50 24
                if ($text !== '') {
51 12
                    $node->insertBefore(new Text($leftovers . $content));
52
                }
53
54 24
                $leftovers = '';
55 24
                continue;
56
            }
57
58
            // Does the URL end with punctuation that should be stripped?
59 24
            if (\substr($content, -1) === '.') {
60
                // Add the punctuation later
61 3
                $content = \substr($content, 0, -1);
62 3
                $leftovers = '.';
63
            }
64
65
            // The last character cannot be - or _
66 24
            if (\in_array(\substr($content, -1), ['-', '_'])) {
67 6
                $node->insertBefore(new Text($content . $leftovers));
68 6
                $leftovers = '';
69 6
                continue;
70
            }
71
72 18
            $node->insertBefore(new Link('mailto:' . $content, $content));
73
        }
74
75 24
        $node->detach();
76 24
    }
77
}
78