src/EventSubscriber/DtoSubscriber.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Service\ServiceException;
  4. use App\Event\AfterDtoCreatedEvent;
  5. use App\Service\ValidationExceptionData;
  6. use Symfony\Component\Validator\Validator\ValidatorInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class DtoSubscriber implements EventSubscriberInterface
  9. {
  10.     public function __construct(private ValidatorInterface $validator)
  11.     {
  12.     }
  13.     public static function getSubscribedEvents(): array
  14.     {
  15.         return [
  16.             AfterDtoCreatedEvent::NAME => 'validateDto'
  17.         ];
  18.     }
  19.     public function validateDto(AfterDtoCreatedEvent $event): void
  20.     {
  21.         $dto $event->getDto();
  22.         $errors $this->validator->validate($dto);
  23.         if (count($errors) > 0) {
  24.             $validationExceptionData = new ValidationExceptionData(422'ConstraintViolationList'$errors);
  25.             throw new ServiceException($validationExceptionData);
  26.         }
  27.     }
  28. }