CollectionToArrayTransformer.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Doctrine\Form\DataTransformer;
  11. use Doctrine\Common\Collections\ArrayCollection;
  12. use Doctrine\Common\Collections\Collection;
  13. use Symfony\Component\Form\DataTransformerInterface;
  14. use Symfony\Component\Form\Exception\TransformationFailedException;
  15. /**
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class CollectionToArrayTransformer implements DataTransformerInterface
  19. {
  20. /**
  21. * Transforms a collection into an array.
  22. *
  23. * @return mixed An array of entities
  24. *
  25. * @throws TransformationFailedException
  26. */
  27. public function transform($collection)
  28. {
  29. if (null === $collection) {
  30. return [];
  31. }
  32. // For cases when the collection getter returns $collection->toArray()
  33. // in order to prevent modifications of the returned collection
  34. if (\is_array($collection)) {
  35. return $collection;
  36. }
  37. if (!$collection instanceof Collection) {
  38. throw new TransformationFailedException('Expected a Doctrine\Common\Collections\Collection object.');
  39. }
  40. return $collection->toArray();
  41. }
  42. /**
  43. * Transforms choice keys into entities.
  44. *
  45. * @param mixed $array An array of entities
  46. *
  47. * @return Collection A collection of entities
  48. */
  49. public function reverseTransform($array)
  50. {
  51. if ('' === $array || null === $array) {
  52. $array = [];
  53. } else {
  54. $array = (array) $array;
  55. }
  56. return new ArrayCollection($array);
  57. }
  58. }