Test Setup Failed
Push — main ( aa8716...cc6c96 )
by Loïc
03:28
created

MarkdownExtension   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 1 Features 2
Metric Value
eloc 10
c 4
b 1
f 2
dl 0
loc 35
ccs 14
cts 14
cp 1
rs 10
wmc 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Twig\Extension;
6
7
use App\Helper\StringHelper;
8
use Twig\Attribute\AsTwigFilter;
9
10
use function Symfony\Component\String\u;
11
12
final readonly class MarkdownExtension
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 12 at column 6
Loading history...
13
{
14
    public function __construct(
15 15
        private StringHelper $stringHelper,
16
    ) {
17
    }
18 15
19
    /**
20 6
     * Add the missing anchors on demo website homepage displaying the Github README.
21
     *
22 6
     * @see https://microsymfony.ovh
23 6
     * @see https://github.com/strangebuzz/MicroSymfony/blob/main/README.md?plain=1
24 6
     */
25
    #[AsTwigFilter('add_headers_anchors')]
26
    public function addHeadersAnchors(string $html): string
27
    {
28
        $dom = new \DOMDocument();
29
        $dom->loadHTML(mb_encode_numericentity($html, [0x80, 0x10FFFF, 0, ~0], 'UTF-8'), \LIBXML_HTML_NOIMPLIED | \LIBXML_HTML_NODEFDTD);
30
31
        // Allow to have the same "buggy" anchors as GitHub
32
        /** @var \DOMNodeList<\DOMNode> $tags */
33 2
        $tags = (new \DOMXPath($dom))->query('//h2 | //h3');
34
        foreach ($tags as $headerTag) {
35 2
            $slug = $this->stringHelper->slugify($headerTag->textContent);
36 2
            /** @var \DOMElement $headerTag */
37
            $headerTag->setAttribute('id', $slug.(u($slug)->length() !== u($headerTag->textContent)->length() ? '-' : '')); // add "-" when we have a final Emoji.
38
        }
39
40 2
        return (string) $dom->saveHTML();
41 2
    }
42
}
43