Refactor entity normalization to handle Doctrine Collection.

Updated `normalizeDoctrineEntity` to support normalizing `Collection` objects and handle null values in arrays. This ensures compatibility with a broader range of entity structures and improves data integrity during normalization.
This commit is contained in:
Julien Fastré 2025-04-07 14:35:07 +02:00
parent 8331a836f2
commit 1c4ee37507
Signed by: julienfastre
GPG Key ID: BDE2190974723FCB

View File

@ -11,6 +11,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Export; namespace Chill\MainBundle\Export;
use Doctrine\Common\Collections\Collection;
use Doctrine\Persistence\ObjectRepository; use Doctrine\Persistence\ObjectRepository;
trait ExportDataNormalizerTrait trait ExportDataNormalizerTrait
@ -21,10 +22,13 @@ trait ExportDataNormalizerTrait
public function normalizeDoctrineEntity(object|array $entity): array|int public function normalizeDoctrineEntity(object|array $entity): array|int
{ {
if (is_array($entity)) { if (is_array($entity)) {
return array_values(array_map(static fn (object $entity) => $entity->getId(), $entity)); return array_values(array_filter(array_map(static fn (object $entity) => $entity->getId(), $entity), fn ($value) => null !== $value));
}
if ($entity instanceof Collection) {
return $this->normalizeDoctrineEntity($entity->toArray());
} }
return $entity->getId(); return $entity?->getId();
} }
public function denormalizeDoctrineEntity(array|int $id, ObjectRepository $repository): object|array public function denormalizeDoctrineEntity(array|int $id, ObjectRepository $repository): object|array