TitleProcessor::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 25
ccs 11
cts 11
cp 1
rs 9.9332
cc 4
nc 4
nop 2
crap 4
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
class TitleProcessor implements ProcessorInterface
17
{
18 13
    public function __invoke(\DOMElement $svg, array $options = []): \DOMElement
19
    {
20 13
        if (empty($options['title'])) {
21 12
            return $svg; // Do nothing unless title is set
22
        }
23
24
        /** @var \DOMNode $child */
25 4
        foreach ($svg->getElementsByTagName('title') as $child) {
26
            // Remove title nodes directly under main element
27 1
            if ($child->parentNode === $svg) {
28 1
                DomUtil::removeNode($child);
29
            }
30
        }
31
32
        // Create title element
33 4
        $title = DomUtil::createElement('title', $options['title'], $svg->firstChild, true);
34
35
        // Reference title identifier with aria attribute
36 4
        $title->setAttribute('id', $options['aria-labelledby']);
37 4
        $svg->setAttribute('aria-labelledby', $options['aria-labelledby']);
38
39
        // Remove unneeded title attribute
40 4
        $svg->removeAttribute('title');
41
42 4
        return $svg;
43
    }
44
}
45