ldc-cocotte/shared/Filesystem/TemporaryFileFactory.php

140 lines
4.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Shared\Filesystem;
final class TemporaryFileFactory
{
private const CHUNK_SIZE = 8192;
/** @var string[] */
private array $temporaryFilePaths = [];
/**
* @throws TemporaryFileException if the source file cannot be read or written.
*/
public function newWithContentOf(\SplFileObject $sourceFile): \SplFileObject
{
$sourceFile->rewind();
$tempFile = $this->openNewTempFile($sourceFile->getFilename());
while (! $sourceFile->eof()) {
$chunk = $sourceFile->fread(self::CHUNK_SIZE);
if ($chunk === false) {
throw new TemporaryFileException('Could not read the contents of the source file.');
}
$this->writeChunk($tempFile, $chunk);
}
$tempFile->rewind();
return $tempFile;
}
/**
* @param resource $stream
*
* @throws TemporaryFileException if the stream is not valid or readable.
*/
public function newWithStream($stream, string $originalFileName = ''): \SplFileObject
{
if (! is_resource($stream) || get_resource_type($stream) !== 'stream') {
throw new TemporaryFileException('Provided stream is not a valid stream resource.');
}
$metadata = stream_get_meta_data($stream);
if (! str_contains($metadata['mode'], 'r') && ! str_contains($metadata['mode'], '+')) {
throw new TemporaryFileException(sprintf('Stream with mode "%s" is not readable.', $metadata['mode']));
}
if ($metadata['seekable'] && ftell($stream) !== 0) {
rewind($stream);
}
$tempFile = $this->openNewTempFile($originalFileName);
while (! feof($stream)) {
$chunk = fread($stream, self::CHUNK_SIZE);
if ($chunk === false) {
throw new TemporaryFileException('Could not read from the provided stream.');
}
$this->writeChunk($tempFile, $chunk);
}
$tempFile->rewind();
return $tempFile;
}
/**
* @throws TemporaryFileException if the bytes cannot be persisted.
*/
public function newWithBytes(string $contents, string $originalFileName = ''): \SplFileObject
{
$tempFile = $this->openNewTempFile($originalFileName);
$this->writeChunk($tempFile, $contents);
$tempFile->rewind();
return $tempFile;
}
private function openNewTempFile(string $originalFileName): \SplFileObject
{
$path = $this->createTempFilePath($originalFileName);
try {
return new \SplFileObject($path, 'w+b');
} catch (\RuntimeException $e) {
throw new TemporaryFileException('Could not open temporary file.', 0, $e);
}
}
private function writeChunk(\SplFileObject $file, string $chunk): void
{
if ($chunk === '') {
return;
}
$written = $file->fwrite($chunk);
if ($written === false || $written < strlen($chunk)) {
throw new TemporaryFileException('Could not persist temporary file contents.');
}
}
private function createTempFilePath(string $originalName): string
{
$baseTempPath = tempnam(sys_get_temp_dir(), 'tmp_');
if ($baseTempPath === false) {
throw new TemporaryFileException('Could not create a temporary file path.');
}
$rawExtension = pathinfo($originalName, PATHINFO_EXTENSION);
$extension = preg_replace('/[^a-zA-Z0-9_-]/', '', $rawExtension) ?? '';
if ($extension !== '') {
$targetPath = $baseTempPath . '.' . $extension;
if (! rename($baseTempPath, $targetPath)) {
@unlink($baseTempPath);
throw new TemporaryFileException('Could not rename temporary file with extension.');
}
$baseTempPath = $targetPath;
}
$this->temporaryFilePaths[] = $baseTempPath;
return $baseTempPath;
}
public function __destruct()
{
foreach ($this->temporaryFilePaths as $path) {
if (is_file($path)) {
@unlink($path);
}
}
$this->temporaryFilePaths = [];
}
}