Passed
Push — main ( 89e46a...7f37fd )
by Loïc
03:53
created

MarkdownExtension::getFilters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 1
eloc 2
c 2
b 0
f 2
nc 1
nop 0
dl 0
loc 4
ccs 3
cts 3
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;
0 ignored issues
show
Bug introduced by
The type App\Helper\StringHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Twig\Extension\AbstractExtension;
9
use Twig\TwigFilter;
10
11
use function Symfony\Component\String\u;
12
13
final class MarkdownExtension extends AbstractExtension
14
{
15 11
    public function __construct(
16
        private readonly StringHelper $stringHelper,
17
    ) {
18 11
    }
19
20 4
    public function getFilters(): array
21
    {
22 4
        return [
23 4
            new TwigFilter('add_headers_anchors', $this->addHeadersAnchors(...)),
24 4
        ];
25
    }
26
27
    /**
28
     * Add the missing anchors on demo website homepage displaying the Githb README.
29
     *
30
     * @see https://microsymfony.ovh
31
     * @see https://github.com/strangebuzz/MicroSymfony/blob/main/README.md?plain=1
32
     */
33 2
    public function addHeadersAnchors(string $html): string
34
    {
35 2
        $dom = new \DOMDocument();
36 2
        $dom->loadHTML(mb_encode_numericentity($html, [0x80, 0x10FFFF, 0, ~0], 'UTF-8'), \LIBXML_HTML_NOIMPLIED | \LIBXML_HTML_NODEFDTD);
37
38
        /** @var \DOMNodeList<\DOMNode> $tags */
39 2
        $tags = (new \DOMXPath($dom))->query('//h1 | //h2 | //h3 | //h4 | //h5 | //h6');
40
        // Allow to have the same "buggy" anchors as GitHub
41 2
        foreach ($tags as $headerTag) {
42 2
            $slug = $this->stringHelper->slugify($headerTag->textContent);
43
            /** @var \DOMElement $headerTag */
44 2
            $headerTag->setAttribute('id', $slug.(u($slug)->length() !== u($headerTag->textContent)->length() ? '-' : '')); // add "-" when we have a final Emoji.
45
        }
46
47 2
        return (string) $dom->saveHTML();
48
    }
49
}
50