You are here

class CountryConstraintValidator in Address 8

Validates the country constraint.

Hierarchy

Expanded class hierarchy of CountryConstraintValidator

1 file declares its use of CountryConstraintValidator
CountryConstraintValidatorTest.php in tests/src/Unit/Plugin/Validation/Constraint/CountryConstraintValidatorTest.php

File

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

Namespace

Drupal\address\Plugin\Validation\Constraint
View source
class CountryConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  /**
   * The country repository.
   *
   * @var \CommerceGuys\Addressing\Country\CountryRepositoryInterface
   */
  protected $countryRepository;

  /**
   * Constructs a new CountryConstraintValidator object.
   *
   * @param \CommerceGuys\Addressing\Country\CountryRepositoryInterface $country_repository
   *   The country repository.
   */
  public function __construct(CountryRepositoryInterface $country_repository) {
    $this->countryRepository = $country_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('address.country_repository'));
  }

  /**
   * {@inheritdoc}
   */
  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();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CountryConstraintValidator::$countryRepository protected property The country repository.
CountryConstraintValidator::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create
CountryConstraintValidator::validate public function Checks if the passed value is valid.
CountryConstraintValidator::__construct public function Constructs a new CountryConstraintValidator object.