AllowedValuesConstraintValidator.php in Drupal 9
File
core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/AllowedValuesConstraintValidator.php
View source
<?php
namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TypedData\OptionsProviderInterface;
use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\Core\TypedData\PrimitiveInterface;
use Drupal\Core\TypedData\Validation\TypedDataAwareValidatorTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\ChoiceValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
class AllowedValuesConstraintValidator extends ChoiceValidator implements ContainerInjectionInterface {
use TypedDataAwareValidatorTrait;
protected $currentUser;
public static function create(ContainerInterface $container) {
return new static($container
->get('current_user'));
}
public function __construct(AccountInterface $current_user) {
$this->currentUser = $current_user;
}
public function validate($value, Constraint $constraint) {
$typed_data = $this
->getTypedData();
if ($typed_data instanceof OptionsProviderInterface) {
$allowed_values = $typed_data
->getSettableValues($this->currentUser);
$constraint->choices = $allowed_values;
if ($typed_data instanceof ComplexDataInterface) {
$name = $typed_data
->getDataDefinition()
->getMainPropertyName();
if (!isset($name)) {
throw new \LogicException('Cannot validate allowed values for complex data without a main property.');
}
$typed_data = $typed_data
->get($name);
$value = $typed_data
->getValue();
}
}
if (!isset($value)) {
return;
}
if (!$typed_data instanceof PrimitiveInterface) {
throw new \LogicException('The data type must be a PrimitiveInterface at this point.');
}
$value = $typed_data
->getCastedValue();
if ($constraint->callback) {
if (!\is_callable($choices = [
$this->context
->getObject(),
$constraint->callback,
]) && !\is_callable($choices = [
$this->context
->getClassName(),
$constraint->callback,
]) && !\is_callable($choices = $constraint->callback)) {
throw new ConstraintDefinitionException('The AllowedValuesConstraint constraint expects a valid callback');
}
$allowed_values = \call_user_func($choices);
$constraint->choices = $allowed_values;
$constraint->callback = NULL;
}
$type = gettype($value);
foreach ($constraint->choices as &$choice) {
settype($choice, $type);
}
parent::validate($value, $constraint);
}
}