4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Intl\Intl;
15 use Symfony\Component\Validator\Constraint;
16 use Symfony\Component\Validator\ConstraintValidator;
17 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
20 * Validates whether a value is a valid language code.
22 * @author Bernhard Schussek <bschussek@gmail.com>
24 class LanguageValidator extends ConstraintValidator
29 public function validate($value, Constraint $constraint)
31 if (!$constraint instanceof Language) {
32 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Language');
35 if (null === $value || '' === $value) {
39 if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
40 throw new UnexpectedTypeException($value, 'string');
43 $value = (string) $value;
44 $languages = Intl::getLanguageBundle()->getLanguageNames();
46 if (!isset($languages[$value])) {
47 $this->context->buildViolation($constraint->message)
48 ->setParameter('{{ value }}', $this->formatValue($value))
49 ->setCode(Language::NO_SUCH_LANGUAGE_ERROR)