vendor/api-platform/core/src/Symfony/EventListener/ValidateListener.php line 44

  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Symfony\EventListener;
  12. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  13. use ApiPlatform\Util\OperationRequestInitiatorTrait;
  14. use ApiPlatform\Validator\Exception\ValidationException;
  15. use ApiPlatform\Validator\ValidatorInterface;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\HttpKernel\Event\ViewEvent;
  18. /**
  19.  * Validates data.
  20.  *
  21.  * @author Kévin Dunglas <dunglas@gmail.com>
  22.  */
  23. final class ValidateListener
  24. {
  25.     use OperationRequestInitiatorTrait;
  26.     public const OPERATION_ATTRIBUTE_KEY 'validate';
  27.     public function __construct(private readonly ValidatorInterface $validatorResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory)
  28.     {
  29.         $this->resourceMetadataCollectionFactory $resourceMetadataCollectionFactory;
  30.     }
  31.     /**
  32.      * Validates data returned by the controller if applicable.
  33.      *
  34.      * @throws ValidationException
  35.      */
  36.     public function onKernelView(ViewEvent $event): void
  37.     {
  38.         $controllerResult $event->getControllerResult();
  39.         $request $event->getRequest();
  40.         $operation $this->initializeOperation($request);
  41.         if (
  42.             $controllerResult instanceof Response
  43.             || $request->isMethodSafe()
  44.             || $request->isMethod('DELETE')
  45.         ) {
  46.             return;
  47.         }
  48.         if (!$operation || !($operation->canValidate() ?? true)) {
  49.             return;
  50.         }
  51.         $this->validator->validate($controllerResult$operation->getValidationContext() ?? []);
  52.     }
  53. }