1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Knp\DictionaryBundle\Validator\Constraints; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use Knp\DictionaryBundle\Dictionary\Collection; |
9
|
|
|
use Symfony\Component\Form\Exception\UnexpectedTypeException; |
10
|
|
|
use Symfony\Component\Validator\Constraint; |
11
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
12
|
|
|
|
13
|
|
|
final class DictionaryValidator extends ConstraintValidator |
14
|
|
|
{ |
15
|
|
|
public function __construct(private Collection $dictionaries) {} |
16
|
|
|
|
17
|
|
|
public function validate(mixed $value, Constraint $constraint): void |
18
|
|
|
{ |
19
|
5 |
|
if (!$constraint instanceof Dictionary) { |
20
|
|
|
throw new UnexpectedTypeException($constraint, Dictionary::class); |
21
|
5 |
|
} |
22
|
5 |
|
|
23
|
|
|
if (null === $value || '' === $value) { |
24
|
4 |
|
return; |
25
|
|
|
} |
26
|
4 |
|
|
27
|
1 |
|
$dictionary = $this->dictionaries[$constraint->name]; |
28
|
|
|
$values = $dictionary->getKeys(); |
29
|
|
|
|
30
|
3 |
|
if (!\in_array($value, $values, true)) { |
31
|
|
|
$this->context->addViolation( |
32
|
|
|
$constraint->message, |
33
|
|
|
[ |
34
|
3 |
|
'{{ key }}' => $this->varToString($value), |
35
|
3 |
|
'{{ keys }}' => implode(', ', array_map([$this, 'varToString'], $values)), |
36
|
|
|
] |
37
|
3 |
|
); |
38
|
2 |
|
} |
39
|
2 |
|
} |
40
|
|
|
|
41
|
2 |
|
private function varToString(mixed $var): string |
42
|
2 |
|
{ |
43
|
2 |
|
if (null === $var) { |
44
|
2 |
|
return 'null'; |
45
|
2 |
|
} |
46
|
|
|
|
47
|
|
|
if (\is_string($var)) { |
48
|
|
|
return '"'.$var.'"'; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if (\is_bool($var)) { |
52
|
3 |
|
return $var ? 'true' : 'false'; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
if (\is_float($var)) { |
56
|
|
|
return 0.0 === $var |
|
|
|
|
57
|
2 |
|
? '0.0' |
58
|
|
|
: (string) $var; |
59
|
2 |
|
} |
60
|
1 |
|
|
61
|
|
|
if (\is_object($var) && method_exists($var, '__toString')) { |
62
|
|
|
return $var->__toString(); |
63
|
2 |
|
} |
64
|
2 |
|
|
65
|
|
|
if (settype($var, 'string')) { |
66
|
|
|
/** |
67
|
1 |
|
* @var string $var |
68
|
1 |
|
*/ |
69
|
|
|
return $var; |
70
|
|
|
} |
71
|
1 |
|
|
72
|
1 |
|
throw new Exception('Unable to transform var to string.'); |
73
|
1 |
|
} |
74
|
|
|
} |
75
|
|
|
|