ApiResourcesValidatorSubscriber.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\ApiResources\ApiResourcesInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\ViewEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Validator\Validator\ValidatorInterface;
  10. /**
  11. * Class ApiResourcesValidatorSubscriber : EventSubscriber qui déploit le system de validator de symfony si la resource est une instance de ApiResources
  12. * @package App\EventSubscriber
  13. */
  14. final class ApiResourcesValidatorSubscriber implements EventSubscriberInterface
  15. {
  16. public function __construct(private ValidatorInterface $validator)
  17. {
  18. }
  19. /**
  20. * ne se déclenche qu'après le post validate d'api platform
  21. * @return array[]
  22. */
  23. public static function getSubscribedEvents()
  24. {
  25. return [
  26. KernelEvents::VIEW => ['validate', EventPriorities::POST_VALIDATE],
  27. ];
  28. }
  29. /**
  30. * Si l'entité est une instance de ApiResourcesInterface, alors on active le validator
  31. * @param ViewEvent $event
  32. * @throws \Exception
  33. */
  34. public function validate(ViewEvent $event): void
  35. {
  36. $entity = $event->getControllerResult();
  37. if(!$entity instanceof ApiResourcesInterface)
  38. return;
  39. $violations = $this->validator->validate($entity);
  40. if (0 !== count($violations)) {
  41. $messages = [];
  42. // there are errors, now you can show them
  43. foreach ($violations as $violation) {
  44. $messages[] = $violation->getMessage();
  45. }
  46. throw new \Exception(join(',', $messages), 500);
  47. }
  48. }
  49. }