39 lines
941 B
PHP
39 lines
941 B
PHP
<?php
|
|
|
|
namespace App\Form\DataTransformer;
|
|
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
use Symfony\Component\Form\DataTransformerInterface;
|
|
use Symfony\Component\Form\Exception\TransformationFailedException;
|
|
|
|
class EntityToIdTransformer implements DataTransformerInterface
|
|
{
|
|
public function __construct(private readonly EntityManagerInterface $entityManager, private readonly string $class)
|
|
{
|
|
}
|
|
|
|
public function transform($value)
|
|
{
|
|
if (null === $value) {
|
|
return null;
|
|
}
|
|
|
|
return $value->getId();
|
|
}
|
|
|
|
public function reverseTransform($value)
|
|
{
|
|
if (empty($value)) {
|
|
return null;
|
|
}
|
|
|
|
$entity = $this->entityManager->getRepository($this->class)->find($value);
|
|
|
|
if (null === $entity) {
|
|
throw new TransformationFailedException(sprintf('No %s with id %d found', $this->class, $value));
|
|
}
|
|
|
|
return $entity;
|
|
}
|
|
}
|