vendor/launchpad/backend/src/Base/EventListener/CorsListener.php line 40

Open in your IDE?
  1. <?php
  2. namespace LaunchPad\Bundle\LaunchPadBundle\Base\EventListener;
  3. use Psr\Container\ContainerInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. final class CorsListener implements EventSubscriberInterface
  9. {
  10.     private $config;
  11.     /**
  12.      * CorsListener constructor.
  13.      * @param array $config
  14.      */
  15.     public function __construct(array $config)
  16.     {
  17.         $this->config $config['cors'];
  18.     }
  19.     /**
  20.      * @return array
  21.      */
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             KernelEvents::RESPONSE => ['onKernelResponse'9999],
  26.         ];
  27.     }
  28.     /**
  29.      * @param ResponseEvent $event
  30.      * @return void
  31.      */
  32.     public function onKernelResponse(ResponseEvent $event): void
  33.     {
  34.         if (!$event->isMasterRequest()) {
  35.             return;
  36.         }
  37.         $defaultHeaders $this->getDefaultHeaders();
  38.         if ($event->getRequest()->getMethod() === 'OPTIONS') {
  39.             $event->setResponse(
  40.                 new Response(
  41.                     '',
  42.                     200,
  43.                     $defaultHeaders + ['Content-Length' => 0]
  44.                 )
  45.             );
  46.             return ;
  47.         }
  48.         $response $event->getResponse();
  49.         if (!$response) {
  50.             return;
  51.         }
  52.         foreach($defaultHeaders as $headerName => $headerValue) {
  53.             $response->headers->set($headerName$headerValue);
  54.         }
  55.     }
  56.     /**
  57.      * Get default headers
  58.      *
  59.      * @return array
  60.      */
  61.     private function getDefaultHeaders()
  62.     {
  63.         return [
  64.             'Access-Control-Allow-Origin' => $this->getConfig('allow_origin'),
  65.             'Access-Control-Allow-Methods' => $this->getConfig('allow_methods'),
  66.             'Access-Control-Allow-Headers' => $this->getConfig('allow_headers'),
  67.         ];
  68.     }
  69.     /**
  70.      * @param $key
  71.      * @return mixed|null
  72.      */
  73.     private function getConfig($key)
  74.     {
  75.         return $this->config[$key] ?? null;
  76.     }
  77. }