1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace League\CommonMark\Extension\Mention\Generator;
13
14use League\CommonMark\Extension\Mention\Mention;
15use League\CommonMark\Inline\Element\AbstractInline;
16
17final class CallbackGenerator implements MentionGeneratorInterface
18{
19    /**
20     * 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
21     *
22     * @var callable(Mention): ?AbstractInline
23     */
24    private $callback;
25
26    public function __construct(callable $callback)
27    {
28        $this->callback = $callback;
29    }
30
31    public function generateMention(Mention $mention): ?AbstractInline
32    {
33        $result = \call_user_func_array($this->callback, [$mention]);
34        if ($result === null) {
35            return null;
36        }
37
38        if ($result instanceof AbstractInline && !($result instanceof Mention)) {
39            return $result;
40        }
41
42        if ($result instanceof Mention && $result->hasUrl()) {
43            return $mention;
44        }
45
46        throw new \RuntimeException('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');
47    }
48}
49