Version 1
[yaffs-website] / vendor / symfony / validator / Constraints / TypeValidator.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\Validator\Context\ExecutionContextInterface;
15 use Symfony\Component\Validator\Constraint;
16 use Symfony\Component\Validator\ConstraintValidator;
17 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
18
19 /**
20  * @author Bernhard Schussek <bschussek@gmail.com>
21  */
22 class TypeValidator extends ConstraintValidator
23 {
24     /**
25      * {@inheritdoc}
26      */
27     public function validate($value, Constraint $constraint)
28     {
29         if (!$constraint instanceof Type) {
30             throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Type');
31         }
32
33         if (null === $value) {
34             return;
35         }
36
37         $type = strtolower($constraint->type);
38         $type = $type == 'boolean' ? 'bool' : $constraint->type;
39         $isFunction = 'is_'.$type;
40         $ctypeFunction = 'ctype_'.$type;
41
42         if (function_exists($isFunction) && $isFunction($value)) {
43             return;
44         } elseif (function_exists($ctypeFunction) && $ctypeFunction($value)) {
45             return;
46         } elseif ($value instanceof $constraint->type) {
47             return;
48         }
49
50         if ($this->context instanceof ExecutionContextInterface) {
51             $this->context->buildViolation($constraint->message)
52                 ->setParameter('{{ value }}', $this->formatValue($value))
53                 ->setParameter('{{ type }}', $constraint->type)
54                 ->setCode(Type::INVALID_TYPE_ERROR)
55                 ->addViolation();
56         } else {
57             $this->buildViolation($constraint->message)
58                 ->setParameter('{{ value }}', $this->formatValue($value))
59                 ->setParameter('{{ type }}', $constraint->type)
60                 ->setCode(Type::INVALID_TYPE_ERROR)
61                 ->addViolation();
62         }
63     }
64 }