From 1fff15864697c6078a74d0a53dab79a5a88803f4 Mon Sep 17 00:00:00 2001 From: WybrenKoelmans Date: Fri, 4 Jul 2014 11:05:25 +0200 Subject: [PATCH] [HttpFoundation] Added a switch to delete file after the response is send --- .../HttpFoundation/BinaryFileResponse.php | 20 ++++++++++++++ .../Tests/BinaryFileResponseTest.php | 26 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php index 986dde1ac6..e01f3dc717 100644 --- a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php +++ b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php @@ -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; + } + } diff --git a/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php index d7d1b03c3c..1323a75aa8 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php @@ -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); + } + } }