<?php
namespace App\EventSubscriber\Developers;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
class DevelopersDeserializationExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [KernelEvents::EXCEPTION => 'onKernelException'];
}
public function onKernelException(ExceptionEvent $event): void
{
$request = $event->getRequest();
$controller = $request->attributes->get('_controller');
if (!is_string($controller)) {
return;
}
if (!str_starts_with($controller, 'App\\Controller\\Developers\\Api\\')) {
return;
}
if (!$request->isMethod('POST') && !$request->isMethod('PUT') && !$request->isMethod('PATCH')) {
return;
}
$exception = $event->getThrowable();
if (!$exception instanceof ExceptionInterface) {
return;
}
$event->setThrowable(new BadRequestHttpException(
message: 'Invalid JSON request or field value.',
previous: $exception,
));
}
}