Browse Source

Throwing PersistenceFailedException when findOrCreate fails to save

Jeremy Harris 7 years ago
parent
commit
d840670fac
2 changed files with 15 additions and 7 deletions
  1. 7 1
      src/ORM/Table.php
  2. 8 6
      tests/TestCase/ORM/TableTest.php

+ 7 - 1
src/ORM/Table.php

@@ -1737,7 +1737,13 @@ class Table implements RepositoryInterface, EventListenerInterface, EventDispatc
         }
         unset($options['defaults']);
 
-        return $this->save($entity, $options) ?: $entity;
+        $result = $this->save($entity, $options);
+
+        if ($result === false) {
+            throw new PersistenceFailedException($entity, ['findOrCreate']);
+        }
+
+        return $entity;
     }
 
     /**

+ 8 - 6
tests/TestCase/ORM/TableTest.php

@@ -32,6 +32,7 @@ use Cake\ORM\Association\BelongsToMany;
 use Cake\ORM\Association\HasMany;
 use Cake\ORM\Association\HasOne;
 use Cake\ORM\Entity;
+use Cake\ORM\Exception\PersistenceFailedException;
 use Cake\ORM\Query;
 use Cake\ORM\RulesChecker;
 use Cake\ORM\SaveOptionsBuilder;
@@ -5840,21 +5841,22 @@ class TableTest extends TestCase
     }
 
     /**
-     * Test that findOrCreate creates a new valid entity with the search data
+     * Test that findOrCreate throws a PersistenceFailedException when it cannot save
+     * an entity created from $search
      *
      * @return void
      */
-    public function testFindOrCreateValidatesNewEntity()
+    public function testFindOrCreateWithInvalidEntity()
     {
+        $this->expectException(PersistenceFailedException::class);
+        $this->expectExceptionMessage('Entity findOrCreate failure (title: "_empty").');
+
         $articles = $this->getTableLocator()->get('Articles');
         $validator = new Validator();
         $validator->notBlank('title');
         $articles->setValidator('default', $validator);
 
-        $article = $articles->findOrCreate(['title' => '']);
-        $this->assertTrue($article->isNew());
-        $this->assertNotEmpty($article->getError('title'));
-        $this->assertNull($article->id);
+        $articles->findOrCreate(['title' => '']);
     }
 
     /**