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
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace League\CommonMark\Extension\Mention; |
15
|
|
|
|
16
|
|
|
use League\CommonMark\Environment\ConfigurableEnvironmentInterface; |
17
|
|
|
use League\CommonMark\Exception\InvalidOptionException; |
18
|
|
|
use League\CommonMark\Extension\ExtensionInterface; |
19
|
|
|
use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface; |
20
|
|
|
|
21
|
|
|
final class MentionExtension implements ExtensionInterface |
22
|
|
|
{ |
23
|
21 |
|
public function register(ConfigurableEnvironmentInterface $environment): void |
24
|
|
|
{ |
25
|
21 |
|
$mentions = $environment->getConfig('mentions', []); |
26
|
21 |
|
foreach ($mentions as $name => $mention) { |
27
|
18 |
|
foreach (['prefix', 'regex', 'generator'] as $key) { |
28
|
18 |
|
if (! \array_key_exists($key, $mention)) { |
29
|
3 |
|
throw new InvalidOptionException(\sprintf('Required option "mentions/%s/%s" for the Mention extension is missing', $name, $key)); |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
15 |
|
if (! self::isAValidPartialRegex($mention['regex'])) { |
34
|
3 |
|
throw InvalidOptionException::forConfigOption(\sprintf('mentions/%s/regex', $name), $mention['regex'], 'Invalid partial regex. Make sure to exclude starting/ending delimiters and flags.'); |
35
|
|
|
} |
36
|
|
|
|
37
|
12 |
|
if ($mention['generator'] instanceof MentionGeneratorInterface) { |
38
|
3 |
|
$environment->addInlineParser(new MentionParser($mention['prefix'], $mention['regex'], $mention['generator'])); |
39
|
9 |
|
} elseif (\is_string($mention['generator'])) { |
40
|
3 |
|
$environment->addInlineParser(MentionParser::createWithStringTemplate($mention['prefix'], $mention['regex'], $mention['generator'])); |
41
|
6 |
|
} elseif (\is_callable($mention['generator'])) { |
42
|
3 |
|
$environment->addInlineParser(MentionParser::createWithCallback($mention['prefix'], $mention['regex'], $mention['generator'])); |
43
|
|
|
} else { |
44
|
3 |
|
throw new InvalidOptionException(\sprintf('The "generator" provided for the "%s" MentionParser configuration must be a string template, callable, or an object that implements %s.', $name, MentionGeneratorInterface::class)); |
45
|
|
|
} |
46
|
|
|
} |
47
|
12 |
|
} |
48
|
|
|
|
49
|
15 |
|
private static function isAValidPartialRegex(string $regex): bool |
50
|
|
|
{ |
51
|
15 |
|
$regex = '/' . $regex . '/i'; |
52
|
|
|
|
53
|
15 |
|
return @\preg_match($regex, '') !== false; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|