40d63970e25a6ecb5f9ab5025f334b02d1283c85
[yaffs-website] / vendor / symfony / validator / Constraints / LocaleValidator.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Validator\Constraints;
13
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;
18
19 /**
20  * Validates whether a value is a valid locale code.
21  *
22  * @author Bernhard Schussek <bschussek@gmail.com>
23  */
24 class LocaleValidator extends ConstraintValidator
25 {
26     /**
27      * {@inheritdoc}
28      */
29     public function validate($value, Constraint $constraint)
30     {
31         if (!$constraint instanceof Locale) {
32             throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Locale');
33         }
34
35         if (null === $value || '' === $value) {
36             return;
37         }
38
39         if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
40             throw new UnexpectedTypeException($value, 'string');
41         }
42
43         $value = (string) $value;
44         $locales = Intl::getLocaleBundle()->getLocaleNames();
45         $aliases = Intl::getLocaleBundle()->getAliases();
46
47         if (!isset($locales[$value]) && !\in_array($value, $aliases)) {
48             $this->context->buildViolation($constraint->message)
49                 ->setParameter('{{ value }}', $this->formatValue($value))
50                 ->setCode(Locale::NO_SUCH_LOCALE_ERROR)
51                 ->addViolation();
52         }
53     }
54 }