-
Notifications
You must be signed in to change notification settings - Fork 1
/
SymfonyMiddleware.php
54 lines (46 loc) · 2.07 KB
/
SymfonyMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace App\Middleware;
use App\Kernel;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Factory\ResponseFactory;
use Slim\Psr7\Factory\ServerRequestFactory;
use Slim\Psr7\Factory\StreamFactory;
use Slim\Psr7\Factory\UploadedFileFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
final readonly class SymfonyMiddleware implements MiddlewareInterface
{
public function __construct(
public string $appEnv,
public bool $appDebug
) {
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$kernel = new Kernel($this->appEnv, $this->appDebug);
$httpFoundationFactory = new HttpFoundationFactory();
$psrHttpFactory = new PsrHttpFactory(new ServerRequestFactory(), new StreamFactory(), new UploadedFileFactory(), new ResponseFactory());
$kernel->boot();
$dispatcher = $kernel->getContainer()->get('event_dispatcher');
$dispatcher->addListener(
'kernel.exception',
function (ExceptionEvent $event) use ($request, $handler, $httpFoundationFactory): void {
if ($event->getThrowable() instanceof NotFoundHttpException) {
$event->allowCustomResponseCode();
$psr7Response = $handler->handle($request);
$response = $httpFoundationFactory->createResponse($psr7Response);
$event->setResponse($response);
}
}
);
$symfonyRequest = $httpFoundationFactory->createRequest($request);
$symfonyResponse = $kernel->handle($symfonyRequest);
$kernel->terminate($symfonyRequest, $symfonyResponse);
return $psrHttpFactory->createResponse($symfonyResponse);
}
}