| 148 |
lars |
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 <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 |
|
|
|
14 |
namespace League\CommonMark\Extension\Mention\Generator;
|
|
|
15 |
|
|
|
16 |
use League\CommonMark\Extension\Mention\Mention;
|
|
|
17 |
use League\CommonMark\Node\Inline\AbstractInline;
|
|
|
18 |
|
|
|
19 |
final class CallbackGenerator implements MentionGeneratorInterface
|
|
|
20 |
{
|
|
|
21 |
/**
|
|
|
22 |
* 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
|
|
|
23 |
*
|
|
|
24 |
* @var callable(Mention): ?AbstractInline
|
|
|
25 |
*/
|
|
|
26 |
private $callback;
|
|
|
27 |
|
|
|
28 |
public function __construct(callable $callback)
|
|
|
29 |
{
|
|
|
30 |
$this->callback = $callback;
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
public function generateMention(Mention $mention): ?AbstractInline
|
|
|
34 |
{
|
|
|
35 |
$result = \call_user_func($this->callback, $mention);
|
|
|
36 |
if ($result === null) {
|
|
|
37 |
return null;
|
|
|
38 |
}
|
|
|
39 |
|
|
|
40 |
if ($result instanceof AbstractInline && ! ($result instanceof Mention)) {
|
|
|
41 |
return $result;
|
|
|
42 |
}
|
|
|
43 |
|
|
|
44 |
if ($result instanceof Mention && $result->hasUrl()) {
|
|
|
45 |
return $mention;
|
|
|
46 |
}
|
|
|
47 |
|
|
|
48 |
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');
|
|
|
49 |
}
|
|
|
50 |
}
|