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
|
66 |
|
public function __construct() |
25
|
|
|
{ |
26
|
66 |
|
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
|
58 |
|
public function getTempDirForThisExecution(): string |
34
|
|
|
{ |
35
|
58 |
|
$dir = self::getTempBaseDir() . DIRECTORY_SEPARATOR . self::$timestamp; |
36
|
58 |
|
self::mkdirIfNotExists($dir); |
37
|
58 |
|
self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'config'); |
38
|
58 |
|
self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'logs'); |
39
|
58 |
|
self::mkdirIfNotExists($dir . DIRECTORY_SEPARATOR . 'coverage'); |
40
|
|
|
|
41
|
58 |
|
return $dir; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @return string |
46
|
|
|
* |
47
|
|
|
* @throws \RuntimeException |
48
|
|
|
*/ |
49
|
58 |
|
public static function getTempBaseDir(): string |
50
|
|
|
{ |
51
|
58 |
|
$dirs = self::$tempDirs; |
52
|
|
|
// Fallback to sys temp dir |
53
|
58 |
|
$dirs[] = sys_get_temp_dir(); |
54
|
|
|
|
55
|
58 |
|
foreach ($dirs as $directory) { |
56
|
58 |
|
if (file_exists($directory)) { |
57
|
58 |
|
$baseDir = $directory . DIRECTORY_SEPARATOR . 'paraunit'; |
58
|
|
|
|
59
|
|
|
try { |
60
|
58 |
|
self::mkdirIfNotExists($baseDir); |
61
|
|
|
|
62
|
58 |
|
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
|
58 |
|
public static function mkdirIfNotExists(string $path) |
78
|
|
|
{ |
79
|
58 |
|
if (file_exists($path)) { |
80
|
57 |
|
return; |
81
|
|
|
} |
82
|
|
|
|
83
|
58 |
View Code Duplication |
if (! mkdir($path) && ! is_dir($path)) { |
|
|
|
|
84
|
|
|
throw new \RuntimeException('Unable to create temporary directory ' . $path); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.