LocaleValidator.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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\Locales;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  15. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  16. /**
  17. * Validates whether a value is a valid locale code.
  18. *
  19. * @author Bernhard Schussek <bschussek@gmail.com>
  20. */
  21. class LocaleValidator extends ConstraintValidator
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function validate($value, Constraint $constraint)
  27. {
  28. if (!$constraint instanceof Locale) {
  29. throw new UnexpectedTypeException($constraint, Locale::class);
  30. }
  31. if (null === $value || '' === $value) {
  32. return;
  33. }
  34. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  35. throw new UnexpectedValueException($value, 'string');
  36. }
  37. $inputValue = (string) $value;
  38. $value = $inputValue;
  39. if ($constraint->canonicalize) {
  40. $value = \Locale::canonicalize($value);
  41. }
  42. if (!Locales::exists($value)) {
  43. $this->context->buildViolation($constraint->message)
  44. ->setParameter('{{ value }}', $this->formatValue($inputValue))
  45. ->setCode(Locale::NO_SUCH_LOCALE_ERROR)
  46. ->addViolation();
  47. }
  48. }
  49. }