You are here

public function AllowedValuesConstraintValidator::validate in Select (or other) 8

Same name and namespace in other branches
  1. 4.x src/Plugin/Validation/AllowedValuesConstraintValidator.php \Drupal\select_or_other\Plugin\Validation\AllowedValuesConstraintValidator::validate()

File

src/Plugin/Validation/AllowedValuesConstraintValidator.php, line 53

Class

AllowedValuesConstraintValidator
Validates the AllowedValues constraint.

Namespace

Drupal\select_or_other\Plugin\Validation

Code

public function validate($value, Constraint $constraint) {
  $typed_data = $this
    ->getTypedData();
  if ($this
    ->mustBeValidatedByCore($typed_data)) {
    $this
      ->validateUsingCoreValidation($value, $constraint);
  }
  else {
    $constraint->choices = array_keys($this
      ->getValidChoices($typed_data));
    $value = $this
      ->getMainPropertyValue($typed_data);

    // Force the choices to be the same type as the value.
    $type = gettype($value);
    foreach ($constraint->choices as &$choice) {
      settype($choice, $type);
    }
    if (isset($value)) {
      if (!in_array($value, $constraint->choices)) {
        $constraint->choices[] = $value;
      }
      parent::validate($value, $constraint);
    }
  }
}