<?php

declare(strict_types=1);

namespace App\EventSubscriber;

use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class UniqueConstraintSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::EXCEPTION => 'onKernelException',
        ];
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $this->findUniqueConstraintViolation($event->getThrowable());

        if (!$exception) {
            return;
        }

        $event->setResponse(new JsonResponse(
            [
                'success' => false,
                'error' => 'nom duplique',
            ],
            JsonResponse::HTTP_CONFLICT
        ));
    }

    private function findUniqueConstraintViolation(\Throwable $throwable): ?UniqueConstraintViolationException
    {
        for ($current = $throwable; $current !== null; $current = $current->getPrevious()) {
            if ($current instanceof UniqueConstraintViolationException) {
                return $current;
            }
        }

        return null;
    }
}
