/**
  * @param string $value
  * @param Doctrine\Common\Collections\Collection $collection
  */
 public function reverseTransform($value, $collection)
 {
     if (strlen(trim($value)) == 0) {
         // don't check for collection count, a straight clear doesnt initialize the collection
         $collection->clear();
         return $collection;
     }
     $className = $this->getOption('className');
     $values = explode($this->getOption('separator'), $value);
     if ($this->getOption('trim') === true) {
         $values = array_map('trim', $values);
     }
     /* @var $em Doctrine\ORM\EntityManager */
     $em = $this->getOption('em');
     $reflField = $em->getClassMetadata($className)->getReflectionProperty($this->getOption('fieldName'));
     // 1. removing elements that are not yet present anymore
     foreach ($collection as $object) {
         $uniqueIdent = $reflField->getValue($object);
         $key = \array_search($uniqueIdent, $values);
         if ($key === false) {
             $collection->removeElement($object);
         } else {
             // found in the collection, no need to do anything with it so remove it
             unset($values[$key]);
         }
     }
     // 2. add elements that are known to the EntityManager but newly connected, query them from the repository
     if (count($values)) {
         $dql = "SELECT o FROM " . $className . " o WHERE o." . $this->getOption('fieldName') . " IN (";
         $query = $em->createQuery();
         $needles = array();
         $i = 0;
         foreach ($values as $val) {
             $query->setParameter(++$i, $val);
             $needles[] = "?" . $i;
         }
         $dql .= implode(",", $needles) . ")";
         $query->setDql($dql);
         $newElements = $query->getResult();
         foreach ($newElements as $object) {
             $collection->add($object);
             $uniqueIdent = $reflField->getValue($object);
             $key = \array_search($uniqueIdent, $values);
             unset($values[$key]);
         }
     }
     // 3. new elements that are not in the repository have to be created and persisted then attached:
     if (count($values)) {
         $callback = $this->getOption('createInstanceCallback');
         if (!$callback || !\is_callable($callback)) {
             throw new TransformationFailedException("Cannot transform list of identifiers, because a new " . "element was detected and it is unknown how to create an instance of this element.");
         }
         foreach ($values as $newValue) {
             $newInstance = \call_user_func($callback, $newValue);
             if (!$newInstance instanceof $className) {
                 throw new TransformationFailedException("Error while trying to create a new instance for " . "the identifier '" . $newValue . "'. No new instance was created.");
             }
             $collection->add($newInstance);
             $em->persist($newInstance);
         }
     }
     return $collection;
 }