41 lines
1.2 KiB
PHP
41 lines
1.2 KiB
PHP
<?php
|
|
// TempFileStream.php
|
|
// Created: 2021-05-02
|
|
// Updated: 2024-08-01
|
|
|
|
namespace Index\IO;
|
|
|
|
/**
|
|
* Represents a temporary file stream. Will remain in memory if the size is below a given threshold.
|
|
*/
|
|
class TempFileStream extends GenericStream {
|
|
/**
|
|
* Default maximum size the stream can be to remain in memory and not be written to disk.
|
|
*
|
|
* @var int
|
|
*/
|
|
public const MAX_MEMORY = 2 * 1024 * 1024;
|
|
|
|
/**
|
|
* @param ?string $body Contents of the stream.
|
|
* @param int $maxMemory Maximum filesize until the file is moved out of memory and to disk.
|
|
*/
|
|
public function __construct(?string $body = null, int $maxMemory = self::MAX_MEMORY) {
|
|
parent::__construct(fopen("php://temp/maxmemory:{$maxMemory}", 'r+b'));
|
|
|
|
if($body !== null) {
|
|
$this->write($body);
|
|
$this->flush();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Creates a TempFileStream from a string.
|
|
*
|
|
* @param string $string Data to write to the temporary file.
|
|
* @return TempFileStream Stream representing the given text.
|
|
*/
|
|
public static function fromString(string $string): TempFileStream {
|
|
return new TempFileStream($string);
|
|
}
|
|
}
|