vendor/qandidate/symfony-json-request-transformer/src/JsonRequestTransformerListener.php line 25

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the qandidate/symfony-json-request-transformer package.
  5.  *
  6.  * (c) Qandidate.com <opensource@qandidate.com>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Qandidate\Common\Symfony\HttpKernel\EventListener;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpKernel\Event\RequestEvent;
  15. /**
  16.  * Transforms the body of a json request to POST parameters.
  17.  */
  18. class JsonRequestTransformerListener
  19. {
  20.     public function onKernelRequest(RequestEvent $event): void
  21.     {
  22.         $request $event->getRequest();
  23.         if (!$this->isJsonRequest($request)) {
  24.             return;
  25.         }
  26.         $content $request->getContent();
  27.         if (empty($content)) {
  28.             return;
  29.         }
  30.         if (!$this->transformJsonBody($request)) {
  31.             $response = new Response('Unable to parse request.'Response::HTTP_BAD_REQUEST);
  32.             $event->setResponse($response);
  33.         }
  34.     }
  35.     private function isJsonRequest(Request $request): bool
  36.     {
  37.         // Request::getContentType() is deprecated since Symfony 6.2
  38.         return 'json' === (method_exists($request'getContentTypeFormat') ? $request->getContentTypeFormat() : $request->getContentType());
  39.     }
  40.     private function transformJsonBody(Request $request): bool
  41.     {
  42.         $data json_decode((string) $request->getContent(), true);
  43.         if (JSON_ERROR_NONE !== json_last_error()) {
  44.             return false;
  45.         }
  46.         if (is_null($data) || is_bool($data)) {
  47.             return true;
  48.         }
  49.         if (!is_array($data)) {
  50.             return false;
  51.         }
  52.         $request->request->replace($data);
  53.         return true;
  54.     }
  55. }