src/EventSubscriber/JSONRequestTransformer.php line 16

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace PPApi\EventSubscriber;
  3. use PPApi\Model\V1\APIError;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class JSONRequestTransformer implements EventSubscriberInterface
  10. {
  11.     public function onKernelRequest(RequestEvent $event)
  12.     {
  13.         if (!$event->isMainRequest()) {
  14.             return;
  15.         }
  16.         $request $event->getRequest();
  17.         if (
  18.             // allow GET request with header `Content-Type`
  19.             $request->isMethod('GET') ||
  20.             $request->isMethod('DELETE') ||
  21.             (
  22.                 // for cases like: application/json; charset=UTF-8 etc
  23.                 !str_contains($request->headers->get('Content-Type'), 'application/json') &&
  24.                 // addon requesting '/authenticate' endpoint with missing content-type header
  25.                 !preg_match('~^/authenticate~'$event->getRequest()->getPathInfo())
  26.             )
  27.         ) {
  28.             return;
  29.         }
  30.         if (!$this->transformJsonBody($request)) {
  31.             $err = new APIError(JsonResponse::HTTP_INTERNAL_SERVER_ERROR'Invalid JSON format.');
  32.             $response = new JsonResponse($errJsonResponse::HTTP_BAD_REQUEST);
  33.             $event->setResponse($response);
  34.         }
  35.     }
  36.     private function transformJsonBody(Request $request) {
  37.         $data json_decode($request->getContent(), true);
  38.         if (json_last_error() !== JSON_ERROR_NONE) {
  39.             return false;
  40.         }
  41.         if ($data === null) {
  42.             return true;
  43.         }
  44.         $request->request->replace($data);
  45.         return true;
  46.     }
  47.     public static function getSubscribedEvents(): array
  48.     {
  49.         return [
  50.             KernelEvents::REQUEST => ['onKernelRequest'100],
  51.         ];
  52.     }
  53. }