ModelsToArrayTransformer.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 Sonata\AdminBundle\Form\DataTransformer;
  11. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  12. use Symfony\Component\Form\Exception\TransformationFailedException;
  13. use Symfony\Component\Form\DataTransformerInterface;
  14. use Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList;
  15. class ModelsToArrayTransformer implements DataTransformerInterface
  16. {
  17. protected $choiceList;
  18. /**
  19. * @param \Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList $choiceList
  20. */
  21. public function __construct(ModelChoiceList $choiceList)
  22. {
  23. $this->choiceList = $choiceList;
  24. }
  25. /**
  26. * {@inheritDoc}
  27. */
  28. public function transform($collection)
  29. {
  30. if (null === $collection) {
  31. return array();
  32. }
  33. $array = array();
  34. if (count($this->choiceList->getIdentifier()) > 1) {
  35. // load all choices
  36. $availableEntities = $this->choiceList->getEntities();
  37. foreach ($collection as $entity) {
  38. // identify choices by their collection key
  39. $key = array_search($entity, $availableEntities);
  40. $array[] = $key;
  41. }
  42. } else {
  43. foreach ($collection as $entity) {
  44. $array[] = current($this->choiceList->getIdentifierValues($entity));
  45. }
  46. }
  47. return $array;
  48. }
  49. /**
  50. * {@inheritDoc}
  51. */
  52. public function reverseTransform($keys)
  53. {
  54. $collection = $this->choiceList->getModelManager()->getModelCollectionInstance(
  55. $this->choiceList->getClass()
  56. );
  57. if (!$collection instanceof \ArrayAccess) {
  58. throw new UnexpectedTypeException($collection, '\ArrayAccess');
  59. }
  60. if ('' === $keys || null === $keys) {
  61. return $collection;
  62. }
  63. if (!is_array($keys)) {
  64. throw new UnexpectedTypeException($keys, 'array');
  65. }
  66. $notFound = array();
  67. // optimize this into a SELECT WHERE IN query
  68. foreach ($keys as $key) {
  69. if ($entity = $this->choiceList->getEntity($key)) {
  70. $collection[] = $entity;
  71. } else {
  72. $notFound[] = $key;
  73. }
  74. }
  75. if (count($notFound) > 0) {
  76. throw new TransformationFailedException(sprintf('The entities with keys "%s" could not be found', implode('", "', $notFound)));
  77. }
  78. return $collection;
  79. }
  80. }