PreserveAspectRatioProcessor::__invoke()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 30
ccs 14
cts 14
cp 1
rs 9.4888
cc 5
nc 6
nop 2
crap 5
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
class PreserveAspectRatioProcessor
15
{
16
    const ATTRIBUTE_NAME = 'preserveAspectRatio';
17
    const VALUES = [
18
        [
19
            'name' => 'align',
20
            'default' => 'xMidYMid',
21
            'values' => [
22
                'none' => 'none',
23
                'xminymin' => 'xMinYMin',
24
                'xmidymin' => 'xMidYMin',
25
                'xmaxymin' => 'xMaxYMin',
26
                'xminymid' => 'xMinYMid',
27
                'xmidymid' => 'xMidYMid', // Default
28
                'xmaxymid' => 'xMaxYMid',
29
                'xminymax' => 'xMinYMax',
30
                'xmidymax' => 'xMidYMax',
31
                'xmaxymax' => 'xMaxYMax',
32
            ],
33
        ], [
34
            'name' => 'meet or slice',
35
            'default' => 'meet',
36
            'values' => [
37
                'meet' => 'meet', // Default
38
                'slice' => 'slice',
39
            ],
40
        ],
41
    ];
42
43 13
    public function __invoke(\DOMElement $svg, array $options = []): \DOMElement
44
    {
45 13
        $value = preg_split('@\s+@Uis', $svg->getAttribute(self::ATTRIBUTE_NAME));
46 13
        $value = array_slice($value, 0, count(self::VALUES));
47
48 13
        $count = count(self::VALUES);
49 13
        foreach (array_reverse(self::VALUES, true) as $pos => $data) {
50
            // Use default value if not set
51 13
            $value[$pos] = $value[$pos] ?? $data['default'];
52
53
            // Normalize value
54 13
            $value[$pos] = $data['values'][mb_strtolower($value[$pos])] ?? $value[$pos];
55
56
            // Update default value count
57 13
            if ($count === $pos + 1 && $value[$pos] === $data['default']) {
58 13
                $count = $pos;
59
            }
60
        }
61
62
        // Discard defaults at end
63 13
        $value = array_slice($value, 0, $count);
64
65
        // Set the normalized value or remove attribute if is empty or the defaults
66 13
        if (count($value) > 0) {
67 10
            $svg->setAttribute(self::ATTRIBUTE_NAME, implode(' ', $value));
68
        } else {
69 5
            $svg->removeAttribute(self::ATTRIBUTE_NAME);
70
        }
71
72 13
        return $svg;
73
    }
74
}
75