src/EventListener/RouterListener.php line 16

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. class RouterListener
  6. {
  7.     public const ALLOWED_METHOD = [
  8.         Request::METHOD_PUT,
  9.         Request::METHOD_DELETE,
  10.         Request::METHOD_PATCH,
  11.     ];
  12.     public function onKernelRequest(RequestEvent $event): void
  13.     {
  14.         if (!$event->isMainRequest()) {
  15.             // don't do anything if it's not the main request
  16.             return;
  17.         }
  18.         $method $event->getRequest()?->getMethod();
  19.         if ($method === Request::METHOD_GET) {
  20.             // don't do anything if it's method GET
  21.             return;
  22.         }
  23.         $realMethod $event->getRequest()?->headers?->get('x-real-method');
  24.         if (!$realMethod) {
  25.             // don't do anything if it's not have custom header x-real-method
  26.             return;
  27.         }
  28.         if (!in_array($realMethodself::ALLOWED_METHOD)) {
  29.             return;
  30.         }
  31.         $event->getRequest()->setMethod($realMethod);
  32.     }
  33. }