Test Failed
Push — develop ( 819262...d1effe )
by Paul
08:00
created

Svg::url()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 1
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 path: $path");
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 path: $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 = empty($style) ? 'pointer-events: none;' : $style.'; 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((string) $style, ';').'; '.$value;
70
                }
71
                $processor->set_attribute($attribute, $value);
72
            }
73
        }
74
        return $processor->get_updated_html();
75
    }
76
}
77