|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bdf\Form\View; |
|
4
|
|
|
|
|
5
|
|
|
use Bdf\Form\Validator\ConstraintValueValidator; |
|
6
|
|
|
use Bdf\Form\Validator\ValueValidatorInterface; |
|
7
|
|
|
use Symfony\Component\Validator\Constraints\Count; |
|
8
|
|
|
use Symfony\Component\Validator\Constraints\Length; |
|
9
|
|
|
use Symfony\Component\Validator\Constraints\NotBlank; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Normalize symfony constraints to array |
|
13
|
|
|
* This normalization process permit to filter unserializable values, and disociate validation business and view rendering |
|
14
|
|
|
*/ |
|
15
|
|
|
final class ConstraintsNormalizer |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var array<class-string<\Symfony\Component\Validator\Constraint>, array<string, mixed>> |
|
|
|
|
|
|
19
|
|
|
*/ |
|
20
|
|
|
static private $constraints = [ |
|
21
|
|
|
NotBlank::class => [], |
|
22
|
|
|
Length::class => ['min' => null, 'max' => null], |
|
23
|
|
|
Count::class => ['min' => null, 'max' => null], |
|
24
|
|
|
]; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Process normalization |
|
28
|
|
|
* The return value consists of and array with constraint class as key, and associative array of constraints attributes as value |
|
29
|
|
|
* |
|
30
|
|
|
* @param ValueValidatorInterface $validator |
|
31
|
|
|
* |
|
32
|
|
|
* @return array |
|
33
|
|
|
* @see FieldViewInterface::constraints() |
|
34
|
|
|
*/ |
|
35
|
47 |
|
public static function normalize(ValueValidatorInterface $validator): array |
|
36
|
|
|
{ |
|
37
|
47 |
|
if (!$validator instanceof ConstraintValueValidator) { |
|
38
|
1 |
|
return []; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
47 |
|
$normalizedConstraints = []; |
|
42
|
|
|
|
|
43
|
47 |
|
foreach ($validator->constraints() as $constraint) { |
|
44
|
26 |
|
$className = get_class($constraint); |
|
45
|
|
|
|
|
46
|
26 |
|
if (isset(self::$constraints[$className])) { |
|
47
|
21 |
|
$normalizedConstraints[$className] = array_intersect_key((array) $constraint, self::$constraints[$className]); |
|
48
|
20 |
|
} elseif (($option = $constraint->getDefaultOption()) !== null) { |
|
|
|
|
|
|
49
|
20 |
|
$value = $constraint->{$option}; |
|
50
|
|
|
|
|
51
|
20 |
|
if (is_scalar($value)) { |
|
52
|
8 |
|
$normalizedConstraints[$className] = [$option => $value]; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
47 |
|
return $normalizedConstraints; |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|