-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTempFileHandler.php
86 lines (73 loc) · 2.16 KB
/
TempFileHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Rcsofttech85\FileHandler;
use Rcsofttech85\FileHandler\Exception\FileHandlerException;
use Rcsofttech85\FileHandler\Validator\FileValidatorTrait;
class TempFileHandler
{
use FileValidatorTrait;
/**
* @param string $tempFilePath
* @param string $filename
* @return void
* @throws FileHandlerException
*/
public function renameTempFile(string $tempFilePath, string $filename): void
{
if (!rename($tempFilePath, $filename)) {
throw new FileHandlerException('Failed to rename temp file');
}
}
public function cleanupTempFile(string $tempFilePath): void
{
if (file_exists($tempFilePath)) {
unlink($tempFilePath);
}
}
/**
* @param string $tempFilePath
* @param array<string> $row
* @return void
*/
public function writeRowToTempFile(string $tempFilePath, array $row): void
{
$tempFileHandle = fopen($tempFilePath, 'a');
if ($tempFileHandle) {
fputs($tempFileHandle, implode(',', $row) . PHP_EOL);
fclose($tempFileHandle);
}
}
/**
* @param array<string> $headers
* @param string|null $dirName
* @param string|null $prefix
* @return string|false
* @throws FileHandlerException
*/
public function createTempFileWithHeaders(
array $headers,
string|null $dirName = null,
string|null $prefix = null
): string|false {
if (null === $dirName) {
$dirName = sys_get_temp_dir();
}
if (null === $prefix) {
$prefix = 'tempfile_';
}
$tempFilePath = $this->getTempName($dirName, $prefix);
if (!$tempFilePath) {
return false;
}
$tempFileHandle = $this->openFileAndReturnResource($tempFilePath);
fputs($tempFileHandle, implode(',', $headers) . PHP_EOL);
fclose($tempFileHandle);
return $tempFilePath;
}
public function getTempName(string $directory, string $prefix): string|false
{
if (!is_dir($directory)) {
return false;
}
return tempnam($directory, $prefix);
}
}