|
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\Embed; |
|
15
|
|
|
|
|
16
|
|
|
use League\CommonMark\Event\DocumentParsedEvent; |
|
17
|
|
|
use League\CommonMark\Extension\CommonMark\Node\Inline\Link; |
|
18
|
|
|
use League\CommonMark\Node\Block\Paragraph; |
|
19
|
|
|
use League\CommonMark\Node\NodeIterator; |
|
20
|
|
|
|
|
21
|
|
|
final class EmbedProcessor |
|
22
|
|
|
{ |
|
23
|
|
|
public const FALLBACK_REMOVE = 'remove'; |
|
24
|
|
|
public const FALLBACK_LINK = 'link'; |
|
25
|
|
|
|
|
26
|
|
|
private EmbedAdapterInterface $adapter; |
|
27
|
|
|
private string $fallback; |
|
28
|
|
|
|
|
29
|
14 |
|
public function __construct(EmbedAdapterInterface $adapter, string $fallback = self::FALLBACK_REMOVE) |
|
30
|
|
|
{ |
|
31
|
14 |
|
$this->adapter = $adapter; |
|
32
|
14 |
|
$this->fallback = $fallback; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
14 |
|
public function __invoke(DocumentParsedEvent $event): void |
|
36
|
|
|
{ |
|
37
|
14 |
|
$embeds = []; |
|
38
|
14 |
|
foreach (new NodeIterator($event->getDocument()) as $node) { |
|
39
|
14 |
|
if ($node instanceof Embed) { |
|
40
|
14 |
|
$embeds[] = $node; |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
14 |
|
$this->adapter->updateEmbeds($embeds); |
|
45
|
|
|
|
|
46
|
14 |
|
foreach ($embeds as $embed) { |
|
47
|
14 |
|
if ($embed->getEmbedCode() !== null) { |
|
48
|
10 |
|
continue; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
8 |
|
if ($this->fallback === self::FALLBACK_REMOVE) { |
|
52
|
4 |
|
$embed->detach(); |
|
53
|
4 |
|
} elseif ($this->fallback === self::FALLBACK_LINK) { |
|
54
|
4 |
|
$paragraph = new Paragraph(); |
|
55
|
4 |
|
$paragraph->appendChild(new Link($embed->getUrl(), $embed->getUrl())); |
|
56
|
4 |
|
$embed->replaceWith($paragraph); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|