LocaleValidator.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. /**
  15. * Validates whether a value is a valid locale code
  16. *
  17. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  18. */
  19. class LocaleValidator extends ConstraintValidator
  20. {
  21. public function isValid($value, Constraint $constraint)
  22. {
  23. if (null === $value || '' === $value) {
  24. return true;
  25. }
  26. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
  27. throw new UnexpectedTypeException($value, 'string');
  28. }
  29. $value = (string) $value;
  30. if (!in_array($value, \Symfony\Component\Locale\Locale::getLocales())) {
  31. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  32. return false;
  33. }
  34. return true;
  35. }
  36. }