Lines
0.00%
0 / 14
Methods
0.00%
0 / 5
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __construct | 0.00% | 0 / 1 | 0.00% | 0 / 1 | 2 | ||
| createWithPrefix | 0.00% | 0 / 4 | 0.00% | 0 / 1 | 6 | ||
| getFilePath | 0.00% | 0 / 1 | 0.00% | 0 / 1 | 2 | ||
| remove | 0.00% | 0 / 1 | 0.00% | 0 / 1 | 2 | ||
| removeTree | 0.00% | 0 / 7 | 0.00% | 0 / 1 | 72 | ||
| 9 | final readonly class TempDirectory | |
| 10 | { | |
| 11 | private function __construct(public string $path) {} | |
| 12 | ||
| 13 | public static function createWithPrefix(string $prefix): self | |
| 14 | { | |
| 15 | $path = sys_get_temp_dir() . '/' . $prefix . bin2hex(random_bytes(6)); | |
| 16 | ||
| 17 | if (!mkdir($path, 0o700)) { | |
| 18 | throw new RuntimeException('Could not create the temporary directory ' . $path); | |
| 19 | } | |
| 20 | ||
| 21 | return new self($path); | |
| 22 | } | |
| 23 | ||
| 24 | public function getFilePath(string $name): string | |
| 25 | { | |
| 26 | return $this->path . '/' . $name; | |
| 27 | } | |
| 28 | ||
| 29 | public function remove(): void | |
| 30 | { | |
| 31 | self::removeTree($this->path); | |
| 32 | } | |
| 33 | ||
| 34 | private static function removeTree(string $path): void | |
| 35 | { | |
| 36 | if (!is_dir($path)) { | |
| 37 | return; | |
| 38 | } | |
| 39 | ||
| 40 | foreach (scandir($path) ?: [] as $entry) { | |
| 41 | if ($entry === '.' || $entry === '..') { | |
| 42 | continue; | |
| 43 | } | |
| 44 | ||
| 45 | $child = $path . '/' . $entry; | |
| 46 | is_dir($child) && !is_link($child) ? self::removeTree($child) : unlink($child); | |
| 47 | } | |
| 48 | ||
| 49 | rmdir($path); | |
| 50 | } | |
| 51 | } |