You are here

public function AllowedValuesConstraintValidator::validate in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/AllowedValuesConstraintValidator.php \Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraintValidator::validate()

Checks if the passed value is valid.

Parameters

mixed $value The value that should be validated:

Constraint $constraint The constraint for the validation:

Overrides ChoiceValidator::validate

File

core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/AllowedValuesConstraintValidator.php, line 53
Contains \Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraintValidator.

Class

AllowedValuesConstraintValidator
Validates the AllowedValues constraint.

Namespace

Drupal\Core\Validation\Plugin\Validation\Constraint

Code

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 the data is complex, we have to validate its main property.
    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.');
      }
      $value = $typed_data
        ->get($name)
        ->getValue();
    }
  }

  // The parent implementation ignores values that are not set, but makes
  // sure some choices are available firstly. However, we want to support
  // empty choices for undefined values, e.g. if a term reference field
  // points to an empty vocabulary.
  if (!isset($value)) {
    return;
  }
  parent::validate($value, $constraint);
}