Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a developer-friendly way to keep the file until the end of the request #20

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<?php
use mikehaertl\tmp\File;

function getTemporaryFilePath() : string
{
$file = new File('some content');
$file->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
Expand Down
15 changes: 15 additions & 0 deletions src/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
12 changes: 12 additions & 0 deletions tests/FileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Loading