LanguageValidator.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace Symfony\Component\Validator\Constraints;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. use Symfony\Component\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Locale\Locale;
  15. /**
  16. * Validates whether a value is a valid language code
  17. *
  18. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  19. */
  20. class LanguageValidator extends ConstraintValidator
  21. {
  22. public function isValid($value, Constraint $constraint)
  23. {
  24. if ($value === null || $value === '') {
  25. return true;
  26. }
  27. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
  28. throw new UnexpectedTypeException($value, 'string');
  29. }
  30. $value = (string)$value;
  31. if (!in_array($value, Locale::getLanguages())) {
  32. $this->setMessage($constraint->message, array('{{ value }}' => $value));
  33. return false;
  34. }
  35. return true;
  36. }
  37. }