Guest User

Untitled

a guest
Apr 1st, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. <?php
  2.  
  3. namespace AppBundle\Form\DataTransformer;
  4.  
  5. use AppBundle\Entity\Entity;
  6. use AppBundle\Entity\EntityRepository;
  7. use Symfony\Component\Form\DataTransformerInterface;
  8. use Symfony\Component\Form\Exception\TransformationFailedException;
  9.  
  10. class EntitiesToIdsDataTransformer implements DataTransformerInterface
  11. {
  12. /**
  13. * @var EntityRepository
  14. */
  15. private $entityRepository;
  16.  
  17. public function __construct(EntityRepository $entity)
  18. {
  19. $this->entityRepository = $entity;
  20. }
  21.  
  22. /**
  23. * @param array|\Traversable|null $value
  24. * @return array|string
  25. * @throws TransformationFailedException
  26. */
  27. public function transform($value)
  28. {
  29. if (null === $value) {
  30. // as the DataTransformerInterface suggests
  31. return '';
  32. }
  33.  
  34. if (!is_array($value) && !$value instanceof \Traversable) {
  35. throw new TransformationFailedException(sprintf(
  36. 'Array or Traversable expected, %s given',
  37. gettype($value)
  38. ));
  39. }
  40.  
  41. $ids = [];
  42.  
  43. foreach ($value as $entity) {
  44. if (!$entity instanceof Entity) {
  45. throw new TransformationFailedException(sprintf(
  46. '%s expected, %s given',
  47. Entity::class,
  48. gettype($entity)
  49. ));
  50. }
  51.  
  52. $ids[] = $entity->getId();
  53. }
  54.  
  55. return $ids;
  56. }
  57.  
  58. /**
  59. * @param array|null $value
  60. * @return \AppBundle\Entity\Entity[]|null
  61. * @throws TransformationFailedException
  62. */
  63. public function reverseTransform($value)
  64. {
  65. if (empty($value)) {
  66. // as the DataTransformerInterface suggests
  67. return null;
  68. }
  69.  
  70. if (!is_array($value)) {
  71. throw new TransformationFailedException(sprintf(
  72. 'Array expected, %s given',
  73. gettype($value)
  74. ));
  75. }
  76.  
  77. return $this->entityRepository->findByIds($value);
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment