AnonymousFootnotesListener::onDocumentParsed()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 31
ccs 20
cts 20
cp 1
rs 9.3222
c 1
b 0
f 0
cc 5
nc 4
nop 1
crap 5
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\Footnote;
19
use League\CommonMark\Extension\Footnote\Node\FootnoteBackref;
20
use League\CommonMark\Extension\Footnote\Node\FootnoteRef;
21
use League\CommonMark\Node\Block\Paragraph;
22
use League\CommonMark\Node\Inline\Text;
23
use League\CommonMark\Reference\Reference;
24
use League\Config\ConfigurationAwareInterface;
25
use League\Config\ConfigurationInterface;
26
27
final class AnonymousFootnotesListener implements ConfigurationAwareInterface
28
{
29
    /** @var ConfigurationInterface */
30
    private $config;
31
32 105
    public function onDocumentParsed(DocumentParsedEvent $event): void
33
    {
34 105
        $document = $event->getDocument();
35 105
        $walker   = $document->walker();
36
37 105
        while ($event = $walker->next()) {
38 105
            if (! $event->isEntering()) {
39 105
                continue;
40
            }
41
42 105
            $node = $event->getNode();
43 105
            if (! $node instanceof FootnoteRef || ($text = $node->getContent()) === null) {
44 105
                continue;
45
            }
46
47
            // Anonymous footnote needs to create a footnote from its content
48 21
            $existingReference = $node->getReference();
49 21
            $newReference      = new Reference(
50 21
                $existingReference->getLabel(),
51 21
                '#' . $this->config->get('footnote/ref_id_prefix') . $existingReference->getLabel(),
52 21
                $existingReference->getTitle()
53
            );
54
55 21
            $paragraph = new Paragraph();
56 21
            $paragraph->appendChild(new Text($text));
57 21
            $paragraph->appendChild(new FootnoteBackref($newReference));
58
59 21
            $footnote = new Footnote($newReference);
60 21
            $footnote->appendChild($paragraph);
61
62 21
            $document->appendChild($footnote);
63
        }
64 105
    }
65
66 105
    public function setConfiguration(ConfigurationInterface $configuration): void
67
    {
68 105
        $this->config = $configuration;
69 105
    }
70
}
71