You are here

public function CountryConstraintValidator::validate in Address 8

File

src/Plugin/Validation/Constraint/CountryConstraintValidator.php, line 43

Class

CountryConstraintValidator
Validates the country constraint.

Namespace

Drupal\address\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {
  $country_code = $value;
  if ($country_code === NULL || $country_code === '') {
    return;
  }
  $countries = $this->countryRepository
    ->getList();
  if (!isset($countries[$country_code])) {
    $this->context
      ->buildViolation($constraint->invalidMessage)
      ->setParameter('%value', $this
      ->formatValue($country_code))
      ->addViolation();
    return;
  }
  $available_countries = $constraint->availableCountries;
  if (!empty($available_countries) && !in_array($country_code, $available_countries)) {
    $this->context
      ->buildViolation($constraint->notAvailableMessage)
      ->setParameter('%value', $this
      ->formatValue($country_code))
      ->addViolation();
  }
}