/**
  * @param mixed $valueOrObject
  * @param string $target
  * @return array
  */
 protected function toMany($valueOrObject, $target, Collection $collection = null, $depth = 2)
 {
     if (!is_array($valueOrObject) && !$valueOrObject instanceof Traversable) {
         $valueOrObject = (array) $valueOrObject;
     }
     if (!$collection instanceof Collection) {
         $collection = new ArrayCollection();
     }
     $keepers = array();
     foreach ($valueOrObject as $value) {
         if (method_exists($value, 'toArray')) {
             $value = $value->toArray($depth);
         } else {
             if (!is_array($value) && !$value instanceof Traversable) {
                 $value = (array) $value;
             }
         }
         if (isset($value['id']) && strlen($value['id']) && ($found = $this->find($target, $value['id']))) {
             $keepers[] = $found->id;
             $this->hydrate($value, $found);
         } else {
             $obj = new $target();
             $obj->fromArray($value);
             $obj->id = null;
             if ($collection instanceof PersistentCollection) {
                 if ($owner = $collection->getOwner()) {
                     $mapping = $collection->getMapping();
                     $mappedBy = $mapping['mappedBy'];
                     $obj->{$mappedBy} = $owner;
                 }
             }
             $collection->add($obj);
         }
     }
     $collection->forAll(function ($key, $element) use($collection, $keepers) {
         if (strlen($element->id) && !in_array($element->id, $keepers)) {
             $collection->remove($key);
         }
     });
     return $collection;
 }