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