Passed
Push — 2.0 ( e43938...34a9b2 )
by Colin
03:10 queued 01:16
created

FixOrphanedFootnotesAndRefsListener   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
eloc 17
c 2
b 0
f 0
dl 0
loc 40
ccs 18
cts 18
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A buildMapOfKnownFootnotesAndRefs() 0 16 4
A onDocumentParsed() 0 17 6
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace League\CommonMark\Extension\Footnote\Event;
15
16
use League\CommonMark\Event\DocumentParsedEvent;
17
use League\CommonMark\Extension\Footnote\Node\Footnote;
18
use League\CommonMark\Extension\Footnote\Node\FootnoteRef;
19
use League\CommonMark\Node\Block\Document;
20
use League\CommonMark\Node\Inline\Text;
21
22
final class FixOrphanedFootnotesAndRefsListener
23
{
24 90
    public function onDocumentParsed(DocumentParsedEvent $event): void
25
    {
26 90
        $document = $event->getDocument();
27 90
        $map      = $this->buildMapOfKnownFootnotesAndRefs($document);
28
29 90
        foreach ($document->iterator() as $node) {
30 90
            if ($node instanceof FootnoteRef && ! isset($map[Footnote::class][$node->getReference()->getLabel()])) {
31
                // Found an orphaned FootnoteRef without a corresponding Footnote
32
                // Restore the original footnote ref text
33 8
                $node->replaceWith(new Text(\sprintf('[^%s]', $node->getReference()->getLabel())));
34
            }
35
36
            // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed
37 90
            if ($node instanceof Footnote && ! isset($map[FootnoteRef::class][$node->getReference()->getLabel()])) {
38
                // Found an orphaned Footnote without a corresponding FootnoteRef
39
                // Remove the footnote
40 8
                $node->detach();
41
            }
42
        }
43 90
    }
44
45
    /** @phpstan-ignore-next-line */
46 90
    private function buildMapOfKnownFootnotesAndRefs(Document $document): array // @phpcs:ignore
47
    {
48 45
        $map = [
49 45
            Footnote::class => [],
50
            FootnoteRef::class => [],
51
        ];
52
53 90
        foreach ($document->iterator() as $node) {
54 90
            if ($node instanceof Footnote) {
55 82
                $map[Footnote::class][$node->getReference()->getLabel()] = true;
56 90
            } elseif ($node instanceof FootnoteRef) {
57 82
                $map[FootnoteRef::class][$node->getReference()->getLabel()] = true;
58
            }
59
        }
60
61 90
        return $map;
62
    }
63
}
64