<?php declare(strict_types=1);
/**
*
* (c) BonBonSlick
*
*/
/**
* (c) BonBonSlick
*/
/*
* Created by BonBonSlick
* Contacts: google it
* Date: 10/13/18
* Time: 2:21 PM
*/
namespace App\Subscribers;
use function is_array;
use function json_decode;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class self
*/
final class BeforeControllerActionSubscriber implements EventSubscriberInterface
{
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'convertJsonStringToArray',
];
}
/**
* @param FilterControllerEvent $event
*/
public function convertJsonStringToArray(FilterControllerEvent $event): void
{
$request = $event->getRequest();
$requestContent = $request->getContent();
// check if json and not empty content
$isContentEmpty = true === empty($requestContent) || null === $requestContent || '' === trim($requestContent);
if (true === $isContentEmpty || $request->getContentType() !== 'json') {
return;
}
// check for errors
$jsonContent = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new BadRequestHttpException('Invalid json body: ' . json_last_error_msg());
}
// replace request data with json content
$request->request->replace(is_array($jsonContent) ? $jsonContent : []);
}
}