1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Knp\DictionaryBundle\Validator\Constraints\DictionaryValidator; |
6
|
|
|
|
7
|
|
|
use Composer\InstalledVersions; |
8
|
|
|
use Exception; |
9
|
|
|
use Knp\DictionaryBundle\Validator\Constraints\Dictionary; |
10
|
|
|
use Symfony\Component\Form\Exception\UnexpectedTypeException; |
11
|
|
|
use Symfony\Component\Validator\Constraint; |
12
|
|
|
|
13
|
|
|
switch ($version = substr((string) InstalledVersions::getVersion('symfony/validator'), 0, 3)) { |
14
|
|
|
default: |
15
|
|
|
throw new Exception('knplabs/dictionary-bundle is not compatible with the current version of symfony/validator: '.$version); |
16
|
|
|
|
17
|
|
|
case '6.0': |
18
|
|
|
trait SymfonyCompatibilityTrait |
19
|
|
|
{ |
20
|
|
|
public function validate(mixed $value, Constraint $constraint): void |
21
|
|
|
{ |
22
|
|
|
if (!$constraint instanceof Dictionary) { |
23
|
|
|
throw new UnexpectedTypeException($constraint, Dictionary::class); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
if (null === $value || '' === $value) { |
27
|
|
|
return; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$dictionary = $this->dictionaries[$constraint->name]; |
31
|
|
|
$values = $dictionary->getKeys(); |
32
|
|
|
|
33
|
|
|
if (!\in_array($value, $values, true)) { |
34
|
|
|
$this->context->addViolation( |
35
|
|
|
$constraint->message, |
36
|
|
|
[ |
37
|
|
|
'{{ key }}' => $this->varToString($value), |
|
|
|
|
38
|
|
|
'{{ keys }}' => implode(', ', array_map([$this, 'varToString'], $values)), |
39
|
|
|
] |
40
|
|
|
); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
break; |
46
|
|
|
|
47
|
|
|
case '5.4': |
48
|
|
|
trait SymfonyCompatibilityTrait |
49
|
|
|
{ |
50
|
|
|
public function validate($value, Constraint $constraint): void |
51
|
|
|
{ |
52
|
|
|
if (!$constraint instanceof Dictionary) { |
53
|
|
|
throw new UnexpectedTypeException($constraint, Dictionary::class); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (null === $value || '' === $value) { |
57
|
|
|
return; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$dictionary = $this->dictionaries[$constraint->name]; |
61
|
|
|
$values = $dictionary->getKeys(); |
62
|
|
|
|
63
|
|
|
if (!\in_array($value, $values, true)) { |
64
|
|
|
$this->context->addViolation( |
65
|
|
|
$constraint->message, |
66
|
|
|
[ |
67
|
|
|
'{{ key }}' => $this->varToString($value), |
68
|
|
|
'{{ keys }}' => implode(', ', array_map([$this, 'varToString'], $values)), |
69
|
|
|
] |
70
|
|
|
); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
break; |
76
|
|
|
} |
77
|
|
|
|