<?php
/*
* This file is part of the cargo app.
*
* Copyright 2024 logist.cloud <support@logist.cloud>
*/
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\AcceptHeader;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Exception\LogistProdException;
/**
* @author Grigoriy Kulin <yarboroda@gmail.com>
*/
class ExceptionListener
{
public function __construct(#[Autowire(value: '%kernel.environment%')] private string $env)
{
}
public function __invoke(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$request = $event->getRequest();
$accept = AcceptHeader::fromString($request->headers->get('Accept'));
if(!$accept->has('application/json') || !$exception instanceof \JsonSerializable){
return;
}
$code = $exception->getCode();
if($this->env !== 'dev' && $this->env !== 'test'){
$exception = new LogistProdException('exception proxy for prod', $code, $exception);
}
$response = new JsonResponse($exception, $code, ['Content-Type' => $request->getMimeType('application/json')]);
$event->setResponse($response);
}
}