CleanAttributesProcessor::__invoke()   B
last analyzed

Complexity

Conditions 8
Paths 3

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 33
ccs 22
cts 22
cp 1
rs 8.4444
cc 8
nc 3
nop 2
crap 8
1
<?php
2
3
/*
4
 * This file is part of ocubom/twig-svg-extension
5
 *
6
 * © Oscar Cubo Medina <https://ocubom.github.io>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ocubom\Twig\Extension\Svg\Processor;
13
14
use Ocubom\Twig\Extension\Svg\Util\DomUtil;
15
16
use function BenTools\IterableFunctions\iterable_to_array;
17
18
class CleanAttributesProcessor implements ProcessorInterface
19
{
20
    const ATTRIBUTES_SETS = [
21
        // size attributes
22
        'viewBox' => '@size0',
23
        'height' => '@size1',
24
        'width' => ' @size1',
25
26
        // aria-* attributes followed with related attributes
27
        'aria-' => 'aria',
28
        'focusable' => 'aria@1',
29
        'role' => 'aria@1',
30
31
        // data-* attributes
32
        'data-' => 'data',
33
    ];
34
35 13
    public function __invoke(\DOMElement $svg, array $options = []): \DOMElement
36
    {
37 13
        $attributes = iterable_to_array(DomUtil::getElementAttributes($svg));
38 13
        uksort($attributes, function ($x, $y) {
39 13
            $values = [
40 13
                'x' => [$x, '', ''],
41 13
                'y' => [$y, '', ''],
42 13
            ];
43 13
            foreach (self::ATTRIBUTES_SETS as $key => $val) {
44 13
                foreach (['x', 'y'] as $var) {
45 13
                    if (str_starts_with($values[$var][0], $key)) {
46 13
                        $values[$var][1] = $val;
47 13
                        $values[$var][2] = substr($values[$var][0], strlen($key));
48
                    }
49
                }
50
            }
51
52 13
            return strnatcasecmp($values['x'][1], $values['y'][1])
53 13
                ?: strnatcasecmp($values['x'][2], $values['y'][2])
54 13
                ?: strnatcasecmp($x, $y);
55 13
        });
56
57 13
        foreach ($attributes as $key => $val) {
58 13
            $svg->removeAttribute($key);
59
60 13
            $val = trim($val);
61 13
            if (!empty($val)) {
62
                // Recreate attribute in correct order
63 13
                $svg->setAttribute($key, $val);
64
            }
65
        }
66
67 13
        return $svg;
68
    }
69
}
70