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

MarkdownExtension::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 0
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
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