Passed
Push — master ( 939a6b...8ca850 )
by Bence
03:55
created

TempManager::__construct()   B

Complexity

Conditions 7
Paths 21

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 8.1426

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 21
nop 1
dl 0
loc 20
ccs 10
cts 14
cp 0.7143
crap 8.1426
rs 8.2222
c 0
b 0
f 0
1
<?php
2
3
namespace CSFCloud\TempFiles;
4
5
use Exception;
6
use CSFCloud\TempFiles\TempFile;
7
8
class TempManager {
9
10
    const TEMP_DIR = __DIR__ . "/temp";
11
12
    private $dir;
13
14 3
    public function __construct(string $context) {
15 3
        if (!preg_match('/^[a-z0-9\_\-]+$/i', $context)) {
16
            throw new Exception("The temp context must be an alphanumeric string");
17
        }
18 3
        if (!file_exists(self::TEMP_DIR)) {
19 3
            mkdir(self::TEMP_DIR, 0777, true);
20
        }
21 3
        if (is_writable(self::TEMP_DIR)) {
22 3
            $this->dir = self::TEMP_DIR . "/" . $context;
23
        } else {
24
            $this->dir = sys_get_temp_dir() . "/csf/" . $context;
25
        }
26 3
        $this->dir = self::TEMP_DIR . "/" . $context;
27 3
        if (!file_exists($this->dir)) {
28 3
            if (!mkdir($this->dir, 0777, true)) {
29
                throw new Exception("Creating new directory failed (" . $this->dir . ")");
30
            }
31
        }
32 3
        if (!is_writable($this->dir)) {
33
            throw new Exception("The temp directory must be writeable (" . $this->dir . ")");
34
        }
35 3
    }
36
37 3
    private function IdToPath(string $id) : string {
38 3
        $path = $this->dir . "/" . $id;
39 3
        if (!file_exists($path)) {
40 3
            touch($path);
41
        }
42 3
        return $path;
43
    }
44
45 3
    public function createFile() : TempFile {
46 3
        $id = uniqid("", true);
47 3
        return new TempFile($id, $this->IdToPath($id));
48
    }
49
50
    public function getFile(string $id) : TempFile {
51
        return new TempFile($id, $this->IdToPath($id));
52
    }
53
54
}