Completed
Pull Request — master (#3)
by Colin
15:37 queued 13:56
created

EmailAddressParser::getCharacters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark-extras package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmark-js)
9
 *  - (c) John MacFarlane
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace League\CommonMark\Extras\EmailAutolink;
16
17
use League\CommonMark\Inline\Element\Link;
18
use League\CommonMark\Inline\Element\Text;
19
use League\CommonMark\Inline\Parser\AbstractInlineParser;
20
use League\CommonMark\InlineParserContext;
21
use League\CommonMark\Util\RegexHelper;
22
23
class EmailAddressParser extends AbstractInlineParser
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28 12
    public function getCharacters()
29
    {
30 12
        return ['@'];
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 12
    public function parse(InlineParserContext $inlineContext)
37
    {
38
        // There must be some text prior to the @
39 12
        $lastChild = $inlineContext->getContainer()->lastChild();
40 12
        if (!($lastChild instanceof Text)) {
41 3
            return false;
42
        }
43
44 9
        $everythingBeforeTheAtSymbol = $lastChild->getContent();
45 9
        if ($everythingBeforeTheAtSymbol === '') {
46
            return false;
47
        }
48
49
        // Attempt to parse the mailbox portion, which should exist at the very end of this string
50 9
        $matches = RegexHelper::matchAll('/[a-zA-Z0-9.!#$%&\'*+\\/=?^_`{|}~-]+$/', $everythingBeforeTheAtSymbol);
51 9
        if (empty($matches)) {
52
            return false;
53
        }
54
55 9
        $mailbox = end($matches);
56
57
        // Attempt to parse the '@' symbol and domain name
58 9
        $domain = $inlineContext->getCursor()->match('/^@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/');
59 9
        if ($domain === null) {
60
            return false;
61
        }
62
63 9
        $address = $mailbox . $domain;
64
65 9
        $inlineContext->getContainer()->appendChild(new Link('mailto:' . $address, $address));
66
67
        // Remove the $mailbox part from $lastChild
68 9
        $newContent = substr($everythingBeforeTheAtSymbol, 0, 0 - strlen($mailbox));
69 9
        $lastChild->setContent($newContent);
70
71 9
        return true;
72
    }
73
}
74