| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?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.
- */
- 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.
- *
- * @throws \Exception
- */
- public function validate(ViewEvent $event): void
- {
- $entity = $event->getControllerResult();
- if (!$entity instanceof ApiResourcesInterface) {
- return;
- }
- $violations = $this->validator->validate($entity);
- if (count($violations) !== 0) {
- $messages = [];
- // there are errors, now you can show them
- foreach ($violations as $violation) {
- $messages[] = $violation->getMessage();
- }
- throw new \Exception(join(',', $messages), 500);
- }
- }
- }
|