diff --git a/src/Symfony/Component/Validator/Constraints/UniqueValidator.php b/src/Symfony/Component/Validator/Constraints/UniqueValidator.php index 1e692fe682a21..b0eefd84cb82f 100644 --- a/src/Symfony/Component/Validator/Constraints/UniqueValidator.php +++ b/src/Symfony/Component/Validator/Constraints/UniqueValidator.php @@ -43,12 +43,12 @@ public function validate(mixed $value, Constraint $constraint) $collectionElements = []; $normalizer = $this->getNormalizer($constraint); foreach ($value as $element) { + $element = $normalizer($element); + if ($fields && !$element = $this->reduceElementKeys($fields, $element)) { continue; } - $element = $normalizer($element); - if (\in_array($element, $collectionElements, true)) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php index 35bde67d9bd3f..3c2dd9f21c98f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UniqueValidatorTest.php @@ -16,6 +16,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Symfony\Component\Validator\Exception\UnexpectedValueException; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; +use Symfony\Component\Validator\Tests\Dummy\DummyClassOne; class UniqueValidatorTest extends ConstraintValidatorTestCase { @@ -283,6 +284,36 @@ public static function getInvalidCollectionValues(): array ], ]; } + + public function testArrayOfObjectsUnique() + { + $array = [ + new DummyClassOne(), + new DummyClassOne(), + new DummyClassOne(), + ]; + + $array[0]->code = '1'; + $array[1]->code = '2'; + $array[2]->code = '3'; + + $this->validator->validate( + $array, + new Unique( + normalizer: [self::class, 'normalizeDummyClassOne'], + fields: 'code' + ) + ); + + $this->assertNoViolation(); + } + + public static function normalizeDummyClassOne(DummyClassOne $obj): array + { + return [ + 'code' => $obj->code, + ]; + } } class CallableClass