src/EventListener/OptionsApiRequestListener.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. use Symfony\Component\HttpKernel\HttpKernelInterface;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class OptionsApiRequestListener implements EventSubscriberInterface
  10. {
  11.     public function onKernelResponse(ResponseEvent $event): void
  12.     {
  13.         if (HttpKernelInterface::MAIN_REQUEST !== $event->getRequestType()) {
  14.             return;
  15.         }
  16.         $request $event->getRequest();
  17.         $response $event->getResponse();
  18.         if (Request::METHOD_OPTIONS === $request->getMethod()
  19.             && $response->getStatusCode() == Response::HTTP_METHOD_NOT_ALLOWED
  20.             && !str_starts_with($request->getUri(), '/api/')
  21.         ) {
  22.             $response = new Response(
  23.                 '',
  24.                 Response::HTTP_OK
  25.             );
  26.             $event->setResponse($response);
  27.         }
  28.     }
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             KernelEvents::RESPONSE => 'onKernelResponse',
  33.         ];
  34.     }
  35. }