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.

ProductToIdTransformer.php 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Lc\CaracoleBundle\Form\Product;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Lc\CaracoleBundle\Model\Product\ProductInterface;
  5. use Symfony\Component\Form\DataTransformerInterface;
  6. use Symfony\Component\Form\Exception\TransformationFailedException;
  7. class ProductToIdTransformer implements DataTransformerInterface
  8. {
  9. private EntityManagerInterface $entityManager;
  10. public function __construct(EntityManagerInterface $entityManager)
  11. {
  12. $this->entityManager = $entityManager;
  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->entityManager->getRepository(
  27. $this->entityManager->getEntityName(ProductInterface::class)
  28. )->find($productId);
  29. if (null === $product) {
  30. throw new TransformationFailedException(
  31. sprintf(
  32. 'An issue with number "%s" does not exist!',
  33. $productId
  34. )
  35. );
  36. }
  37. return $product;
  38. }
  39. }