Browse Source

Merge pull request #6074 from cakephp/3.0-isnew

Allowing cloned entities to be saved after marked as new
Mark Story 11 years ago
parent
commit
30f9ec57b2
3 changed files with 55 additions and 1 deletions
  1. 10 1
      src/Datasource/EntityTrait.php
  2. 23 0
      tests/TestCase/ORM/EntityTest.php
  3. 22 0
      tests/TestCase/ORM/TableTest.php

+ 10 - 1
src/Datasource/EntityTrait.php

@@ -606,7 +606,16 @@ trait EntityTrait
         if ($new === null) {
             return $this->_new;
         }
-        return $this->_new = (bool)$new;
+
+        $new = (bool)$new;
+
+        if ($new) {
+            foreach ($this->_properties as $k => $p) {
+                $this->_dirty[$k] = true;
+            }
+        }
+
+        return $this->_new = $new;
     }
 
     /**

+ 23 - 0
tests/TestCase/ORM/EntityTest.php

@@ -1140,4 +1140,27 @@ class EntityTest extends TestCase
         $entity = new Entity();
         $entity->set($property, 'bar');
     }
+
+    /**
+     * Provides empty values
+     *
+     * @return void
+     */
+    public function testIsDirtyFromClone()
+    {
+        $entity = new Entity(
+            ['a' => 1, 'b' => 2],
+            ['markNew' => false, 'markClean' => true]
+        );
+
+        $this->assertFalse($entity->isNew());
+        $this->assertFalse($entity->dirty());
+
+        $cloned = clone $entity;
+        $cloned->isNew(true);
+
+        $this->assertTrue($cloned->dirty());
+        $this->assertTrue($cloned->dirty('a'));
+        $this->assertTrue($cloned->dirty('b'));
+    }
 }

+ 22 - 0
tests/TestCase/ORM/TableTest.php

@@ -4025,6 +4025,28 @@ class TableTest extends TestCase
     }
 
     /**
+     * Tests that passing a coned entity that was marked as new to save() will
+     * actaully save it as a new entity
+     *
+     * @return void
+     */
+    public function testSaveWithClonedEntity()
+    {
+        $table = TableRegistry::get('Articles');
+        $article = $table->get(1);
+
+        $cloned = clone $article;
+        $cloned->unsetProperty('id');
+        $cloned->isNew(true);
+        $this->assertSame($cloned, $table->save($cloned));
+        $this->assertEquals(
+            $article->extract(['title', 'author_id']),
+            $cloned->extract(['title', 'author_id'])
+        );
+        $this->assertEquals(4, $cloned->id);
+    }
+
+    /**
      * Helper method to skip tests when connection is SQLServer.
      *
      * @return void