123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace Sonata\AdminBundle\Form\DataTransformer;
- use Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList;
- use Symfony\Component\Form\DataTransformerInterface;
- use Symfony\Component\Form\Exception\TransformationFailedException;
- use Symfony\Component\Form\Exception\UnexpectedTypeException;
- class LegacyModelsToArrayTransformer implements DataTransformerInterface
- {
-
- protected $choiceList;
-
- public function __construct(ModelChoiceList $choiceList)
- {
- if (interface_exists('Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface')) {
- @trigger_error(
- 'The '.__CLASS__.' class is deprecated since 3.11, to be removed in 4.0. '.
- 'Use Sonata\AdminBundle\Form\DataTransformer\ModelsToArrayTransformer instead.',
- E_USER_DEPRECATED
- );
- }
- $this->choiceList = $choiceList;
- }
-
- public function transform($collection)
- {
- if (null === $collection) {
- return array();
- }
- $array = array();
- if (count($this->choiceList->getIdentifier()) > 1) {
-
- $availableEntities = $this->choiceList->getEntities();
- foreach ($collection as $entity) {
-
- $key = array_search($entity, $availableEntities);
- $array[] = $key;
- }
- } else {
- foreach ($collection as $entity) {
- $array[] = current($this->choiceList->getIdentifierValues($entity));
- }
- }
- return $array;
- }
-
- public function reverseTransform($keys)
- {
- $collection = $this->choiceList->getModelManager()->getModelCollectionInstance(
- $this->choiceList->getClass()
- );
- if (!$collection instanceof \ArrayAccess) {
- throw new UnexpectedTypeException($collection, '\ArrayAccess');
- }
- if ('' === $keys || null === $keys) {
- return $collection;
- }
- if (!is_array($keys)) {
- throw new UnexpectedTypeException($keys, 'array');
- }
- $notFound = array();
-
- foreach ($keys as $key) {
- if ($entity = $this->choiceList->getEntity($key)) {
- $collection[] = $entity;
- } else {
- $notFound[] = $key;
- }
- }
- if (count($notFound) > 0) {
- throw new TransformationFailedException(sprintf('The entities with keys "%s" could not be found', implode('", "', $notFound)));
- }
- return $collection;
- }
- }
|