. */ namespace App\Validator\Constraints; use App\Entity\Base\AbstractDBElement; use App\Validator\UniqueValidatableInterface; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Symfony\Component\Validator\Exception\UnexpectedValueException; class UniqueObjectCollectionValidator extends ConstraintValidator { public function validate(mixed $value, Constraint $constraint) { if (!$constraint instanceof UniqueObjectCollection) { throw new UnexpectedTypeException($constraint, UniqueObjectCollection::class); } $fields = (array) $constraint->fields; if (null === $value) { return; } if (!\is_array($value) && !$value instanceof \IteratorAggregate) { throw new UnexpectedValueException($value, 'array|IteratorAggregate'); } $collectionElements = []; $normalizer = $this->getNormalizer($constraint); foreach ($value as $key => $object) { if (!$object instanceof UniqueValidatableInterface) { throw new UnexpectedValueException($object, UniqueValidatableInterface::class); } //Convert the object to an array using the helper function $element = $object->getComparableFields(); if ($fields && !$element = $this->reduceElementKeys($fields, $element, $constraint)) { continue; } $element = $normalizer($element); if (\in_array($element, $collectionElements, true)) { $violation = $this->context->buildViolation($constraint->message); $violation->atPath('[' . $key . ']' . '.' . $constraint->fields[0]); $violation->setParameter('{{ value }}', $this->formatValue($value)) ->setCode(UniqueObjectCollection::IS_NOT_UNIQUE) ->addViolation(); return; } $collectionElements[] = $element; } } private function getNormalizer(UniqueObjectCollection $unique): callable { if (null === $unique->normalizer) { return static fn ($value) => $value; } return $unique->normalizer; } private function reduceElementKeys(array $fields, array $element, UniqueObjectCollection $constraint): array { $output = []; foreach ($fields as $field) { if (!\is_string($field)) { throw new UnexpectedTypeException($field, 'string'); } if (\array_key_exists($field, $element)) { //Ignore null values if specified if ($element[$field] === null && $constraint->allowNull) { continue; } $output[$field] = $element[$field]; } } return $output; } }