ApiResourcesValidatorSubscriber.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Symfony\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. */
  13. final class ApiResourcesValidatorSubscriber implements EventSubscriberInterface
  14. {
  15. public function __construct(private ValidatorInterface $validator)
  16. {
  17. }
  18. /**
  19. * ne se déclenche qu'après le post validate d'api platform.
  20. *
  21. * @return array<string, array<int, int|string>>
  22. */
  23. public static function getSubscribedEvents(): array
  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. *
  32. * @throws \Exception
  33. */
  34. public function validate(ViewEvent $event): void
  35. {
  36. $entity = $event->getControllerResult();
  37. if (!$entity instanceof ApiResourcesInterface) {
  38. return;
  39. }
  40. $violations = $this->validator->validate($entity);
  41. if (count($violations) !== 0) {
  42. $messages = [];
  43. // there are errors, now you can show them
  44. foreach ($violations as $violation) {
  45. $messages[] = $violation->getMessage();
  46. }
  47. throw new \Exception(join(',', $messages), 500);
  48. }
  49. }
  50. }