|
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\Provider\FontAwesome; |
|
13
|
|
|
|
|
14
|
|
|
use Ocubom\Twig\Extension\Svg\Loader\LoaderInterface; |
|
15
|
|
|
use Ocubom\Twig\Extension\Svg\Util\DomUtil; |
|
16
|
|
|
use Ocubom\Twig\Extension\Svg\Util\Html5Util; |
|
17
|
|
|
use Twig\Environment; |
|
18
|
|
|
use Twig\Extension\RuntimeExtensionInterface; |
|
19
|
|
|
|
|
20
|
|
|
class FontAwesomeRuntime implements RuntimeExtensionInterface |
|
21
|
|
|
{ |
|
22
|
|
|
private LoaderInterface $loader; |
|
23
|
|
|
|
|
24
|
3 |
|
public function __construct(FontAwesomeLoader $loader) |
|
25
|
|
|
{ |
|
26
|
3 |
|
$this->loader = $loader; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
2 |
|
public function replaceIcons(Environment $twig, string $html): string |
|
30
|
|
|
{ |
|
31
|
|
|
// Load HTML |
|
32
|
2 |
|
$doc = Html5Util::loadHtml($html); |
|
33
|
|
|
|
|
34
|
2 |
|
$query = implode(' | ', array_map( |
|
35
|
2 |
|
function ($class) { |
|
36
|
2 |
|
return sprintf( |
|
37
|
2 |
|
'descendant-or-self::*[@class and contains(concat(\' \', normalize-space(@class), \' \'), \' %s \')]', |
|
38
|
2 |
|
$class |
|
39
|
2 |
|
); |
|
40
|
2 |
|
}, |
|
41
|
2 |
|
array_keys(FontAwesome::PREFIXES) |
|
42
|
2 |
|
)); |
|
43
|
|
|
|
|
44
|
|
|
/** @var \DOMNode $node */ |
|
45
|
2 |
|
foreach (DomUtil::query($query, $doc) as $node) { |
|
46
|
2 |
|
if ($node instanceof \DOMElement) { |
|
47
|
2 |
|
if ($node->hasAttribute('data-fa-transform')) { |
|
48
|
|
|
continue; // Ignore icons with Power Transforms (use svg+js) |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
2 |
|
if ($twig->isDebug()) { |
|
52
|
1 |
|
DomUtil::createComment(DomUtil::toHtml($node), $node, true); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
2 |
|
$icon = $this->loader->resolve( |
|
56
|
2 |
|
$node->getAttribute('class'), // Resolve icon with class … |
|
57
|
2 |
|
DomUtil::getElementAttributes($node) // … and clone all its attributes as options |
|
58
|
2 |
|
); |
|
59
|
|
|
|
|
60
|
|
|
// Replace node |
|
61
|
1 |
|
DomUtil::replaceNode($node, $icon->getElement()); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
// Generate normalized HTML |
|
66
|
1 |
|
return Html5Util::toHtml($doc); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
1 |
|
public function renderHtmlTag(string $icon, array $options = []): string |
|
70
|
|
|
{ |
|
71
|
1 |
|
$icon = $this->loader->resolve($icon, $options); |
|
72
|
|
|
assert($icon instanceof Icon); |
|
73
|
|
|
|
|
74
|
1 |
|
return DomUtil::toHtml($icon->getHtmlTag($options)); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|