Skip to content

Commit

Permalink
Clean primary entity after "Model.afterSaveCommit" is triggered.
Browse files Browse the repository at this point in the history
Previously primary entity was being cleaned too early and callbacks for
Model.afterSaveCommit become useless if one wanted to acccess original state.
  • Loading branch information
ADmad committed Sep 14, 2016
1 parent df1b9b8 commit 720f42d
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
3 changes: 2 additions & 1 deletion src/ORM/Table.php
Expand Up @@ -1502,6 +1502,7 @@ public function save(EntityInterface $entity, $options = [])
$this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options'));
}
if ($options['atomic'] || $options['_primary']) {
$entity->clean();
$entity->isNew(false);
$entity->source($this->registryAlias());
}
Expand Down Expand Up @@ -1606,8 +1607,8 @@ protected function _onSaveSuccess($entity, $options)
throw new RolledbackTransactionException(['table' => get_class($this)]);
}

$entity->clean();
if (!$options['atomic'] && !$options['_primary']) {
$entity->clean();
$entity->isNew(false);
$entity->source($this->registryAlias());
}
Expand Down
12 changes: 5 additions & 7 deletions tests/TestCase/ORM/TableTest.php
Expand Up @@ -2209,11 +2209,9 @@ public function testBeforeSaveStopEvent()
public function testAfterSave()
{
$table = TableRegistry::get('users');
$data = new \Cake\ORM\Entity([
'username' => 'superuser',
'created' => new Time('2013-10-10 00:00'),
'updated' => new Time('2013-10-10 00:00')
]);
$data = $table->get(1);

$data->username = 'newusername';

$called = false;
$listener = function ($e, $entity, $options) use ($data, &$called) {
Expand All @@ -2226,13 +2224,13 @@ public function testAfterSave()
$calledAfterCommit = false;
$listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
$this->assertSame($data, $entity);
$this->assertFalse($entity->dirty());
$this->assertTrue($entity->dirty());
$this->assertNotSame($data->get('username'), $data->getOriginal('username'));
$calledAfterCommit = true;
};
$table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);

$this->assertSame($data, $table->save($data));
$this->assertEquals($data->id, self::$nextUserId);
$this->assertTrue($called);
$this->assertTrue($calledAfterCommit);
}
Expand Down

0 comments on commit 720f42d

Please sign in to comment.