|
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
|
|
|
|