| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <?php
- declare(strict_types=1);
- namespace App\EventSubscriber;
- use ApiPlatform\Core\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[]
- */
- public static function getSubscribedEvents()
- {
- 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);
- }
- }
- }
|