1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace GeminiLabs\SiteReviews\Helpers; |
4
|
|
|
|
5
|
|
|
class Svg |
6
|
|
|
{ |
7
|
|
|
public static function contents(string $path): string |
8
|
|
|
{ |
9
|
|
|
$filename = static::filePath($path); |
10
|
|
|
if (empty($filename)) { |
11
|
|
|
glsr_log()->error("Invalid SVG file: $filename"); |
12
|
|
|
return ''; |
13
|
|
|
} |
14
|
|
|
$contents = (string) file_get_contents($filename); |
15
|
|
|
$contents = preg_replace('/\s+/', ' ', $contents); |
16
|
|
|
$contents = trim($contents); |
17
|
|
|
return $contents; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public static function encoded(string $path): string |
21
|
|
|
{ |
22
|
|
|
$contents = static::contents($path); |
23
|
|
|
if (empty($contents)) { |
24
|
|
|
return ''; |
25
|
|
|
} |
26
|
|
|
// $contents = str_replace('"', "'", $contents); |
27
|
|
|
return 'data:image/svg+xml;base64,'.base64_encode($contents); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public static function filePath(string $path): string |
31
|
|
|
{ |
32
|
|
|
$filename = $path; |
33
|
|
|
if (!file_exists($filename)) { |
34
|
|
|
$filename = glsr()->path($path); |
35
|
|
|
} |
36
|
|
|
if (!file_exists($filename)) { |
37
|
|
|
// glsr_log()->error("Invalid SVG filepath: $filename"); |
38
|
|
|
return ''; |
39
|
|
|
} |
40
|
|
|
$check = wp_check_filetype($filename, [ |
41
|
|
|
'svg' => 'image/svg+xml', |
42
|
|
|
]); |
43
|
|
|
if ('svg' !== $check['ext'] || 'image/svg+xml' !== $check['type']) { |
44
|
|
|
// glsr_log()->error("Invalid SVG file: $filename"); |
45
|
|
|
return ''; |
46
|
|
|
} |
47
|
|
|
return $filename; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public static function get(string $path, array $attributes = []): string |
51
|
|
|
{ |
52
|
|
|
$contents = static::contents($path); |
53
|
|
|
if (empty($contents)) { |
54
|
|
|
return ''; |
55
|
|
|
} |
56
|
|
|
$processor = new \WP_HTML_Tag_Processor($contents); |
57
|
|
|
$processor->next_tag(['tag_name' => 'svg']); |
58
|
|
|
$style = $processor->get_attribute('style'); |
59
|
|
|
$value = $style ? $style.'; pointer-events: none;' : 'pointer-events: none;'; |
60
|
|
|
$processor->set_attribute('style', $value); |
61
|
|
|
if (!empty($attributes)) { |
62
|
|
|
foreach ($attributes as $attribute => $value) { |
63
|
|
|
if ('class' === $attribute) { |
64
|
|
|
$processor->add_class($value); |
65
|
|
|
continue; |
66
|
|
|
} |
67
|
|
|
if ('style' === $attribute) { |
68
|
|
|
$style = $processor->get_attribute('style'); |
69
|
|
|
$value = rtrim($style, ';').'; '.$value; |
|
|
|
|
70
|
|
|
} |
71
|
|
|
$processor->set_attribute($attribute, $value); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
return $processor->get_updated_html(); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|