-
Notifications
You must be signed in to change notification settings - Fork 1
/
WithTempFile.php
33 lines (26 loc) · 906 Bytes
/
WithTempFile.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
<?php declare(strict_types = 1);
namespace LastDragon_ru\LaraASP\Testing\Utils;
use LastDragon_ru\LaraASP\Testing\Package;
use SplFileInfo;
use Symfony\Component\Filesystem\Filesystem;
use function register_shutdown_function;
use function sys_get_temp_dir;
/**
* Allows to create a temporary file. The file will be removed automatically
* after script shutdown.
*/
trait WithTempFile {
public static function getTempFile(?string $content = null, string $suffix = ''): SplFileInfo {
$fs = new Filesystem();
$pkg = Package::Name;
$path = $fs->tempnam(sys_get_temp_dir(), $pkg, $suffix);
$file = new SplFileInfo($path);
if ($content !== null) {
$fs->dumpFile($path, $content);
}
register_shutdown_function(static function () use ($fs, $path): void {
$fs->remove($path);
});
return $file;
}
}