diff --git a/src/ORM/Exception/PersistenceFailedException.php b/src/ORM/Exception/PersistenceFailedException.php new file mode 100644 index 00000000000..59983eaefef --- /dev/null +++ b/src/ORM/Exception/PersistenceFailedException.php @@ -0,0 +1,24 @@ +save($entity, $options); + if ($saved === false) { + throw new PersistenceFailedException(['save', $entity]); + } + + return $saved; + } + /** * Performs the actual saving of an entity based on the passed options. * @@ -1847,6 +1868,26 @@ public function delete(EntityInterface $entity, $options = []) return $success; } + /** + * Try to delete an entity or throw a PersistenceFailedException if the entity is new, + * has no primary key value, application rules checks failed or the delete was aborted by a callback. + * + * @param \Cake\Datasource\EntityInterface $entity The entity to remove. + * @param array|\ArrayAccess $options The options for the delete. + * @return bool success + * @throws \Cake\ORM\Exception\PersistenceFailedException + * @see \Cake\ORM\Table::delete() + */ + public function deleteOrFail(EntityInterface $entity, $options = []) + { + $deleted = $this->delete($entity, $options); + if ($deleted === false) { + throw new PersistenceFailedException(['delete', $entity]); + } + + return $deleted; + } + /** * Perform the delete operation. * diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php index 586d3956b99..d721b1778ac 100644 --- a/tests/TestCase/ORM/TableTest.php +++ b/tests/TestCase/ORM/TableTest.php @@ -6295,6 +6295,43 @@ public function testLoadIntoMany() $this->assertEquals($expected, $result); } + /** + * Tests that saveOrFail triggers an exception on not successful save + * + * @return void + * @expectedException \Cake\ORM\Exception\PersistenceFailedException + * @expectedExceptionMessage Entity save failure. + */ + public function testSaveOrFail() + { + $entity = new Entity([ + 'foo' => 'bar' + ]); + $table = TableRegistry::get('users'); + + $table->saveOrFail($entity); + + $row = $table->find('all')->where(['foo' => 'bar'])->toArray(); + $this->assertSame([], $row->toArray()); + } + + /** + * Tests that deleteOrFail triggers an exception on not successful delete + * + * @return void + * @expectedException \Cake\ORM\Exception\PersistenceFailedException + * @expectedExceptionMessage Entity delete failure. + */ + public function testDeleteOrFail() + { + $entity = new Entity([ + 'id' => 999 + ]); + $table = TableRegistry::get('users'); + + $result = $table->deleteOrFail($entity); + } + /** * Test getting the save options builder. *