ModelsToArrayTransformer.php 2.7 KB

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