Drupal investigation

LocaleValidator.php 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 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, __NAMESPACE__.'\Locale');
  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. $locales = Intl::getLocaleBundle()->getLocaleNames();
  39. $aliases = Intl::getLocaleBundle()->getAliases();
  40. if (!isset($locales[$value]) && !in_array($value, $aliases)) {
  41. if ($this->context instanceof ExecutionContextInterface) {
  42. $this->context->buildViolation($constraint->message)
  43. ->setParameter('{{ value }}', $this->formatValue($value))
  44. ->setCode(Locale::NO_SUCH_LOCALE_ERROR)
  45. ->addViolation();
  46. } else {
  47. $this->buildViolation($constraint->message)
  48. ->setParameter('{{ value }}', $this->formatValue($value))
  49. ->setCode(Locale::NO_SUCH_LOCALE_ERROR)
  50. ->addViolation();
  51. }
  52. }
  53. }
  54. }