Passed
Push — node-iterator ( da69c7...1da87a )
by Colin
40:48 queued 07:54
created

FixOrphanedFootnotesAndRefsListener   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
eloc 17
dl 0
loc 40
rs 10
c 2
b 0
f 0

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
    public function onDocumentParsed(DocumentParsedEvent $event): void
25
    {
26
        $document = $event->getDocument();
27
        $map      = $this->buildMapOfKnownFootnotesAndRefs($document);
28
29
        foreach ($document->iterator() as $node) {
30
            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
                $node->replaceWith(new Text(\sprintf('[^%s]', $node->getReference()->getLabel())));
34
            }
35
36
            // phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed
37
            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
                $node->detach();
41
            }
42
        }
43
    }
44
45
    /** @phpstan-ignore-next-line */
46
    private function buildMapOfKnownFootnotesAndRefs(Document $document): array // @phpcs:ignore
47
    {
48
        $map = [
49
            Footnote::class => [],
50
            FootnoteRef::class => [],
51
        ];
52
53
        foreach ($document->iterator() as $node) {
54
            if ($node instanceof Footnote) {
55
                $map[Footnote::class][$node->getReference()->getLabel()] = true;
56
            } elseif ($node instanceof FootnoteRef) {
57
                $map[FootnoteRef::class][$node->getReference()->getLabel()] = true;
58
            }
59
        }
60
61
        return $map;
62
    }
63
}
64