Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Added the afterSave callback
  • Loading branch information
lorenzo committed Oct 24, 2013
1 parent 17c5818 commit 6d9b73d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
9 changes: 8 additions & 1 deletion Cake/ORM/Table.php
Expand Up @@ -794,13 +794,20 @@ public function save(Entity $entity, array $options = []) {
->values($data)
->executeStatement();

$success = false;
if ($statement->rowCount() > 0) {
$primary = $this->primaryKey();
$id = $statement->lastInsertId($this->table(), $primary);
$entity->set($primary, $id);
$success = $entity;
}

return $entity;
if ($success) {
$event = new Event('Model.afterSave', $this, compact('entity', 'options'));
$this->getEventManager()->dispatch($event);
}

return $success;
}

/**
Expand Down
56 changes: 56 additions & 0 deletions Cake/Test/TestCase/ORM/TableTest.php
Expand Up @@ -1080,4 +1080,60 @@ public function testBeforeSaveStopEvent() {
$this->assertNull($row);
}

/**
* Asserts that afterSave callback is called on successful save
*
* @return void
*/
public function testAfterSave() {
$table = Table::build('users');
$data = new \Cake\ORM\Entity([
'username' => 'superuser',
'created' => new \DateTime('2013-10-10 00:00'),
'updated' => new \DateTime('2013-10-10 00:00')
]);

$called = false;
$listener = function($e, $entity, $options) use ($data, &$called) {
$this->assertSame($data, $entity);
$called = true;
};
$table->getEventManager()->attach($listener, 'Model.afterSave');
$this->assertSame($data, $table->save($data));
$this->assertEquals($data->id, 5);
$this->assertTrue($called);
}

/**
* Asserts that afterSave callback not is called on unsuccessful save
*
* @return void
*/
public function testAfterSaveNotCalled() {
$table = $this->getMock('\Cake\ORM\Table', ['_buildQuery'], [['table' => 'users']]);
$query = $this->getMock('\Cake\ORM\Query', ['executeStatement'], [null, $table]);
$statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
$data = new \Cake\ORM\Entity([
'username' => 'superuser',
'created' => new \DateTime('2013-10-10 00:00'),
'updated' => new \DateTime('2013-10-10 00:00')
]);

$table->expects($this->once())->method('_buildQuery')
->will($this->returnValue($query));

$query->expects($this->once())->method('executeStatement')
->will($this->returnValue($statement));

$statement->expects($this->once())->method('rowCount')->will($this->returnValue(0));

$called = false;
$listener = function($e, $entity, $options) use ($data, &$called) {
$called = true;
};
$table->getEventManager()->attach($listener, 'Model.afterSave');
$this->assertFalse($table->save($data));
$this->assertFalse($called);
}

}

0 comments on commit 6d9b73d

Please sign in to comment.