Browse Source

Disallow nodes being their own parents.

A node can never be its own parent. Disallow this state in both the
update and create scenarios.

Refs #9080
Mark Story 9 years ago
parent
commit
4189c717f0

+ 4 - 4
src/ORM/Behavior/TreeBehavior.php

@@ -103,11 +103,11 @@ class TreeBehavior extends Behavior
         $dirty = $entity->dirty($config['parent']);
         $level = $config['level'];
 
-        if ($isNew && $parent) {
-            if ($entity->get($primaryKey[0]) == $parent) {
-                throw new RuntimeException("Cannot set a node's parent as itself");
-            }
+        if ($parent && $entity->get($primaryKey) == $parent) {
+            throw new RuntimeException("Cannot set a node's parent as itself");
+        }
 
+        if ($isNew && $parent) {
             $parentNode = $this->_getNode($parent);
             $edge = $parentNode->get($config['right']);
             $entity->set($config['left'], $edge);

+ 29 - 0
tests/TestCase/ORM/Behavior/TreeBehaviorTest.php

@@ -887,6 +887,35 @@ class TreeBehaviorTest extends TestCase
     }
 
     /**
+     * Tests making a node its own parent as an existing entity
+     *
+     * @expectedException RuntimeException
+     * @expectedExceptionMessage Cannot set a node's parent as itself
+     * @return void
+     */
+    public function testReParentSelf()
+    {
+        $entity = $this->table->get(1);
+        $entity->parent_id = $entity->id;
+        $this->table->save($entity);
+    }
+
+    /**
+     * Tests making a node its own parent as a new entity.
+     *
+     * @expectedException RuntimeException
+     * @expectedExceptionMessage Cannot set a node's parent as itself
+     * @return void
+     */
+    public function testReParentSelfNewEntity()
+    {
+        $entity = $this->table->newEntity(['name' => 'root']);
+        $entity->id = 1;
+        $entity->parent_id = $entity->id;
+        $this->table->save($entity);
+    }
+
+    /**
      * Tests moving a subtree to the right
      *
      * @return void