1
|
|
|
<?php |
2
|
|
|
namespace CfdiUtils\Utils\Internal; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Utility to work with temporary the creation of files. |
6
|
|
|
* Use it instead of \tempnam PHP function |
7
|
|
|
* |
8
|
|
|
* NOTE: Changes on this file will not be considering a BC since this utility class is for internal usage only |
9
|
|
|
* |
10
|
|
|
* @internal |
11
|
|
|
*/ |
12
|
|
|
final class TemporaryFile |
13
|
|
|
{ |
14
|
|
|
/** @var string */ |
15
|
|
|
private $filename; |
16
|
|
|
|
17
|
54 |
|
private function __construct(string $filename) |
18
|
|
|
{ |
19
|
54 |
|
$this->filename = $filename; |
20
|
54 |
|
} |
21
|
|
|
|
22
|
56 |
|
public static function create(string $directory = ''): self |
23
|
|
|
{ |
24
|
56 |
|
if ('' === $directory) { |
25
|
53 |
|
$directory = sys_get_temp_dir(); |
26
|
53 |
|
if (in_array($directory, ['', '.'], true)) { |
27
|
|
|
throw new \RuntimeException('System has an invalid default temp dir'); |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
56 |
|
$previousErrorLevel = error_reporting(0); |
32
|
56 |
|
$filename = strval(tempnam($directory, '')); |
33
|
56 |
|
error_reporting($previousErrorLevel); |
34
|
|
|
|
35
|
|
|
// must check realpath since windows can return different paths for same location |
36
|
56 |
|
if (realpath(dirname($filename)) !== realpath($directory)) { |
37
|
2 |
|
unlink($filename); |
38
|
2 |
|
$filename = ''; |
39
|
|
|
} |
40
|
|
|
|
41
|
56 |
|
if ('' === $filename) { |
42
|
2 |
|
throw new \RuntimeException(sprintf('Unable to create a temporary file')); |
43
|
|
|
} |
44
|
|
|
|
45
|
54 |
|
return new static($filename); |
46
|
|
|
} |
47
|
|
|
|
48
|
54 |
|
public function getPath(): string |
49
|
|
|
{ |
50
|
54 |
|
return $this->filename; |
51
|
|
|
} |
52
|
|
|
|
53
|
9 |
|
public function retriveContents(): string |
54
|
|
|
{ |
55
|
9 |
|
return strval(file_get_contents($this->filename)); |
56
|
|
|
} |
57
|
|
|
|
58
|
12 |
|
public function storeContents(string $contents) |
59
|
|
|
{ |
60
|
12 |
|
file_put_contents($this->filename, $contents); |
61
|
12 |
|
} |
62
|
|
|
|
63
|
54 |
|
public function remove() |
64
|
|
|
{ |
65
|
54 |
|
$filename = $this->getPath(); |
66
|
54 |
|
if (file_exists($filename)) { |
67
|
54 |
|
unlink($filename); |
68
|
|
|
} |
69
|
54 |
|
} |
70
|
|
|
|
71
|
14 |
|
public function __toString(): string |
72
|
|
|
{ |
73
|
14 |
|
return $this->getPath(); |
74
|
|
|
} |
75
|
|
|
|
76
|
17 |
|
public function runAndRemove(\Closure $fn) |
77
|
|
|
{ |
78
|
|
|
try { |
79
|
17 |
|
return $fn(); |
80
|
|
|
} finally { |
81
|
17 |
|
$this->remove(); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|