diff --git a/core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/CountryConstraint.php b/core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/CountryConstraint.php new file mode 100644 index 0000000..11f1455 --- /dev/null +++ b/core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/CountryConstraint.php @@ -0,0 +1,24 @@ +countryManager = $country_manager; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static($container->get('country_manager')); + } + + /** + * {@inheritdoc} + */ + public function validate($value, Constraint $constraint) { + if ($value === null || $value === '') { + return; + } + + if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) { + throw new UnexpectedTypeException($value, 'string'); + } + + $countries = $this->countryManager->getList(); + $value = (string) $value; + + if (!isset($countries[$value])) { + $this->context->addViolation($constraint->message); + } + } + +} diff --git a/core/tests/Drupal/Tests/Core/Validation/Plugin/Validation/Constraint/CountryConstraintValidatorTest.php b/core/tests/Drupal/Tests/Core/Validation/Plugin/Validation/Constraint/CountryConstraintValidatorTest.php new file mode 100644 index 0000000..273171a --- /dev/null +++ b/core/tests/Drupal/Tests/Core/Validation/Plugin/Validation/Constraint/CountryConstraintValidatorTest.php @@ -0,0 +1,59 @@ +getMock('Drupal\Core\Locale\CountryManagerInterface'); + $country_manager->expects($this->any()) + ->method('getList') + ->willReturn(['FR' => 'France', 'RS' => 'Serbia']); + $context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface'); + if ($valid) { + $context->expects($this->never()) + ->method('addViolation'); + } + else { + $context->expects($this->once()) + ->method('addViolation'); + } + + $constraint = new CountryConstraint(); + $validate = new CountryConstraintValidator($country_manager); + $validate->initialize($context); + $validate->validate($value, $constraint); + } + + public function provideTestValidate() { + return [ + [NULL, TRUE], + ['', TRUE], + ['FR', TRUE], + ['RS', TRUE], + ['INVALID', FALSE], + ]; + + return $data; + } + +}