1<?php
2
3/*
4 * This file is part of the league/commonmark package.
5 *
6 * (c) Colin O'Dell <colinodell@gmail.com>
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
13declare(strict_types=1);
14
15namespace League\CommonMark\Extension\Footnote\Event;
16
17use League\CommonMark\Block\Element\Paragraph;
18use League\CommonMark\Event\DocumentParsedEvent;
19use League\CommonMark\Extension\Footnote\Node\Footnote;
20use League\CommonMark\Extension\Footnote\Node\FootnoteBackref;
21use League\CommonMark\Extension\Footnote\Node\FootnoteRef;
22use League\CommonMark\Inline\Element\Text;
23use League\CommonMark\Reference\Reference;
24use League\CommonMark\Util\ConfigurationAwareInterface;
25use League\CommonMark\Util\ConfigurationInterface;
26
27final class AnonymousFootnotesListener implements ConfigurationAwareInterface
28{
29    /** @var ConfigurationInterface */
30    private $config;
31
32    public function onDocumentParsed(DocumentParsedEvent $event): void
33    {
34        $document = $event->getDocument();
35        $walker = $document->walker();
36
37        while ($event = $walker->next()) {
38            $node = $event->getNode();
39            if ($node instanceof FootnoteRef && $event->isEntering() && null !== $text = $node->getContent()) {
40                // Anonymous footnote needs to create a footnote from its content
41                $existingReference = $node->getReference();
42                $reference = new Reference(
43                    $existingReference->getLabel(),
44                    '#' . $this->config->get('footnote/ref_id_prefix', 'fnref:') . $existingReference->getLabel(),
45                    $existingReference->getTitle()
46                );
47                $footnote = new Footnote($reference);
48                $footnote->addBackref(new FootnoteBackref($reference));
49                $paragraph = new Paragraph();
50                $paragraph->appendChild(new Text($text));
51                $footnote->appendChild($paragraph);
52                $document->appendChild($footnote);
53            }
54        }
55    }
56
57    public function setConfiguration(ConfigurationInterface $config): void
58    {
59        $this->config = $config;
60    }
61}
62