ConstraintValidatorFactory.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace Drupal\Core\Validation;
  3. use Drupal\Core\DependencyInjection\ClassResolverInterface;
  4. use Symfony\Component\Validator\Constraint;
  5. use Symfony\Component\Validator\ConstraintValidatorFactory as BaseConstraintValidatorFactory;
  6. /**
  7. * Defines a constraint validator factory that works with container injection.
  8. *
  9. * @TODO Decide what to do with this class or how to reuse constraint
  10. * validators in https://drupal.org/project/drupal/issues/3097071
  11. */
  12. class ConstraintValidatorFactory extends BaseConstraintValidatorFactory {
  13. /**
  14. * Constructs a new ConstraintValidatorFactory.
  15. *
  16. * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
  17. */
  18. public function __construct(ClassResolverInterface $class_resolver) {
  19. $this->classResolver = $class_resolver;
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function getInstance(Constraint $constraint) {
  25. $class_name = $constraint->validatedBy();
  26. // Constraint validator instances should always be initialized newly and
  27. // never shared, because the current validation context is getting injected
  28. // into them through setter injection and in a case of a recursive
  29. // validation where a validator triggers a validation chain leading to the
  30. // same validator the context of the first call would be exchanged with the
  31. // one of the subsequent validation chain.
  32. return $this->classResolver->getInstanceFromDefinition($class_name);
  33. }
  34. }