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\Event\DocumentParsedEvent; 18use League\CommonMark\Extension\Footnote\Node\Footnote; 19use League\CommonMark\Extension\Footnote\Node\FootnoteBackref; 20use League\CommonMark\Extension\Footnote\Node\FootnoteRef; 21use League\CommonMark\Node\Block\Paragraph; 22use League\CommonMark\Node\Inline\Text; 23use League\CommonMark\Reference\Reference; 24use League\Config\ConfigurationAwareInterface; 25use League\Config\ConfigurationInterface; 26 27final class AnonymousFootnotesListener implements ConfigurationAwareInterface 28{ 29 private ConfigurationInterface $config; 30 31 public function onDocumentParsed(DocumentParsedEvent $event): void 32 { 33 $document = $event->getDocument(); 34 foreach ($document->iterator() as $node) { 35 if (! $node instanceof FootnoteRef || ($text = $node->getContent()) === null) { 36 continue; 37 } 38 39 // Anonymous footnote needs to create a footnote from its content 40 $existingReference = $node->getReference(); 41 $newReference = new Reference( 42 $existingReference->getLabel(), 43 '#' . $this->config->get('footnote/ref_id_prefix') . $existingReference->getLabel(), 44 $existingReference->getTitle() 45 ); 46 47 $paragraph = new Paragraph(); 48 $paragraph->appendChild(new Text($text)); 49 $paragraph->appendChild(new FootnoteBackref($newReference)); 50 51 $footnote = new Footnote($newReference); 52 $footnote->appendChild($paragraph); 53 54 $document->appendChild($footnote); 55 } 56 } 57 58 public function setConfiguration(ConfigurationInterface $configuration): void 59 { 60 $this->config = $configuration; 61 } 62} 63