<?php
/**
 * Entity To Id transformer
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\TagManagerBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * Entity To Id transformer
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class EntityToIdTransformer implements DataTransformerInterface
{
    /**
     * Doctrine Object Manager
     * @var ObjectManager
     */
    protected $objectManager;

    /**
     * Class to transform to/from
     * @var string
     */
    protected $class;

    /**
     * Constructor
     * 
     * @param ObjectManager $objectManager Doctrine Object Manager
     * @param string        $class         Class to transform to/from
     */
    public function __construct(ObjectManager $objectManager, $class)
    {
        $this->objectManager = $objectManager;
        $this->class = $class;
    }

    /**
     * Transform from Entity to int

     * @param object $entity Entity
     *
     * @return int Id
     */
    public function transform($entity)
    {
        if (null === $entity) { return; }
        return $entity->getId();
    }

    /**
     * Transform from int to Entity

     * @param int $id Id
     *
     * @return object Entity
     */
    public function reverseTransform($id)
    {
        if (!$id) { return null; }

        $entity = $this->objectManager
            ->getRepository($this->class)
            ->find($id);

        if (null === $entity) {
            throw new TransformationFailedException();
        }

        return $entity;
    }
}