[HttpFoundation] Added a switch to delete file after the response is send
This commit is contained in:
parent
e42c07b1d6
commit
1fff158646
@ -30,6 +30,7 @@ class BinaryFileResponse extends Response
|
||||
protected $file;
|
||||
protected $offset;
|
||||
protected $maxlen;
|
||||
protected $deleteFileAfterSend = false;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
@ -258,6 +259,10 @@ class BinaryFileResponse extends Response
|
||||
|
||||
fclose($out);
|
||||
fclose($file);
|
||||
|
||||
if ($this->deleteFileAfterSend) {
|
||||
unlink($this->file->getPathname());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -289,4 +294,19 @@ class BinaryFileResponse extends Response
|
||||
{
|
||||
self::$trustXSendfileTypeHeader = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* If this is set to true, the file will be unlinked after the request is send
|
||||
* Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
|
||||
* @param bool $shouldDelete
|
||||
*
|
||||
* @return BinaryFileResponse
|
||||
*/
|
||||
public function deleteFileAfterSend($shouldDelete)
|
||||
{
|
||||
$this->deleteFileAfterSend = $shouldDelete;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -203,6 +203,24 @@ class BinaryFileResponseTest extends ResponseTestCase
|
||||
$this->assertEquals($virtual, $response->headers->get('X-Accel-Redirect'));
|
||||
}
|
||||
|
||||
public function testDeleteFileAfterSend()
|
||||
{
|
||||
$request = Request::create('/');
|
||||
|
||||
$path = __DIR__.'/File/Fixtures/to_delete';
|
||||
touch($path);
|
||||
$realPath = realpath($path);
|
||||
$this->assertFileExists($realPath);
|
||||
|
||||
$response = new BinaryFileResponse($realPath);
|
||||
$response->deleteFileAfterSend(true);
|
||||
|
||||
$response->prepare($request);
|
||||
$response->sendContent();
|
||||
|
||||
$this->assertFileNotExists($path);
|
||||
}
|
||||
|
||||
public function getSampleXAccelMappings()
|
||||
{
|
||||
return array(
|
||||
@ -215,4 +233,12 @@ class BinaryFileResponseTest extends ResponseTestCase
|
||||
{
|
||||
return new BinaryFileResponse(__DIR__ . '/../README.md');
|
||||
}
|
||||
|
||||
public static function tearDownAfterClass()
|
||||
{
|
||||
$path = __DIR__.'/../Fixtures/to_delete';
|
||||
if (file_exists($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user