<?php

namespace KupShop\WarehouseBundle\EventListener;

use KupShop\WarehouseBundle\Exception\WarehouseBaseException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ExceptionListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::EXCEPTION => [
                ['handleException', 50],
            ],
        ];
    }

    public function handleException(ExceptionEvent $event)
    {
        $exception = $event->getThrowable();

        if ($exception instanceof WarehouseBaseException) {
            $event->setResponse(new JsonResponse(['result' => false, 'message' => $exception->getMessage()]));
            $event->stopPropagation();
        }
    }
}
