Skip to content

Commit

Permalink
Changing save code so that beforeFind always get the latest information
Browse files Browse the repository at this point in the history
on the persistence status for the entity
  • Loading branch information
lorenzo committed Nov 3, 2013
1 parent 5aa3113 commit a37143a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Cake/Database/Query.php
Expand Up @@ -515,7 +515,7 @@ protected function _buildFromPart($parts, $generator) {
$parts = $this->_stringifyExpressions($parts, $generator);
foreach ($parts as $k => $p) {
if (!is_numeric($k)) {
$p = $p . ' AS ' . $driver->quoteIdentifier($k);
$p = $p . ' AS ' . $k;
}
$normalized[] = $p;
}
Expand Down
18 changes: 9 additions & 9 deletions Cake/ORM/Table.php
Expand Up @@ -803,6 +803,15 @@ public function save(Entity $entity, array $options = []) {
* @return \Cake\ORM\Entity|boolean
*/
protected function _processSave($entity, $options) {
$primary = $entity->extract((array)$this->primaryKey());
if ($primary && $entity->isNew() === null) {
$entity->isNew(!$this->exists($primary));
}

if ($entity->isNew() === null) {
$entity->isNew(true);
}

$event = new Event('Model.beforeSave', $this, compact('entity', 'options'));
$this->getEventManager()->dispatch($event);

Expand All @@ -814,15 +823,6 @@ protected function _processSave($entity, $options) {
$data = $entity->extract($list, true);
$keys = array_keys($data);

$primary = $entity->extract((array)$this->primaryKey());
if ($primary && $entity->isNew() === null) {
$entity->isNew(!$this->exists($primary));
}

if ($entity->isNew() === null) {
$entity->isNew(true);
}

if ($entity->isNew()) {
$success = $this->_insert($entity, $data);
} else {
Expand Down
21 changes: 21 additions & 0 deletions Cake/Test/TestCase/ORM/TableTest.php
Expand Up @@ -1451,6 +1451,27 @@ public function testSaveUpdateAuto() {
$this->assertFalse($entity->dirty('username'));
}

/**
* Tests that beforeFind gets the correct isNew() state for the entity
*
* @return void
*/
public function testBeforeSaveGetsCorrectPersistance() {
$entity = new \Cake\ORM\Entity([
'id' => 2,
'username' => 'baggins'
]);
$table = TableRegistry::get('users');
$called = false;
$listener = function($event, $entity) use (&$called) {
$this->assertFalse($entity->isNew());
$called = true;
};
$table->getEventManager()->attach($listener, 'Model.beforeSave');
$this->assertSame($entity, $table->save($entity));
$this->assertTrue($called);
}

/**
* Tests that marking an entity as already persisted will prevent the save
* method from trying to infer the entity's actual status.
Expand Down

0 comments on commit a37143a

Please sign in to comment.