Drupal investigation

CountryValidator.php 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\Intl\Intl;
  12. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  13. use Symfony\Component\Validator\Constraint;
  14. use Symfony\Component\Validator\ConstraintValidator;
  15. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  16. /**
  17. * Validates whether a value is a valid country code.
  18. *
  19. * @author Bernhard Schussek <bschussek@gmail.com>
  20. */
  21. class CountryValidator extends ConstraintValidator
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function validate($value, Constraint $constraint)
  27. {
  28. if (!$constraint instanceof Country) {
  29. throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Country');
  30. }
  31. if (null === $value || '' === $value) {
  32. return;
  33. }
  34. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
  35. throw new UnexpectedTypeException($value, 'string');
  36. }
  37. $value = (string) $value;
  38. $countries = Intl::getRegionBundle()->getCountryNames();
  39. if (!isset($countries[$value])) {
  40. if ($this->context instanceof ExecutionContextInterface) {
  41. $this->context->buildViolation($constraint->message)
  42. ->setParameter('{{ value }}', $this->formatValue($value))
  43. ->setCode(Country::NO_SUCH_COUNTRY_ERROR)
  44. ->addViolation();
  45. } else {
  46. $this->buildViolation($constraint->message)
  47. ->setParameter('{{ value }}', $this->formatValue($value))
  48. ->setCode(Country::NO_SUCH_COUNTRY_ERROR)
  49. ->addViolation();
  50. }
  51. }
  52. }
  53. }