Skip to content

Commit

Permalink
Delete all uploaded files after request handle
Browse files Browse the repository at this point in the history
  • Loading branch information
luzrain committed May 15, 2024
1 parent 7d82a57 commit 47938c6
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions src/Http/HttpRequestHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
use Psr\Http\Message\StreamFactoryInterface;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\UploadedFile;
use Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface;
use Symfony\Bridge\PsrHttpMessage\HttpMessageFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;

Expand Down Expand Up @@ -48,7 +51,8 @@ public function __invoke(ServerRequestInterface $request): ResponseInterface

private function handleFile(string $file): ResponseInterface
{
return $this->responseFactory->createResponse()
return $this->responseFactory
->createResponse()
->withBody($this->streamFactory->createStreamFromFile($file))
->withHeader('Content-Type', (new MimeTypeMapper())->lookupMimeTypeFromPath($file))
;
Expand All @@ -66,14 +70,24 @@ private function handle(ServerRequestInterface $request): ResponseInterface
/** @var WorkerProcess $worker */
$worker = $this->kernel->getContainer()->get('phpstreamserver.worker');

$worker->getEventLoop()->defer(fn() => $this->terminate($symfonyRequest, $symfonyResponse));

return $this->psrHttpFactory->createResponse($symfonyResponse);
}

private function terminate(Request $symfonyRequest, Response $symfonyResponse): void
{
if ($this->kernel instanceof TerminableInterface) {
$worker->getEventLoop()->defer(function () use ($symfonyRequest, $symfonyResponse): void {
/** @psalm-suppress UndefinedInterfaceMethod */
$this->kernel->terminate($symfonyRequest, $symfonyResponse);
});
$this->kernel->terminate($symfonyRequest, $symfonyResponse);
}

return $this->psrHttpFactory->createResponse($symfonyResponse);
// Delete all uploaded files
$files = $symfonyRequest->files->all();
\array_walk_recursive($files, static function (UploadedFile $file) {
if (\file_exists($file->getRealPath())) {
\unlink($file->getRealPath());
}
});
}

private function findFileInPublicDirectory(string $requestPath): string|null
Expand Down

0 comments on commit 47938c6

Please sign in to comment.