|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the league/commonmark package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Colin O'Dell <[email protected]> |
|
7
|
|
|
* (c) Rezo Zero / Ambroise Maupate |
|
8
|
|
|
* |
|
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
10
|
|
|
* file that was distributed with this source code. |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
declare(strict_types=1); |
|
14
|
|
|
|
|
15
|
|
|
namespace League\CommonMark\Extension\Footnote\Event; |
|
16
|
|
|
|
|
17
|
|
|
use League\CommonMark\Event\DocumentParsedEvent; |
|
18
|
|
|
use League\CommonMark\Extension\Footnote\Node\FootnoteRef; |
|
19
|
|
|
use League\CommonMark\Reference\Reference; |
|
20
|
|
|
|
|
21
|
|
|
final class NumberFootnotesListener |
|
22
|
|
|
{ |
|
23
|
90 |
|
public function onDocumentParsed(DocumentParsedEvent $event): void |
|
24
|
|
|
{ |
|
25
|
90 |
|
$document = $event->getDocument(); |
|
26
|
90 |
|
$nextCounter = 1; |
|
27
|
90 |
|
$usedLabels = []; |
|
28
|
90 |
|
$usedCounters = []; |
|
29
|
|
|
|
|
30
|
90 |
|
foreach ($document->iterator() as $node) { |
|
31
|
90 |
|
if (! $node instanceof FootnoteRef) { |
|
32
|
90 |
|
continue; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
82 |
|
$existingReference = $node->getReference(); |
|
36
|
82 |
|
$label = $existingReference->getLabel(); |
|
37
|
82 |
|
$counter = $nextCounter; |
|
38
|
82 |
|
$canIncrementCounter = true; |
|
39
|
|
|
|
|
40
|
82 |
|
if (\array_key_exists($label, $usedLabels)) { |
|
41
|
|
|
/* |
|
42
|
|
|
* Reference is used again, we need to point |
|
43
|
|
|
* to the same footnote. But with a different ID |
|
44
|
|
|
*/ |
|
45
|
8 |
|
$counter = $usedCounters[$label]; |
|
46
|
8 |
|
$label .= '__' . ++$usedLabels[$label]; |
|
47
|
8 |
|
$canIncrementCounter = false; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
// rewrite reference title to use a numeric link |
|
51
|
82 |
|
$newReference = new Reference( |
|
52
|
|
|
$label, |
|
53
|
82 |
|
$existingReference->getDestination(), |
|
54
|
82 |
|
(string) $counter |
|
55
|
|
|
); |
|
56
|
|
|
|
|
57
|
|
|
// Override reference with numeric link |
|
58
|
82 |
|
$node->setReference($newReference); |
|
59
|
82 |
|
$document->getReferenceMap()->add($newReference); |
|
60
|
|
|
|
|
61
|
|
|
/* |
|
62
|
|
|
* Store created references in document for |
|
63
|
|
|
* creating FootnoteBackrefs |
|
64
|
|
|
*/ |
|
65
|
82 |
|
$document->data->append($existingReference->getDestination(), $newReference); |
|
66
|
|
|
|
|
67
|
82 |
|
$usedLabels[$label] = 1; |
|
68
|
82 |
|
$usedCounters[$label] = $nextCounter; |
|
69
|
|
|
|
|
70
|
82 |
|
if ($canIncrementCounter) { |
|
71
|
82 |
|
$nextCounter++; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
90 |
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|