EntityToIdTransformer.php 1.37 KB
Newer Older
Julien Jorry committed
1 2 3 4
<?php

namespace App\Form;

5
use Doctrine\ORM\EntityManagerInterface;
Julien Jorry committed
6 7 8 9 10 11
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class EntityToIdTransformer implements DataTransformerInterface
{
    /**
12
     * @var EntityManagerInterface
Julien Jorry committed
13 14 15 16 17 18 19 20
     */
    protected $objectManager;

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

21
    public function __construct(EntityManagerInterface $objectManager, $class)
Julien Jorry committed
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
    {
        $this->objectManager = $objectManager;
        $this->class = $class;
    }

    public function transform($entity)
    {
        if (null === $entity) {
            return;
        }
        if (!is_object($entity)) {
            $entityO = $this->objectManager
                            ->getRepository($this->class)
                            ->find($entity);
            if (null === $entityO) {
                throw new TransformationFailedException();
            }
            return $entityO;
        }
        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;
    }
}