Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix] Model::duplicate #801

Merged
merged 9 commits into from
Dec 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
20 changes: 11 additions & 9 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -1174,19 +1174,21 @@ public function reload()
* when you save it next time, it ends up as a new
* record in the database.
*
* @param mixed $newId
*
* @return $this
* @return static
*/
public function duplicate($newId = null)
public function duplicate()
{
$this->setId(null);

if ($this->id_field) {
$this->setId($newId);
// TODO remove in v2.6
if (func_num_args() > 0) {
throw new Exception('Duplicating using existing ID is no longer supported');
}

return $this;
$duplicate = clone $this;
$duplicate->dirty = $this->data;
$duplicate->entityId = null;
$duplicate->setId(null);

return $duplicate;
}

/**
Expand Down
28 changes: 28 additions & 0 deletions tests/RandomTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,34 @@ public function testNewInstance()
$this->assertTrue(isset($a->persistence));
}

public function testDuplicateSaveNew()
{
$this->setDb([
'rate' => [
['dat' => '18/12/12', 'bid' => 3.4, 'ask' => 9.4],
['dat' => '12/12/12', 'bid' => 8.3, 'ask' => 9.2],
],
]);

$db = new Persistence\Sql($this->db->connection);
$m = new Model_Rate($db);

$m->load(1)->duplicate()->save();

$this->assertSame([
['id' => 1, 'dat' => '18/12/12', 'bid' => '3.4', 'ask' => '9.4'],
['id' => 2, 'dat' => '12/12/12', 'bid' => '8.3', 'ask' => '9.2'],
['id' => 3, 'dat' => '18/12/12', 'bid' => '3.4', 'ask' => '9.4'],
], $m->export());
}

public function testDuplicateWithIdArgumentException()
{
$m = new Model_Rate();
$this->expectException(Exception::class);
$m->duplicate(2)->save();
}

public function testTableNameDots()
{
$d = new Model($this->db, 'db2.doc');
Expand Down