Passed
Push — 2.3 ( 32a49e )
by Colin
03:51 queued 01:09
created

EmbedProcessor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
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