EmbedProcessor::__invoke()   B
last analyzed

Complexity

Conditions 9
Paths 40

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 9
eloc 22
nc 40
nop 1
dl 0
loc 33
rs 8.0555
c 2
b 0
f 0
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\Inline\Text;
20
use League\CommonMark\Node\NodeIterator;
21
22
final class EmbedProcessor
23
{
24
    public const FALLBACK_REMOVE = 'remove';
25
    public const FALLBACK_LINK   = 'link';
26
27
    private EmbedAdapterInterface $adapter;
28
    private string $fallback;
29
30
    public function __construct(EmbedAdapterInterface $adapter, string $fallback = self::FALLBACK_REMOVE)
31
    {
32
        $this->adapter  = $adapter;
33
        $this->fallback = $fallback;
34
    }
35
36
    public function __invoke(DocumentParsedEvent $event): void
37
    {
38
        $document = $event->getDocument();
39
        $embeds   = [];
40
        foreach (new NodeIterator($document) as $node) {
41
            if (! ($node instanceof Embed)) {
42
                continue;
43
            }
44
45
            if ($node->parent() !== $document) {
46
                $replacement = new Paragraph();
47
                $replacement->appendChild(new Text($node->getUrl()));
48
                $node->replaceWith($replacement);
49
            } else {
50
                $embeds[] = $node;
51
            }
52
        }
53
54
        if ($embeds) {
55
            $this->adapter->updateEmbeds($embeds);
56
        }
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
}
73