3 namespace Drupal\Core\Validation\Plugin\Validation\Constraint;
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\Core\Session\AccountInterface;
7 use Drupal\Core\TypedData\OptionsProviderInterface;
8 use Drupal\Core\TypedData\ComplexDataInterface;
9 use Drupal\Core\TypedData\Validation\TypedDataAwareValidatorTrait;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
11 use Symfony\Component\Validator\Constraint;
12 use Symfony\Component\Validator\Constraints\ChoiceValidator;
15 * Validates the AllowedValues constraint.
17 class AllowedValuesConstraintValidator extends ChoiceValidator implements ContainerInjectionInterface {
19 use TypedDataAwareValidatorTrait;
24 * @var \Drupal\Core\Session\AccountInterface
26 protected $currentUser;
31 public static function create(ContainerInterface $container) {
32 return new static($container->get('current_user'));
36 * Constructs a new AllowedValuesConstraintValidator.
38 * @param \Drupal\Core\Session\AccountInterface $current_user
41 public function __construct(AccountInterface $current_user) {
42 $this->currentUser = $current_user;
48 public function validate($value, Constraint $constraint) {
49 $typed_data = $this->getTypedData();
50 if ($typed_data instanceof OptionsProviderInterface) {
51 $allowed_values = $typed_data->getSettableValues($this->currentUser);
52 $constraint->choices = $allowed_values;
54 // If the data is complex, we have to validate its main property.
55 if ($typed_data instanceof ComplexDataInterface) {
56 $name = $typed_data->getDataDefinition()->getMainPropertyName();
58 throw new \LogicException('Cannot validate allowed values for complex data without a main property.');
60 $value = $typed_data->get($name)->getValue();
64 // The parent implementation ignores values that are not set, but makes
65 // sure some choices are available firstly. However, we want to support
66 // empty choices for undefined values; for instance, if a term reference
67 // field points to an empty vocabulary.
72 parent::validate($value, $constraint);