Repository URL to install this package:
|
Version:
6.2.1 ▾
|
digitalascetic/entity-associations
/
EventListener
/
ExceptionEntityAssociationSerializerSubscriber.php
|
|---|
<?php
namespace DigitalAscetic\EntityAssociationsBundle\EventListener;
use DigitalAscetic\EntityAssociationsBundle\Entity\ExceptionEntityAssociation;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
#[AsEventListener(event: KernelEvents::EXCEPTION, method: 'onKernelException')]
class ExceptionEntityAssociationSerializerSubscriber
{
public function onKernelException(ExceptionEvent $event)
{
if ($this->isExceptionEntityAssociation($event->getThrowable())) {
/** @var ExceptionEntityAssociation $exception */
$exception = $event->getThrowable();
$response = new JsonResponse(
$this->convertToArray($exception),
500
);
$response->headers->set('Content-Type', 'application/json');
$event->setResponse($response);
}
}
private function isExceptionEntityAssociation($entity)
{
return ($entity instanceof ExceptionEntityAssociation);
}
/**
* @param \Exception $exception
*
* @return array
*/
protected function convertToArray(ExceptionEntityAssociation $exception)
{
$error = [];
$error['code'] = $exception->getCode();
$errorException['class'] = ExceptionEntityAssociation::class;
$errorException['associations'] = $exception->getAssociations();
$errorException['message'] = $exception->getMessage();
$traces = $exception->getTrace();
$errorException['trace'] = [];
foreach ($traces as $trace) {
$errorException['trace'][] = json_encode($trace);
}
$error['exception'] = [];
$error['exception'][] = $errorException;
$data = [];
$data['error'] = $error;
return $data;
}
}