<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class OptionsApiRequestListener implements EventSubscriberInterface
{
public function onKernelResponse(ResponseEvent $event): void
{
if (HttpKernelInterface::MAIN_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
$response = $event->getResponse();
if (Request::METHOD_OPTIONS === $request->getMethod()
&& $response->getStatusCode() == Response::HTTP_METHOD_NOT_ALLOWED
&& !str_starts_with($request->getUri(), '/api/')
) {
$response = new Response(
'',
Response::HTTP_OK
);
$event->setResponse($response);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
}