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
|
|
|
|