vendor/coreshop/resource-bundle/EventListener/BodyListener.php line 28

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * CoreShop
  5.  *
  6.  * This source file is available under two different licenses:
  7.  *  - GNU General Public License version 3 (GPLv3)
  8.  *  - CoreShop Commercial License (CCL)
  9.  * Full copyright and license information is available in
  10.  * LICENSE.md which is distributed with this source code.
  11.  *
  12.  * @copyright  Copyright (c) CoreShop GmbH (https://www.coreshop.org)
  13.  * @license    https://www.coreshop.org/license     GPLv3 and CCL
  14.  *
  15.  */
  16. namespace CoreShop\Bundle\ResourceBundle\EventListener;
  17. use Symfony\Component\HttpFoundation\InputBag;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpKernel\Event\RequestEvent;
  20. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  21. class BodyListener
  22. {
  23.     public function onKernelRequest(RequestEvent $event): void
  24.     {
  25.         $request $event->getRequest();
  26.         $contentType $request->headers->get('Content-Type');
  27.         $format null === $contentType $request->getRequestFormat() : $request->getFormat($contentType);
  28.         $content $request->getContent();
  29.         if ($this->isDecodeable($request)) {
  30.             if ($format === 'json') {
  31.                 if (!empty($content)) {
  32.                     $data = @json_decode($contenttrue);
  33.                     if (is_array($data)) {
  34.                         $request->request = new InputBag($data);
  35.                     } else {
  36.                         throw new BadRequestHttpException('Invalid ' $format ' message received');
  37.                     }
  38.                 }
  39.             }
  40.         }
  41.     }
  42.     protected function isDecodeable(Request $request): bool
  43.     {
  44.         if (!in_array($request->getMethod(), ['POST''PUT''PATCH''DELETE'])) {
  45.             return false;
  46.         }
  47.         return !$this->isFormRequest($request);
  48.     }
  49.     private function isFormRequest(Request $request): bool
  50.     {
  51.         if (null === $request->headers->get('Content-Type')) {
  52.             return false;
  53.         }
  54.         $contentTypeParts explode(';'$request->headers->get('Content-Type'));
  55.         if (isset($contentTypeParts[0])) {
  56.             return in_array($contentTypeParts[0], ['multipart/form-data''application/x-www-form-urlencoded']);
  57.         }
  58.         return false;
  59.     }
  60. }