vendor/api-platform/core/src/Bridge/Symfony/Validator/Validator.php line 67

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\Bridge\Symfony\Validator;
  12. use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
  13. use ApiPlatform\Core\Validator\ValidatorInterface;
  14. use Psr\Container\ContainerInterface;
  15. use Symfony\Component\Validator\Constraints\GroupSequence;
  16. use Symfony\Component\Validator\Validator\ValidatorInterface as SymfonyValidatorInterface;
  17. /**
  18.  * Validates an item using the Symfony validator component.
  19.  *
  20.  * @author Kévin Dunglas <dunglas@gmail.com>
  21.  *
  22.  * @final
  23.  */
  24. class Validator implements ValidatorInterface
  25. {
  26.     private $validator;
  27.     private $container;
  28.     public function __construct(SymfonyValidatorInterface $validator, ContainerInterface $container = null)
  29.     {
  30.         $this->validator = $validator;
  31.         $this->container = $container;
  32.     }
  33.     /**
  34.      * {@inheritdoc}
  35.      */
  36.     public function validate($data, array $context = [])
  37.     {
  38.         if (null !== $validationGroups = $context['groups'] ?? null) {
  39.             if (
  40.                 $this->container &&
  41.                 \is_string($validationGroups) &&
  42.                 $this->container->has($validationGroups) &&
  43.                 ($service = $this->container->get($validationGroups)) &&
  44.                 \is_callable($service)
  45.             ) {
  46.                 if (!$service instanceof ValidationGroupsGeneratorInterface) {
  47.                     @trigger_error(sprintf('Using a public validation groups generator service not implementing "%s" is deprecated since 2.6 and will be removed in 3.0.', ValidationGroupsGeneratorInterface::class), \E_USER_DEPRECATED);
  48.                 }
  49.                 $validationGroups = $service($data);
  50.             } elseif (\is_callable($validationGroups)) {
  51.                 $validationGroups = $validationGroups($data);
  52.             }
  53.             if (!$validationGroups instanceof GroupSequence) {
  54.                 $validationGroups = (array) $validationGroups;
  55.             }
  56.         }
  57.         $violations = $this->validator->validate($data, null, $validationGroups);
  58.         if (0 !== \count($violations)) {
  59.             throw new ValidationException($violations);
  60.         }
  61.     }
  62. }