<?php
/*
* Disclaimer: This source code is protected by copyright law and by
* international conventions.
*
* Any reproduction or partial or total distribution of the source code, by any
* means whatsoever, is strictly forbidden.
*
* Anyone not complies with these provisions will be guilty of the offense of
* infringement and the penal sanctions provided for by law.
*
* © 2022 All rights reserved.
*/
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class JsonRequestListener
*
* @author Rémy P. <r.peyron@ingeno.eu>
* @package App\EventListener
*/
class JsonRequestListener implements EventSubscriberInterface
{
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [KernelEvents::CONTROLLER => 'convertJsonStringToArray'];
}
/**
* @param ControllerEvent $event
* @return void
*/
public function convertJsonStringToArray(ControllerEvent $event)
{
$request = $event->getRequest();
if ($request->getContentType() !== 'json' || !$request->getContent()) {
return;
}
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new BadRequestHttpException('invalid json body: ' . json_last_error_msg());
}
$request->request->replace(is_array($data) ? $data : []);
}
}