1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\TemporaryDirectory; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
class TemporaryDirectory |
8
|
|
|
{ |
9
|
|
|
/** @var string */ |
10
|
|
|
protected $path; |
11
|
|
|
|
12
|
|
|
public function __construct(string $path, bool $overwriteExistingDirectory = false) |
13
|
|
|
{ |
14
|
|
|
$this->path = $this->sanitizePath($path); |
15
|
|
|
|
16
|
|
|
if ($overwriteExistingDirectory && file_exists($this->path)) { |
17
|
|
|
$this->deleteDirectory($this->path); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
if (! $overwriteExistingDirectory && file_exists($this->path)) { |
21
|
|
|
throw new InvalidArgumentException("Path `{$path}` already exists."); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
if (! file_exists($this->path)) { |
25
|
|
|
mkdir($this->path, 0777, true); |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function path(string $pathOrFilename = ''): string |
30
|
|
|
{ |
31
|
|
|
if (empty($pathOrFilename)) { |
32
|
|
|
return $this->path; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$path = $this->path.DIRECTORY_SEPARATOR.trim($pathOrFilename, '/'); |
36
|
|
|
|
37
|
|
|
$directoryPath = $this->removeFilenameFromPath($path); |
38
|
|
|
|
39
|
|
|
if (! file_exists($directoryPath)) { |
40
|
|
|
mkdir($directoryPath, 0777, true); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $path; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function delete() |
47
|
|
|
{ |
48
|
|
|
$this->deleteDirectory($this->path); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
protected function sanitizePath(string $path): string |
52
|
|
|
{ |
53
|
|
|
if (empty($path)) { |
54
|
|
|
throw new InvalidArgumentException('The path argument can\'t be empty.'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$path = rtrim($path); |
58
|
|
|
|
59
|
|
|
return rtrim($path, DIRECTORY_SEPARATOR); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
protected function removeFilenameFromPath(string $path): string |
63
|
|
|
{ |
64
|
|
|
if (! $this->isFilePath($path)) { |
65
|
|
|
return $path; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return substr($path, 0, strrpos($path, DIRECTORY_SEPARATOR)); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
protected function isFilePath(string $path): bool |
72
|
|
|
{ |
73
|
|
|
return strpos($path, '.') !== false; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
protected function deleteDirectory(string $path): bool |
77
|
|
|
{ |
78
|
|
|
if (! file_exists($path)) { |
79
|
|
|
return true; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
if (! is_dir($path)) { |
83
|
|
|
return unlink($path); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
foreach (scandir($path) as $item) { |
87
|
|
|
if ($item == '.' || $item == '..') { |
88
|
|
|
continue; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
if (! $this->deleteDirectory($path.DIRECTORY_SEPARATOR.$item)) { |
92
|
|
|
return false; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
return rmdir($path); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|