From c77d9f5abf021f29fa96b5720b7b84adbd199092 Mon Sep 17 00:00:00 2001 From: Matthieu Napoli Date: Mon, 29 Jan 2024 10:20:41 +0100 Subject: [PATCH] Cleanup uploaded files for PSR-15 handlers --- src/Event/Http/Psr15Handler.php | 2 ++ src/Event/Http/Psr7Bridge.php | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/Event/Http/Psr15Handler.php b/src/Event/Http/Psr15Handler.php index 79ea99e1e..b263ef928 100644 --- a/src/Event/Http/Psr15Handler.php +++ b/src/Event/Http/Psr15Handler.php @@ -16,6 +16,8 @@ public function __construct(RequestHandlerInterface $psr15Handler) public function handleRequest(HttpRequestEvent $event, Context $context): HttpResponse { + Psr7Bridge::cleanupUploadedFiles(); + $request = Psr7Bridge::convertRequest($event, $context); $response = $this->psr15Handler->handle($request); diff --git a/src/Event/Http/Psr7Bridge.php b/src/Event/Http/Psr7Bridge.php index 2db1406d0..05532bd03 100644 --- a/src/Event/Http/Psr7Bridge.php +++ b/src/Event/Http/Psr7Bridge.php @@ -18,6 +18,8 @@ */ final class Psr7Bridge { + private const UPLOADED_FILES_PREFIX = 'bref_upload_'; + /** * Create a PSR-7 server request from an AWS Lambda HTTP event. */ @@ -106,7 +108,7 @@ private static function parseBodyAndUploadedFiles(HttpRequestEvent $event): arra $parsedBody = []; foreach ($document->getParts() as $part) { if ($part->isFile()) { - $tmpPath = tempnam(sys_get_temp_dir(), 'bref_upload_'); + $tmpPath = tempnam(sys_get_temp_dir(), self::UPLOADED_FILES_PREFIX); if ($tmpPath === false) { throw new RuntimeException('Unable to create a temporary directory'); } @@ -166,4 +168,19 @@ private static function parseKeyAndInsertValueInArray(array &$array, string $key $pointer = $value; } + + /** + * Cleanup previously uploaded files. + */ + public static function cleanupUploadedFiles(): void + { + $tmpFiles = glob(sys_get_temp_dir() . '/' . self::UPLOADED_FILES_PREFIX . '*'); + if ($tmpFiles !== false) { + foreach ($tmpFiles as $file) { + if(is_file($file)) { + unlink($file); + } + } + } + } }