Completed
Pull Request — master (#1)
by Colin
01:50
created

TwitterHandleParser::parse()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 31
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 31
ccs 14
cts 14
cp 1
rs 8.5806
cc 4
eloc 14
nc 3
nop 1
crap 4
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\TwitterHandleAutolink;
16
17
use League\CommonMark\Inline\Element\Link;
18
use League\CommonMark\Inline\Parser\AbstractInlineParser;
19
use League\CommonMark\InlineParserContext;
20
21
class TwitterHandleParser extends AbstractInlineParser
22
{
23 12
    public function getCharacters() {
24 12
        return ['@'];
25
    }
26
27 12
    public function parse(InlineParserContext $inlineContext) {
28 12
        $cursor = $inlineContext->getCursor();
29
30
        // The @ symbol must not have any other characters immediately prior
31 12
        $previousChar = $cursor->peek(-1);
32 12
        if ($previousChar !== null && $previousChar !== ' ') {
33
            // peek() doesn't modify the cursor, so no need to restore state first
34 3
            return false;
35
        }
36
37
        // Save the cursor state in case we need to rewind and bail
38 9
        $previousState = $cursor->saveState();
39
40
        // Advance past the @ symbol to keep parsing simpler
41 9
        $cursor->advance();
42
43
        // Parse the handle
44 9
        $handle = $cursor->match('/^[A-Za-z0-9_]{1,15}(?!\w)/');
45 9
        if (empty($handle)) {
46
            // Regex failed to match; this isn't a valid Twitter handle
47 3
            $cursor->restoreState($previousState);
48
49 3
            return false;
50
        }
51
52 6
        $profileUrl = 'https://twitter.com/' . $handle;
53
54 6
        $inlineContext->getContainer()->appendChild(new Link($profileUrl, '@'.$handle));
55
56 6
        return true;
57
    }
58
}
59