-
-
Notifications
You must be signed in to change notification settings - Fork 568
/
Copy pathSvg.php
82 lines (66 loc) · 2.05 KB
/
Svg.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace Statamic\Tags;
use Statamic\Facades\File;
use Statamic\Facades\URL;
use Statamic\Support\Str;
use Stringy\StaticStringy;
class Svg extends Tags
{
use Concerns\RendersAttributes;
public function wildcard($src)
{
$this->params['src'] = $src;
return $this->index();
}
public function index()
{
$name = Str::ensureRight($this->params->get('src'), '.svg');
$cascade = [
resource_path('svg'),
resource_path(),
public_path('svg'),
public_path(),
];
$svg = null;
foreach ($cascade as $location) {
$file = Url::assemble($location, $name);
if (File::exists($file)) {
$svg = StaticStringy::collapseWhitespace(
File::get($file)
);
break;
}
}
$attributes = $this->renderAttributesFromParams(['src', 'title', 'desc']);
if ($this->params->get('title') || $this->params->get('desc')) {
$svg = $this->setTitleAndDesc($svg);
}
return str_replace(
'<svg',
collect(['<svg', $attributes])->filter()->implode(' '),
$svg
);
}
private function setTitleAndDesc($svg)
{
$doc = new \DOMDocument;
$doc->loadXML($svg);
if ($desc = $this->params->get('desc')) {
if ($el = $doc->getElementsByTagName('desc')[0]) {
$el->nodeValue = $desc;
} else {
$el = $doc->createElement('desc', $desc);
$doc->firstChild->insertBefore($el, $doc->firstChild->firstChild);
}
}
if ($title = $this->params->get('title')) {
if ($el = $doc->getElementsByTagName('title')[0]) {
$el->nodeValue = $title;
} else {
$el = $doc->createElement('title', $title);
$doc->firstChild->insertBefore($el, $doc->firstChild->firstChild);
}
}
return $doc->saveHTML();
}
}