chill-bundles/src/Bundle/ChillMainBundle/Export/ExportDataNormalizerTrait.php
Julien Fastré 8c5abbff74
Update type handling in entity normalization methods
Extended support for `string` types in `normalizeDoctrineEntity` and `denormalizeDoctrineEntity` methods. This ensures compatibility with a broader range of identifier formats and improves flexibility in entity processing.
2025-04-08 15:49:55 +02:00

73 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Export;
use Doctrine\Common\Collections\Collection;
use Doctrine\Persistence\ObjectRepository;
trait ExportDataNormalizerTrait
{
/**
* @param object|list<object> $entity
*/
public function normalizeDoctrineEntity(object|array|null $entity): array|int|string
{
if (is_array($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();
}
public function denormalizeDoctrineEntity(array|int|string $id, ObjectRepository $repository): object|array
{
if (is_array($id)) {
return $repository->findBy(['id' => $id]);
}
if (null === $object = $repository->find($id)) {
throw new \UnexpectedValueException(sprintf('Object with id "%s" does not exist.', $id));
}
return $object;
}
public function normalizeDate(\DateTimeImmutable|\DateTime $date): string
{
return sprintf(
'%s,%s',
$date instanceof \DateTimeImmutable ? 'imm1' : 'mut1',
$date->format('d-m-Y-H:i:s.u e'),
);
}
public function denormalizeDate(string $date): \DateTimeImmutable|\DateTime
{
$format = 'd-m-Y-H:i:s.u e';
$denormalized = match (substr($date, 0, 4)) {
'imm1' => \DateTimeImmutable::createFromFormat($format, substr($date, 5)),
'mut1' => \DateTime::createFromFormat($format, substr($date, 5)),
default => throw new \UnexpectedValueException(sprintf('Unexpected format for the kind selector: %s', substr($date, 0, 4))),
};
if (false === $denormalized) {
throw new \UnexpectedValueException(sprintf('Unexpected date format: %s', substr($date, 5)));
}
return $denormalized;
}
}