1<?php
2
3declare(strict_types=1);
4
5/*
6 * This file is part of the league/commonmark package.
7 *
8 * (c) Colin O'Dell <colinodell@gmail.com>
9 *
10 * For the full copyright and license information, please view the LICENSE
11 * file that was distributed with this source code.
12 */
13
14namespace League\CommonMark\Extension\Mention;
15
16use League\CommonMark\Environment\EnvironmentBuilderInterface;
17use League\CommonMark\Extension\ConfigurableExtensionInterface;
18use League\CommonMark\Extension\Mention\Generator\MentionGeneratorInterface;
19use League\Config\ConfigurationBuilderInterface;
20use League\Config\Exception\InvalidConfigurationException;
21use Nette\Schema\Expect;
22
23final class MentionExtension implements ConfigurableExtensionInterface
24{
25    public function configureSchema(ConfigurationBuilderInterface $builder): void
26    {
27        $isAValidPartialRegex = static function (string $regex): bool {
28            $regex = '/' . $regex . '/i';
29
30            return @\preg_match($regex, '') !== false;
31        };
32
33        $builder->addSchema('mentions', Expect::arrayOf(
34            Expect::structure([
35                'prefix' => Expect::string()->required(),
36                'pattern' => Expect::string()->assert($isAValidPartialRegex, 'Pattern must not include starting/ending delimiters (like "/")')->required(),
37                'generator' => Expect::anyOf(
38                    Expect::type(MentionGeneratorInterface::class),
39                    Expect::string(),
40                    Expect::type('callable')
41                )->required(),
42            ])
43        ));
44    }
45
46    public function register(EnvironmentBuilderInterface $environment): void
47    {
48        $mentions = $environment->getConfiguration()->get('mentions');
49        foreach ($mentions as $name => $mention) {
50            if ($mention['generator'] instanceof MentionGeneratorInterface) {
51                $environment->addInlineParser(new MentionParser($name, $mention['prefix'], $mention['pattern'], $mention['generator']));
52            } elseif (\is_string($mention['generator'])) {
53                $environment->addInlineParser(MentionParser::createWithStringTemplate($name, $mention['prefix'], $mention['pattern'], $mention['generator']));
54            } elseif (\is_callable($mention['generator'])) {
55                $environment->addInlineParser(MentionParser::createWithCallback($name, $mention['prefix'], $mention['pattern'], $mention['generator']));
56            } else {
57                throw new InvalidConfigurationException(\sprintf('The "generator" provided for the "%s" MentionParser configuration must be a string template, callable, or an object that implements %s.', $name, MentionGeneratorInterface::class));
58            }
59        }
60    }
61}
62