<?php
declare(strict_types=1);

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\ApiResources\ApiResourcesInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
 * Class ApiResourcesValidatorSubscriber : EventSubscriber qui déploit le system de validator de symfony si la resource est une instance de ApiResources
 * @package App\EventSubscriber
 */
final class ApiResourcesValidatorSubscriber implements EventSubscriberInterface
{
    public function __construct(private  ValidatorInterface $validator)
    {
    }

    /**
     * ne se déclenche qu'après le post validate d'api platform
     * @return array<string, array<int, int|string>>
     */
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['validate', EventPriorities::POST_VALIDATE],
        ];
    }

    /**
     * Si l'entité est une instance de ApiResourcesInterface, alors on active le validator
     * @param ViewEvent $event
     * @throws \Exception
     */
    public function validate(ViewEvent $event): void
    {
        $entity = $event->getControllerResult();

        if(!$entity instanceof ApiResourcesInterface)
            return;

        $violations = $this->validator->validate($entity);

        if (0 !== count($violations)) {
            $messages = [];
            // there are errors, now you can show them
            foreach ($violations as $violation) {
                $messages[] = $violation->getMessage();
            }
            throw new \Exception(join(',', $messages), 500);
        }
    }
}