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
|
|
|
} |