TempManager   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 73.08%

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 46
ccs 19
cts 26
cp 0.7308
rs 10
c 0
b 0
f 0
wmc 12

4 Methods

Rating   Name   Duplication   Size   Complexity  
A IdToPath() 0 6 2
A createFile() 0 3 1
A getFile() 0 2 1
B __construct() 0 22 8
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
}