-
-
Save craigmarvelley/4755684 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Dpn\ToolsBundle\Form\DataTransformer; | |
use Symfony\Component\Form\DataTransformerInterface; | |
use Symfony\Component\Form\Exception\TransformationFailedException; | |
use Doctrine\Common\Persistence\ObjectManager; | |
class EntityToIdTransformer implements DataTransformerInterface | |
{ | |
/** | |
* @var ObjectManager | |
*/ | |
protected $objectManager; | |
/** | |
* @var string | |
*/ | |
protected $class; | |
public function __construct(ObjectManager $objectManager, $class) | |
{ | |
$this->objectManager = $objectManager; | |
$this->class = $class; | |
} | |
public function transform($entity) | |
{ | |
if (null === $entity) { | |
return; | |
} | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment