From 608959f15d3a6f623793e340c50560a5414a8895 Mon Sep 17 00:00:00 2001 From: Dominik Kohler Date: Mon, 14 Sep 2020 16:37:30 +0200 Subject: [PATCH] added developer-friendly way to keep the temporary file until the end of the request --- README.md | 17 +++++++++++++++++ src/File.php | 15 +++++++++++++++ tests/FileTest.php | 12 ++++++++++++ 3 files changed, 44 insertions(+) diff --git a/README.md b/README.md index 2435d90..4bcce44 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,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 98eb3dc..a1d7845 100644 --- a/src/File.php +++ b/src/File.php @@ -135,6 +135,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 de5dc83..7a543af 100644 --- a/tests/FileTest.php +++ b/tests/FileTest.php @@ -86,6 +86,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';