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