Passed
Push — develop ( 535216...2a3c68 )
by Paul
07:18
created

AbstractSvgAvatar   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
eloc 22
c 0
b 0
f 0
dl 0
loc 36
ccs 0
cts 23
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 3 1
A save() 0 25 5
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Modules\Avatars;
4
5
abstract class AbstractSvgAvatar
6
{
7
    public function create(string $from): string
8
    {
9
        return $this->save($this->generate($from), $this->filename($from));
10
    }
11
12
    abstract public function generate(string $from): string;
13
14
    abstract protected function filename(string $from): string;
15
16
    protected function save(string $contents, string $name): string
17
    {
18
        $uploadsDir = wp_upload_dir();
19
        $baseDir = trailingslashit($uploadsDir['basedir']);
20
        $baseUrl = trailingslashit($uploadsDir['baseurl']);
21
        $pathDir = trailingslashit(glsr()->id).trailingslashit('avatars');
22
        $filename = sprintf('%s.svg', $name ?: 'blank');
23
        $filepath = $baseDir.$pathDir.$filename;
24
        if (!file_exists($filepath)) {
25
            wp_mkdir_p($baseDir.$pathDir);
26
            $fp = @fopen($filepath, 'wb');
27
            if (false === $fp) {
28
                return '';
29
            }
30
            mbstring_binary_safe_encoding();
31
            $dataLength = strlen($contents);
32
            $bytesWritten = fwrite($fp, $contents);
33
            reset_mbstring_encoding();
34
            fclose($fp);
35
            if ($dataLength !== $bytesWritten) {
36
                return '';
37
            }
38
            chmod($filepath, fileperms(ABSPATH.'index.php') & 0777 | 0644);
39
        }
40
        return set_url_scheme($baseUrl.$pathDir.$filename);
41
    }
42
}
43