You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.3KB

  1. <?php
  2. namespace Lc\ShopBundle\Form\DataTransformer;
  3. use Lc\ShopBundle\Context\ProductInterface;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\Form\DataTransformerInterface;
  6. use Symfony\Component\Form\Exception\TransformationFailedException;
  7. class ProductToIdTransformer implements DataTransformerInterface
  8. {
  9. private $em ;
  10. public function __construct(EntityManagerInterface $em)
  11. {
  12. $this->em = $em;
  13. }
  14. public function transform($product)
  15. {
  16. if (null === $product) {
  17. return '';
  18. }
  19. return $product->getId();
  20. }
  21. public function reverseTransform($productId)
  22. {
  23. if (!$productId) {
  24. return;
  25. }
  26. $product = $this->em->getRepository($this->em->getClassMetadata(ProductInterface::class)->getName())->find($productId);
  27. if (null === $product) {
  28. throw new TransformationFailedException(sprintf(
  29. 'An issue with number "%s" does not exist!',
  30. $productId
  31. ));
  32. }
  33. return $product;
  34. }
  35. }