Completed
Push — latest ( 609def...dcbb7e )
by Colin
14s queued 11s
created

AutolinkParser   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 0
Metric Value
wmc 4
eloc 13
c 0
b 0
f 0
dl 0
loc 28
ccs 11
cts 12
cp 0.9167
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getMatchDefinition() 0 3 1
A parse() 0 18 3
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 2880
    public function getMatchDefinition(): InlineParserMatch
31
    {
32 2880
        return InlineParserMatch::regex(self::EMAIL_REGEX . '|' . self::OTHER_LINK_REGEX);
33
    }
34
35 267
    public function parse(InlineParserContext $inlineContext): bool
36
    {
37 267
        $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength());
38 267
        $matches = $inlineContext->getMatches();
39
40 267
        if ($matches[1] !== '') {
41 12
            $inlineContext->getContainer()->appendChild(new Link('mailto:' . UrlEncoder::unescapeAndEncode($matches[1]), $matches[1]));
42
43 12
            return true;
44
        }
45
46 255
        if ($matches[2] !== '') {
47 255
            $inlineContext->getContainer()->appendChild(new Link(UrlEncoder::unescapeAndEncode($matches[2]), $matches[2]));
48
49 255
            return true;
50
        }
51
52
        return false; // This should never happen
53
    }
54
}
55