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
|
|
|
use League\CommonMark\Reference\ReferenceableInterface; |
22
|
|
|
|
23
|
|
|
final class FixOrphanedFootnotesAndRefsListener |
24
|
|
|
{ |
25
|
105 |
|
public function onDocumentParsed(DocumentParsedEvent $event): void |
26
|
|
|
{ |
27
|
105 |
|
$document = $event->getDocument(); |
28
|
105 |
|
$walker = $document->walker(); |
29
|
|
|
|
30
|
105 |
|
while ($event = $walker->next()) { |
31
|
105 |
|
if (! $event->isEntering()) { |
32
|
105 |
|
continue; |
33
|
|
|
} |
34
|
|
|
|
35
|
105 |
|
$node = $event->getNode(); |
36
|
105 |
|
if ($node instanceof FootnoteRef && ! $this->exists($document, Footnote::class, $node->getReference()->getLabel())) { |
37
|
|
|
// Found an orphaned FootnoteRef without a corresponding Footnote |
38
|
|
|
// Restore the original footnote ref text |
39
|
9 |
|
$node->replaceWith(new Text(\sprintf('[^%s]', $node->getReference()->getLabel()))); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
// phpcs:disable SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed |
43
|
105 |
|
if ($node instanceof Footnote && ! $this->exists($document, FootnoteRef::class, $node->getReference()->getLabel())) { |
44
|
|
|
// Found an orphaned Footnote without a corresponding FootnoteRef |
45
|
|
|
// Remove the footnote |
46
|
9 |
|
$walker->resumeAt($node->next() ?? $node->parent()); |
47
|
9 |
|
$node->detach(); |
48
|
|
|
} |
49
|
|
|
} |
50
|
105 |
|
} |
51
|
|
|
|
52
|
96 |
|
private function exists(Document $document, string $type, string $label): bool |
53
|
|
|
{ |
54
|
96 |
|
$walker = $document->walker(); |
55
|
96 |
|
while ($event = $walker->next()) { |
56
|
96 |
|
if (! $event->isEntering()) { |
57
|
96 |
|
continue; |
58
|
|
|
} |
59
|
|
|
|
60
|
96 |
|
$node = $event->getNode(); |
61
|
96 |
|
if ($node instanceof ReferenceableInterface && \get_class($node) === $type && $node->getReference()->getLabel() === $label) { |
62
|
96 |
|
return true; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
18 |
|
return false; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|