Completed
Push — latest ( 76d169...995567 )
by Colin
22s queued 10s
created

AutolinkParser::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.0067

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 18
ccs 10
cts 11
cp 0.9091
rs 9.9332
cc 3
nc 3
nop 2
crap 3.0067
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
17
namespace League\CommonMark\Extension\CommonMark\Parser\Inline;
18
19
use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
20
use League\CommonMark\Parser\Inline\InlineParserInterface;
21
use League\CommonMark\Parser\Inline\InlineParserMatch;
22
use League\CommonMark\Parser\InlineParserContext;
23
use League\CommonMark\Util\UrlEncoder;
24
25
final class AutolinkParser implements InlineParserInterface
26
{
27
    private const EMAIL_REGEX      = '<([a-zA-Z0-9.!#$%&\'*+\\/=?^_`{|}~-]+@[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])?)*)>';
28
    private const OTHER_LINK_REGEX = '<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>';
29
30 2874
    public function getMatchDefinition(): InlineParserMatch
31
    {
32 2874
        return InlineParserMatch::regex(self::EMAIL_REGEX . '|' . self::OTHER_LINK_REGEX);
33
    }
34
35 267
    public function parse(string $match, InlineParserContext $inlineContext): bool
36
    {
37 267
        $cursor = $inlineContext->getCursor();
38 267
        if ($m = $cursor->match('/^' . self::EMAIL_REGEX . '/')) {
39 12
            $email = \substr($m, 1, -1);
40 12
            $inlineContext->getContainer()->appendChild(new Link('mailto:' . UrlEncoder::unescapeAndEncode($email), $email));
41
42 12
            return true;
43
        }
44
45 255
        if ($m = $cursor->match('/^' . self::OTHER_LINK_REGEX . '/')) {
46 255
            $dest = \substr($m, 1, -1);
47 255
            $inlineContext->getContainer()->appendChild(new Link(UrlEncoder::unescapeAndEncode($dest), $dest));
48
49 255
            return true;
50
        }
51
52
        return false;
53
    }
54
}
55