vendor/api-platform/core/src/Validator/EventListener/ValidateListener.php line 49

Open in your IDE?
  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\Core\Validator\EventListener;
  12. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  13. use ApiPlatform\Core\Metadata\Resource\ToggleableOperationAttributeTrait;
  14. use ApiPlatform\Core\Util\RequestAttributesExtractor;
  15. use ApiPlatform\Core\Validator\Exception\ValidationException;
  16. use ApiPlatform\Core\Validator\ValidatorInterface;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpKernel\Event\ViewEvent;
  19. /**
  20.  * Validates data.
  21.  *
  22.  * @author Kévin Dunglas <dunglas@gmail.com>
  23.  */
  24. final class ValidateListener
  25. {
  26.     use ToggleableOperationAttributeTrait;
  27.     public const OPERATION_ATTRIBUTE_KEY 'validate';
  28.     private $validator;
  29.     private $resourceMetadataFactory;
  30.     public function __construct(ValidatorInterface $validatorResourceMetadataFactoryInterface $resourceMetadataFactory)
  31.     {
  32.         $this->validator $validator;
  33.         $this->resourceMetadataFactory $resourceMetadataFactory;
  34.     }
  35.     /**
  36.      * Validates data returned by the controller if applicable.
  37.      *
  38.      * @throws ValidationException
  39.      */
  40.     public function onKernelView(ViewEvent $event): void
  41.     {
  42.         $controllerResult $event->getControllerResult();
  43.         $request $event->getRequest();
  44.         if (
  45.             $controllerResult instanceof Response
  46.             || $request->isMethodSafe()
  47.             || $request->isMethod('DELETE')
  48.             || !($attributes RequestAttributesExtractor::extractAttributes($request))
  49.             || !$attributes['receive']
  50.             || $this->isOperationAttributeDisabled($attributesself::OPERATION_ATTRIBUTE_KEY)
  51.         ) {
  52.             return;
  53.         }
  54.         $resourceMetadata $this->resourceMetadataFactory->create($attributes['resource_class']);
  55.         $validationGroups $resourceMetadata->getOperationAttribute($attributes'validation_groups'nulltrue);
  56.         $this->validator->validate($controllerResult, ['groups' => $validationGroups]);
  57.     }
  58. }