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