class ClassResolverConstraintValidator

Validates if a method on a service or instantiated object returns true.

Hierarchy

Expanded class hierarchy of ClassResolverConstraintValidator

1 file declares its use of ClassResolverConstraintValidator
ClassResolverConstraintValidatorTest.php in core/tests/Drupal/KernelTests/Core/TypedData/ClassResolverConstraintValidatorTest.php

File

core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/ClassResolverConstraintValidator.php, line 17

Namespace

Drupal\Core\Validation\Plugin\Validation\Constraint
View source
class ClassResolverConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
  public function __construct(protected ClassResolver $classResolver) {
  }
  
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) : static {
    return new static($container->get('class_resolver'));
  }
  
  /**
   * {@inheritdoc}
   */
  public function validate(mixed $value, Constraint $constraint) : void {
    if (!$constraint instanceof ClassResolverConstraint) {
      throw new UnexpectedTypeException($constraint, ClassResolverConstraint::class);
    }
    $service = $this->classResolver
      ->getInstanceFromDefinition($constraint->classOrService);
    if (!method_exists($service, $constraint->method)) {
      throw new \InvalidArgumentException('The method "' . $constraint->method . '" does not exist on the service "' . $constraint->classOrService . '".');
    }
    $result = $service->{$constraint->method}($value);
    if ($result !== TRUE) {
      $this->context
        ->buildViolation($constraint->message)
        ->setParameter('@classOrService', $constraint->classOrService)
        ->setParameter('@method', $constraint->method)
        ->setParameter('@value', $value)
        ->addViolation();
    }
  }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title
ClassResolverConstraintValidator::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create
ClassResolverConstraintValidator::validate public function
ClassResolverConstraintValidator::__construct public function

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.