|
11 | 11 |
|
12 | 12 | namespace Symfony\Component\Validator\Constraints;
|
13 | 13 |
|
| 14 | +use Symfony\Component\PropertyAccess\PropertyAccess; |
| 15 | +use Symfony\Component\PropertyAccess\PropertyAccessorInterface; |
14 | 16 | use Symfony\Component\Validator\Constraint;
|
15 | 17 | use Symfony\Component\Validator\ConstraintValidator;
|
16 | 18 | use Symfony\Component\Validator\Exception\UnexpectedTypeException;
|
|
21 | 23 | */
|
22 | 24 | class UniqueValidator extends ConstraintValidator
|
23 | 25 | {
|
| 26 | + private ?PropertyAccessorInterface $propertyAccessor; |
| 27 | + |
| 28 | + public function __construct(PropertyAccessorInterface $propertyAccessor = null) |
| 29 | + { |
| 30 | + $this->propertyAccessor = $propertyAccessor; |
| 31 | + } |
| 32 | + |
24 | 33 | /**
|
25 | 34 | * {@inheritdoc}
|
26 | 35 | */
|
@@ -72,18 +81,34 @@ private function getNormalizer(Unique $unique): callable
|
72 | 81 | return $unique->normalizer;
|
73 | 82 | }
|
74 | 83 |
|
75 |
| - private function reduceElementKeys(array $fields, array $element): array |
| 84 | + private function reduceElementKeys(array $fields, array|object $element): array |
76 | 85 | {
|
77 | 86 | $output = [];
|
78 | 87 | foreach ($fields as $field) {
|
79 | 88 | if (!\is_string($field)) {
|
80 | 89 | throw new UnexpectedTypeException($field, 'string');
|
81 | 90 | }
|
82 |
| - if (isset($element[$field])) { |
83 |
| - $output[$field] = $element[$field]; |
| 91 | + |
| 92 | + // For no BC, because PropertyAccessor require brackets for array keys |
| 93 | + // Previous implementation, only check in array |
| 94 | + if (\is_array($element) && !str_contains($field, '[')) { |
| 95 | + $field = "[{$field}]"; |
| 96 | + } |
| 97 | + |
| 98 | + if (null !== $value = $this->getPropertyAccessor()->getValue($element, $field)) { |
| 99 | + $output[$field] = $value; |
84 | 100 | }
|
85 | 101 | }
|
86 | 102 |
|
87 | 103 | return $output;
|
88 | 104 | }
|
| 105 | + |
| 106 | + private function getPropertyAccessor(): PropertyAccessorInterface |
| 107 | + { |
| 108 | + if (null === $this->propertyAccessor) { |
| 109 | + $this->propertyAccessor = PropertyAccess::createPropertyAccessor(); |
| 110 | + } |
| 111 | + |
| 112 | + return $this->propertyAccessor; |
| 113 | + } |
89 | 114 | }
|
0 commit comments