Skip to content

Instantly share code, notes, and snippets.

@rgeraads
Last active August 18, 2023 11:41
Show Gist options
  • Save rgeraads/0507a5869555cf243ad31aaf1e93081d to your computer and use it in GitHub Desktop.
Save rgeraads/0507a5869555cf243ad31aaf1e93081d to your computer and use it in GitHub Desktop.
Temporary file for when a file path is required
<?php declare(strict_types=1);
final class TempFile
{
/** @var resource */
private $fileHandle;
/**
* @param resource $fileHandle
*/
private function __construct($fileHandle)
{
$this->fileHandle = $fileHandle;
}
public static function fromData(string $data): self
{
$fileHandle = tmpfile();
fwrite($fileHandle, $data);
return new self($fileHandle);
}
public function getPath(): string
{
return stream_get_meta_data($this->fileHandle)['uri'];
}
public function __destruct()
{
fclose($this->fileHandle);
}
}
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class TempFileTest extends TestCase
{
/** @test */
public function it_should_create_a_temp_file(): void
{
$tempFile = TempFile::fromData('foo');
$filePath = $tempFile->getPath();
self::assertFileExists($filePath);
$tempFile = null;
self::assertFileDoesNotExist($filePath);
}
/** @test */
public function it_should_expose_its_path(): void
{
$tempFile = TempFile::fromData('foo');
$filePath = $tempFile->getPath();
self::assertStringStartsWith('/tmp/php', $filePath);
}
/** @test */
public function it_should_create_unique_paths(): void
{
$filePaths = [
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
(TempFile::fromData('foo'))->getPath(),
];
self::assertCount(10, array_unique($filePaths));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment