<?php
namespace Suzuki\CoreBundle\APIExceptions;
use Suzuki\CoreComponent\APIExceptions\APIExceptionInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class APIExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($event->getException() instanceof APIExceptionInterface) {
$response = new JsonResponse($this->buildResponseData($event->getException()));
$response->setStatusCode($event->getException()->getCode());
$event->setResponse($response);
}
}
/**
* @param APIExceptionInterface $exception
*
* @return array
*/
private function buildResponseData(ApiExceptionInterface $exception)
{
$messages = json_decode($exception->getMessage());
if ( !is_array($messages)) {
$messages = $exception->getMessage() ? [$exception->getMessage()] : [];
}
return [
'error' => [
'code' => $exception->getCode(),
'messages' => $messages,
],
];
}
}