<?php
/**
 * Created by PhpStorm.
 * User: vbourdeix
 * Date: 21/03/2018
 * Time: 00:11
 */

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class ExceptionSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::EXCEPTION => 'processException'
        );
    }

    public function processException(GetResponseForExceptionEvent $event)
    {
        if ( $_ENV['APP_ENV'] == 'dev') return;

        $exception = $event->getException();
        if ($exception instanceof HttpExceptionInterface) {
            $statusCode = $exception->getStatusCode();
            $message = $exception->getMessage();
        } else {
            $statusCode = 500;
            $message = "L'application a rencontrée une erreur imprévue.";
        }

        $apiErrorResponse = new JsonResponse();
        $apiErrorResponse->setContent(
            json_encode(
                array(
                    "error" => $message
                )
            ),
            $statusCode
        );
        $event->setResponse($apiErrorResponse);
    }
}