/
TypeValidator.php
96 lines (86 loc) · 3.14 KB
/
TypeValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class TypeValidator extends ConstraintValidator
{
private const VALIDATION_FUNCTIONS = [
'bool' => 'is_bool',
'boolean' => 'is_bool',
'int' => 'is_int',
'integer' => 'is_int',
'long' => 'is_int',
'float' => 'is_float',
'double' => 'is_float',
'real' => 'is_float',
'number' => 'is_int || is_float && !is_nan',
'finite-float' => 'is_float && is_finite',
'finite-number' => 'is_int || is_float && is_finite',
'numeric' => 'is_numeric',
'string' => 'is_string',
'scalar' => 'is_scalar',
'array' => 'is_array',
'list' => 'is_array && array_is_list',
'associative_array' => 'is_array && !array_is_list',
'iterable' => 'is_iterable',
'countable' => 'is_countable',
'callable' => 'is_callable',
'object' => 'is_object',
'resource' => 'is_resource',
'null' => 'is_null',
'alnum' => 'ctype_alnum',
'alpha' => 'ctype_alpha',
'cntrl' => 'ctype_cntrl',
'digit' => 'ctype_digit',
'graph' => 'ctype_graph',
'lower' => 'ctype_lower',
'print' => 'ctype_print',
'punct' => 'ctype_punct',
'space' => 'ctype_space',
'upper' => 'ctype_upper',
'xdigit' => 'ctype_xdigit',
];
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof Type) {
throw new UnexpectedTypeException($constraint, Type::class);
}
if (null === $value) {
return;
}
$types = (array) $constraint->type;
foreach ($types as $type) {
$type = strtolower($type);
if (isset(self::VALIDATION_FUNCTIONS[$type]) && match ($type) {
'finite-float' => \is_float($value) && is_finite($value),
'finite-number' => \is_int($value) || \is_float($value) && is_finite($value),
'number' => \is_int($value) || \is_float($value) && !is_nan($value),
'list' => \is_array($value) && array_is_list($value),
'associative_array' => \is_array($value) && !array_is_list($value),
default => self::VALIDATION_FUNCTIONS[$type]($value),
}) {
return;
}
if ($value instanceof $type) {
return;
}
}
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameter('{{ type }}', implode('|', $types))
->setCode(Type::INVALID_TYPE_ERROR)
->addViolation();
}
}