diff --git a/README.md b/README.md index 86d7b4a..564b5f0 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,23 @@ echo $file->getFileName(); echo $file->getTempDir(); ``` +In some places you might be forced to pass the file path instead of the instance, leading to the situation that the +instance is no longer referenced. You can delay the automatic delete until the end of the request by calling +`keepDuringRequest()`. + +```php +keepDuringRequest(); + + return $file->getFileName(); +} +``` + If you want to keep the temporary file, e.g. for debugging, you can set the `$delete` property to false: ```php diff --git a/src/File.php b/src/File.php index 2271260..d3b0c71 100644 --- a/src/File.php +++ b/src/File.php @@ -164,6 +164,21 @@ public static function getTempDir() } } + /** + * Keep a reference for this object until the request ends. + * This allows to keep the file during a request, even if the object is not passed back. + * + * @return $this + */ + public function keepDuringRequest() + { + register_shutdown_function(function () { + $this; + }); + + return $this; + } + /** * @return string the full file name */ diff --git a/tests/FileTest.php b/tests/FileTest.php index d3d0616..0d0bd29 100644 --- a/tests/FileTest.php +++ b/tests/FileTest.php @@ -94,6 +94,18 @@ public function testCanKeepTempFile() unlink($out); } + public function testCanKeepTempFileEvenIfItsNotLongerReferenced() + { + $content = 'test content'; + $tmp = new File($content); + $tmp->keepDuringRequest(); + $fileName = $tmp->getFileName(); + + $this->assertFileExists($fileName); + unset($tmp); + $this->assertFileExists($fileName); + } + public function testCanCastToFileName() { $content = 'test content';