Passed
Push — main ( 77e259...371264 )
by Oscar
08:09 queued 06:34
created

TitleProcessor::__invoke()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 29
ccs 14
cts 14
cp 1
rs 9.7998
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\Ident;
15
use Ocubom\Twig\Extension\Svg\Util\DomHelper;
16
17
class TitleProcessor implements ProcessorInterface
18
{
19 5
    public function __invoke(\DOMElement $svg, array $options = []): \DOMElement
20
    {
21 5
        if (empty($options['title'])) {
22 4
            return $svg; // Do nothing unless title is set
23
        }
24
25
        /** @var \DOMNode $child */
26 2
        foreach ($svg->getElementsByTagName('title') as $child) {
27
            // Remove title nodes directly under main element
28 1
            if ($child->parentNode === $svg) {
29 1
                DomHelper::removeNode($child);
30
            }
31
        }
32
33
        // Create title element
34
        assert($svg->ownerDocument instanceof \DOMDocument);
35 2
        $title = $svg->insertBefore(
36 2
            $svg->ownerDocument->createElement('title', $options['title']),
37 2
            $svg->firstChild
38 2
        );
39
        assert($title instanceof \DOMElement);
40
41
        // Generate title identifier
42 2
        $id = $options['aria-labelledby'] ?? Ident::generate($title);
43
        // Reference title identifier with aria attribute
44 2
        $title->setAttribute('id', $id);
45 2
        $svg->setAttribute('aria-labelledby', $id);
46
47 2
        return $svg;
48
    }
49
}
50