protected function _saveTarget(EntityInterface $parentEntity, $entities, $options)
{
$joinAssociations = false;
if (!empty($options['associated'][$this->_junctionProperty]['associated'])) {
$joinAssociations = $options['associated'][$this->_junctionProperty]['associated'];
}
unset($options['associated'][$this->_junctionProperty]);
if (!(is_array($entities) || $entities instanceof Traversable)) {
$name = $this->property();
$message = sprintf('Could not save %s, it cannot be traversed', $name);
throw new InvalidArgumentException($message);
}
$table = $this->target();
$original = $entities;
$persisted = [];
foreach ($entities as $k => $entity) {
if (!$entity instanceof EntityInterface) {
break;
}
if (!empty($options['atomic'])) {
$entity = clone $entity;
}
$saved = $table->save($entity, $options);
if ($saved) {
$entities[$k] = $entity;
$persisted[] = $entity;
continue;
}
// Saving the new linked entity failed, copy errors back into the
// original entity if applicable and abort.
if (!empty($options['atomic'])) {
$original[$k]->errors($entity->errors());
}
if (!$saved) {
return false;
}
}
$options['associated'] = $joinAssociations;
$success = $this->_saveLinks($parentEntity, $persisted, $options);
if (!$success && !empty($options['atomic'])) {
$parentEntity->set($this->property(), $original);
return false;
}
$parentEntity->set($this->property(), $entities);
return $parentEntity;
}