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\Renderer;
16
17use League\CommonMark\Extension\Footnote\Node\FootnoteBackref;
18use League\CommonMark\Node\Node;
19use League\CommonMark\Renderer\ChildNodeRendererInterface;
20use League\CommonMark\Renderer\NodeRendererInterface;
21use League\CommonMark\Util\HtmlElement;
22use League\CommonMark\Xml\XmlNodeRendererInterface;
23use League\Config\ConfigurationAwareInterface;
24use League\Config\ConfigurationInterface;
25
26final class FootnoteBackrefRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface
27{
28    public const DEFAULT_SYMBOL = '↩';
29
30    private ConfigurationInterface $config;
31
32    /**
33     * @param FootnoteBackref $node
34     *
35     * {@inheritDoc}
36     *
37     * @psalm-suppress MoreSpecificImplementedParamType
38     */
39    public function render(Node $node, ChildNodeRendererInterface $childRenderer): string
40    {
41        FootnoteBackref::assertInstanceOf($node);
42
43        $attrs = $node->data->getData('attributes');
44
45        $attrs->append('class', $this->config->get('footnote/backref_class'));
46        $attrs->set('rev', 'footnote');
47        $attrs->set('href', \mb_strtolower($node->getReference()->getDestination(), 'UTF-8'));
48        $attrs->set('role', 'doc-backlink');
49
50        $symbol = $this->config->get('footnote/backref_symbol');
51        \assert(\is_string($symbol));
52
53        return '&nbsp;' . new HtmlElement('a', $attrs->export(), \htmlspecialchars($symbol), true);
54    }
55
56    public function setConfiguration(ConfigurationInterface $configuration): void
57    {
58        $this->config = $configuration;
59    }
60
61    public function getXmlTagName(Node $node): string
62    {
63        return 'footnote_backref';
64    }
65
66    /**
67     * @param FootnoteBackref $node
68     *
69     * @return array<string, scalar>
70     *
71     * @psalm-suppress MoreSpecificImplementedParamType
72     */
73    public function getXmlAttributes(Node $node): array
74    {
75        FootnoteBackref::assertInstanceOf($node);
76
77        return [
78            'reference' => $node->getReference()->getLabel(),
79        ];
80    }
81}
82