TempManager::IdToPath()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 2
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
            if (!mkdir(self::TEMP_DIR, 0777, true)) {
20
                throw new Exception("Creating new directory failed (" . self::TEMP_DIR . ")");
21
            }
22
        }
23 3
        if (is_writable(self::TEMP_DIR)) {
24 3
            $this->dir = self::TEMP_DIR . "/" . $context;
25
        } else {
26
            $this->dir = sys_get_temp_dir() . "/csf/" . $context;
27
        }
28 3
        $this->dir = self::TEMP_DIR . "/" . $context;
29 3
        if (!file_exists($this->dir)) {
30 3
            if (!mkdir($this->dir, 0777, true)) {
31
                throw new Exception("Creating new directory failed (" . $this->dir . ")");
32
            }
33
        }
34 3
        if (!is_writable($this->dir)) {
35
            throw new Exception("The temp directory must be writeable (" . $this->dir . ")");
36
        }
37 3
    }
38
39 3
    private function IdToPath(string $id) : string {
40 3
        $path = $this->dir . "/" . $id;
41 3
        if (!file_exists($path)) {
42 3
            touch($path);
43
        }
44 3
        return $path;
45
    }
46
47 3
    public function createFile() : TempFile {
48 3
        $id = uniqid("", true);
49 3
        return new TempFile($id, $this->IdToPath($id));
50
    }
51
52
    public function getFile(string $id) : TempFile {
53
        return new TempFile($id, $this->IdToPath($id));
54
    }
55
56
}