-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathTempFileManager.php
More file actions
82 lines (64 loc) · 1.91 KB
/
TempFileManager.php
File metadata and controls
82 lines (64 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace Nick\SecureSpreadsheet;
use RuntimeException;
class TempFileManager
{
private $baseDir;
private $jobDir;
private $cleaned = false;
public function __construct(?string $preferredDir = null)
{
$this->baseDir = $this->resolveBaseDir($preferredDir);
$this->jobDir = $this->createJobDir();
// request shutdown function to cleanup temp files
register_shutdown_function([$this, 'cleanup']);
}
private function resolveBaseDir(?string $preferredDir): string
{
$candidates = array_filter([
$preferredDir,
getenv('TMPDIR'),
getenv('TMP'),
getenv('TEMP'),
sys_get_temp_dir(),
'/tmp',
getcwd().DIRECTORY_SEPARATOR.'tmp',
]);
foreach ($candidates as $dir) {
if ($this->isUsableDir($dir)) {
return rtrim($dir, DIRECTORY_SEPARATOR);
}
}
throw new RuntimeException('No usable temp directory.');
}
private function isUsableDir(string $dir): bool
{
return is_dir($dir)
&& is_writable($dir)
&& ! is_link($dir);
}
private function createJobDir(): string
{
$jobDir = $this->baseDir.DIRECTORY_SEPARATOR.'job_'.bin2hex(random_bytes(8));
if (! mkdir($jobDir, 0700)) {
throw new RuntimeException('Failed to create job temp directory');
}
return $jobDir;
}
public function path(string $name): string
{
return $this->jobDir.DIRECTORY_SEPARATOR.$name;
}
public function cleanup(): void
{
if ($this->cleaned || ! is_dir($this->jobDir)) {
return;
}
$files = glob($this->jobDir.DIRECTORY_SEPARATOR.'*') ?: [];
foreach ($files as $file) {
@unlink($file);
}
@rmdir($this->jobDir);
$this->cleaned = true;
}
}