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

AbstractSvgAvatar::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
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