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
|
|
|
{ |
25
|
12 |
|
return ['@']; |
26
|
|
|
} |
27
|
|
|
|
28
|
12 |
|
public function parse(InlineParserContext $inlineContext) |
29
|
|
|
{ |
30
|
12 |
|
$cursor = $inlineContext->getCursor(); |
31
|
|
|
|
32
|
|
|
// The @ symbol must not have any other characters immediately prior |
33
|
12 |
|
$previousChar = $cursor->peek(-1); |
34
|
12 |
|
if ($previousChar !== null && $previousChar !== ' ') { |
35
|
|
|
// peek() doesn't modify the cursor, so no need to restore state first |
36
|
3 |
|
return false; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
// Save the cursor state in case we need to rewind and bail |
40
|
9 |
|
$previousState = $cursor->saveState(); |
41
|
|
|
|
42
|
|
|
// Advance past the @ symbol to keep parsing simpler |
43
|
9 |
|
$cursor->advance(); |
44
|
|
|
|
45
|
|
|
// Parse the handle |
46
|
9 |
|
$handle = $cursor->match('/^[A-Za-z0-9_]{1,15}(?!\w)/'); |
47
|
9 |
|
if (empty($handle)) { |
48
|
|
|
// Regex failed to match; this isn't a valid Twitter handle |
49
|
3 |
|
$cursor->restoreState($previousState); |
50
|
|
|
|
51
|
3 |
|
return false; |
52
|
|
|
} |
53
|
|
|
|
54
|
6 |
|
$profileUrl = 'https://twitter.com/' . $handle; |
55
|
|
|
|
56
|
6 |
|
$inlineContext->getContainer()->appendChild(new Link($profileUrl, '@' . $handle)); |
57
|
|
|
|
58
|
6 |
|
return true; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|