Skip to content

Commit

Permalink
Refactoring Table::save() to use Connection::transactional()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Oct 25, 2013
1 parent 57097ef commit e3c0867
Showing 1 changed file with 20 additions and 24 deletions.
44 changes: 20 additions & 24 deletions Cake/ORM/Table.php
Expand Up @@ -783,47 +783,43 @@ public function save(Entity $entity, array $options = []) {
return $event->result;
}

if ($options['atomic']) {
$connection = $this->connection();
$success = $connection->transactional(function() use ($entity, $options) {
return $this->_processSave($entity, $options);
});
} else {
$success = $this->_processSave($entity, $data, $options);
}

return $success;
}

protected function _processSave($entity, $options) {
$data = empty($options['fieldList']) ?
$entity->toArray() :
$entity->extract($options['fieldList']);

$schema = $this->schema();
$data = array_intersect_key($data, array_flip($schema->columns()));
$query = $this->_buildQuery();

$connection = $this->connection();
if ($options['atomic']) {
$connection->begin();
}

try {
$statement = $query->insert($this->table(), array_keys($data))
$statement = $query->insert($this->table(), array_keys($data))
->values($data)
->executeStatement();

$success = false;
if ($statement->rowCount() > 0) {
$primary = $this->primaryKey();
$id = $statement->lastInsertId($this->table(), $primary);
$entity->set($primary, $id);
$success = $entity;
}
} catch (\Exception $e) {
if ($options['atomic']) {
$connection->rollback();
}
throw $e;
$success = false;
if ($statement->rowCount() > 0) {
$primary = $this->primaryKey();
$id = $statement->lastInsertId($this->table(), $primary);
$entity->set($primary, $id);
$success = $entity;
}

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

if ($options['atomic']) {
$connection->commit();
}

return $success;
}

Expand Down

0 comments on commit e3c0867

Please sign in to comment.