EntityToIdTransformer.php 1.72 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
<?php

namespace App\Form;

use App\Entity\Siege;
use Doctrine\ORM\EntityManagerInterface;
use Ramsey\Uuid\Lazy\LazyUuidFromString;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class EntityToIdTransformer implements DataTransformerInterface
{
    /**
     * @var EntityManagerInterface
     */
    protected $objectManager;

    /**
     * @var string
     */
    protected $class;

    public function __construct(EntityManagerInterface $objectManager, $class)
    {
        $this->objectManager = $objectManager;
        $this->class = $class;
    }

    public function transform($entity)
    {
        if (1 === $entity && Siege::class == $this->class) {
            return $this->objectManager
                ->getRepository($this->class)
                ->getTheOne();
        }
        if (null === $entity) {
            return;
        }
        if (!is_object($entity)) {
            $entityO = $this->objectManager
                            ->getRepository($this->class)
                            ->find($entity);
            if (null === $entityO) {
                throw new TransformationFailedException();
            }

            return $entityO;
        }
        if ($entity instanceof LazyUuidFromString) {
            return $entity->toString();
        }

        return $entity->getId();
    }

    public function reverseTransform($id)
    {
        if (!$id) {
            return null;
        }
        $entity = $this->objectManager
                       ->getRepository($this->class)
                       ->find($id);
        if (null === $entity) {
            throw new TransformationFailedException();
        }

        return $entity;
    }
}