1 | <?php |
||
18 | final class InlineMentionParser implements InlineParserInterface |
||
19 | { |
||
20 | /** @var string */ |
||
21 | private $linkPattern; |
||
22 | |||
23 | /** @var string */ |
||
24 | private $handleRegex; |
||
25 | |||
26 | /** |
||
27 | * @param string $linkPattern |
||
28 | * @param string $handleRegex |
||
29 | */ |
||
30 | 6 | public function __construct($linkPattern, $handleRegex = '/^[A-Za-z0-9_]+(?!\w)/') |
|
35 | |||
36 | /** |
||
37 | * {@inheritdoc} |
||
38 | */ |
||
39 | 6 | public function getName() |
|
43 | |||
44 | /** |
||
45 | * {@inheritdoc} |
||
46 | */ |
||
47 | 6 | public function getCharacters() |
|
51 | |||
52 | /** |
||
53 | * {@inheritdoc} |
||
54 | */ |
||
55 | 6 | public function parse(InlineParserContext $inlineContext) |
|
56 | { |
||
57 | 6 | $cursor = $inlineContext->getCursor(); |
|
58 | |||
59 | // The @ symbol must not have any other characters immediately prior |
||
60 | 6 | $previousChar = $cursor->peek(-1); |
|
61 | 6 | if ($previousChar !== null && $previousChar !== ' ') { |
|
62 | // peek() doesn't modify the cursor, so no need to restore state first |
||
63 | 3 | return false; |
|
64 | } |
||
65 | |||
66 | // Save the cursor state in case we need to rewind and bail |
||
67 | 6 | $previousState = $cursor->saveState(); |
|
68 | |||
69 | // Advance past the @ symbol to keep parsing simpler |
||
70 | 6 | $cursor->advance(); |
|
71 | |||
72 | // Parse the handle |
||
73 | 6 | $handle = $cursor->match($this->handleRegex); |
|
74 | 6 | if (empty($handle)) { |
|
75 | // Regex failed to match; this isn't a valid Twitter handle |
||
76 | 3 | $cursor->restoreState($previousState); |
|
77 | |||
78 | 3 | return false; |
|
79 | } |
||
80 | |||
81 | 6 | $url = sprintf($this->linkPattern, $handle); |
|
82 | |||
83 | 6 | $inlineContext->getContainer()->appendChild(new Link($url, '@' . $handle)); |
|
84 | |||
85 | 6 | return true; |
|
86 | } |
||
87 | |||
88 | 3 | public static function createTwitterHandleParser() |
|
92 | |||
93 | 3 | public static function createGithubHandleParser() |
|
98 | } |
||
99 |