|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Paraunit\File; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class TempDirectory |
|
9
|
|
|
* @package Paraunit\File |
|
10
|
|
|
*/ |
|
11
|
|
|
class TempDirectory |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var string[] */ |
|
14
|
|
|
private static $tempDirs = [ |
|
15
|
|
|
'/dev/shm', |
|
16
|
|
|
]; |
|
17
|
|
|
|
|
18
|
|
|
/** @var string */ |
|
19
|
|
|
private static $timestamp; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Paraunit constructor. |
|
23
|
|
|
*/ |
|
24
|
72 |
|
public function __construct() |
|
25
|
|
|
{ |
|
26
|
72 |
|
self::$timestamp = uniqid(date('Ymd-His'), true); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @return string |
|
31
|
|
|
* @throws \RuntimeException If the temp dirs cannot be created |
|
32
|
|
|
*/ |
|
33
|
64 |
|
public function getTempDirForThisExecution(): string |
|
34
|
|
|
{ |
|
35
|
64 |
|
$dir = self::getTempBaseDir() . DIRECTORY_SEPARATOR . self::$timestamp; |
|
36
|
64 |
|
self::mkdirIfNotExists($dir); |
|
37
|
64 |
|
self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'config'); |
|
38
|
64 |
|
self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'logs'); |
|
39
|
64 |
|
self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'coverage'); |
|
40
|
|
|
|
|
41
|
64 |
|
return $dir; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* @return string |
|
46
|
|
|
* |
|
47
|
|
|
* @throws \RuntimeException |
|
48
|
|
|
*/ |
|
49
|
64 |
|
public static function getTempBaseDir(): string |
|
50
|
|
|
{ |
|
51
|
64 |
|
$dirs = self::$tempDirs; |
|
52
|
|
|
// Fallback to sys temp dir |
|
53
|
64 |
|
$dirs[] = sys_get_temp_dir(); |
|
54
|
|
|
|
|
55
|
64 |
|
foreach ($dirs as $directory) { |
|
56
|
64 |
|
if (file_exists($directory)) { |
|
57
|
64 |
|
$baseDir = $directory . DIRECTORY_SEPARATOR . 'paraunit'; |
|
58
|
|
|
|
|
59
|
|
|
try { |
|
60
|
64 |
|
self::mkdirIfNotExists($baseDir); |
|
61
|
|
|
|
|
62
|
64 |
|
return $baseDir; |
|
63
|
|
|
} catch (\RuntimeException $e) { |
|
64
|
|
|
// ignore and try next dir |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
throw new \RuntimeException('Unable to create a temporary directory'); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* @param string $path |
|
74
|
|
|
* |
|
75
|
|
|
* @throws \RuntimeException If the dir cannot be created |
|
76
|
|
|
*/ |
|
77
|
64 |
|
public static function mkdirIfNotExists(string $path) |
|
78
|
|
|
{ |
|
79
|
64 |
|
if (file_exists($path)) { |
|
80
|
63 |
|
return; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
64 |
|
if (! mkdir($path) && ! is_dir($path)) { |
|
84
|
|
|
throw new \RuntimeException('Unable to create temporary directory ' . $path); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|