Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 36 additions & 3 deletions src/Model/Behavior/DuplicatableBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ class DuplicatableBehavior extends Behavior
'set' => [],
'prepend' => [],
'append' => [],
'saveOptions' => []
'saveOptions' => [],
'preserveKeyFromCompositeKey' => ''
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this this a string, what if composite key consistents of 3 fields and 2 need to be removed?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

];

/**
Expand Down Expand Up @@ -179,12 +180,14 @@ protected function _modifyEntity(EntityInterface $entity, $object)
if ($object instanceof BelongsToMany) {
unset($entity->_joinData);
} else {

// unset primary key
unset($entity->{$object->getPrimaryKey()});
$this->removePrimaryKey($entity, $object);

// unset foreign key
if ($object instanceof Association) {
unset($entity->{$object->getPrimaryKey()});
// unset primary key
$this->removePrimaryKey($entity, $object);
}
}

Expand Down Expand Up @@ -329,4 +332,34 @@ protected function _doAction($action, EntityInterface $entity, $prop, $value = n
break;
}
}

/**
* Removes the primary key from the entity being duplicated. If the entity has a composite key, you must
* specify which field we wish to preserve
*
* @param EntityInterface $entity
* @param $object
* @throws \Exception
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return void missing maybe here?

*/
protected function removePrimaryKey(EntityInterface $entity, $object)
{
if (is_array($object->getPrimaryKey())) {

$compositeKey = $object->getPrimaryKey();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make this assignment the first statement (with name $primaryKey) and avoid calling method again.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


$keyToPreserve = $this->getConfig('preserveKeyFromCompositeKey');

if(!in_array($keyToPreserve, $compositeKey)){
throw new \Exception('You must specify which key to preserve when duplicating composite keys');
}

foreach ($compositeKey as $pkField){
if ($pkField != $keyToPreserve) {
unset($entity->{$pkField});
}
}
} else {
unset($entity->{$object->getPrimaryKey()});
}
}
}