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

TitleProcessor   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 15
c 1
b 0
f 0
dl 0
loc 31
ccs 14
cts 14
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 29 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