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\Generator;
15
16use League\CommonMark\Exception\LogicException;
17use League\CommonMark\Extension\Mention\Mention;
18use League\CommonMark\Node\Inline\AbstractInline;
19
20final class CallbackGenerator implements MentionGeneratorInterface
21{
22    /**
23     * A callback function which sets the URL on the passed mention and returns the mention, return a new AbstractInline based object or null if the mention is not a match
24     *
25     * @var callable(Mention): ?AbstractInline
26     */
27    private $callback;
28
29    public function __construct(callable $callback)
30    {
31        $this->callback = $callback;
32    }
33
34    /**
35     * @throws LogicException
36     */
37    public function generateMention(Mention $mention): ?AbstractInline
38    {
39        $result = \call_user_func($this->callback, $mention);
40        if ($result === null) {
41            return null;
42        }
43
44        if ($result instanceof AbstractInline && ! ($result instanceof Mention)) {
45            return $result;
46        }
47
48        if ($result instanceof Mention && $result->hasUrl()) {
49            return $mention;
50        }
51
52        throw new LogicException('CallbackGenerator callable must set the URL on the passed mention and return the mention, return a new AbstractInline based object or null if the mention is not a match');
53    }
54}
55