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

Cleanup uploaded files for PSR-15 handlers #1726

Merged
merged 4 commits into from Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Event/Http/Psr15Handler.php
Expand Up @@ -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);
Expand Down
19 changes: 18 additions & 1 deletion src/Event/Http/Psr7Bridge.php
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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');
}
Expand Down Expand Up @@ -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);
mnapoli marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
}
}