public function testToHierarchyNestsCorrectly() { // Prune all categories Cluster::query()->delete(); // Build a sample tree structure: // // - A // |- A.1 // |- A.2 // - B // |- B.1 // |- B.2 // |- B.2.1 // |- B.2.2 // |- B.2.2.1 // |- B.2.3 // |- B.3 // - C // |- C.1 // |- C.2 // - D // $a = Cluster::create(array('name' => 'A')); $b = Cluster::create(array('name' => 'B')); $c = Cluster::create(array('name' => 'C')); $d = Cluster::create(array('name' => 'D')); $ch = Cluster::create(array('name' => 'A.1')); $ch->makeChildOf($a); $ch = Cluster::create(array('name' => 'A.2')); $ch->makeChildOf($a); $ch = Cluster::create(array('name' => 'B.1')); $ch->makeChildOf($b); $ch = Cluster::create(array('name' => 'B.2')); $ch->makeChildOf($b); $ch2 = Cluster::create(array('name' => 'B.2.1')); $ch2->makeChildOf($ch); $ch2 = Cluster::create(array('name' => 'B.2.2')); $ch2->makeChildOf($ch); $ch3 = Cluster::create(array('name' => 'B.2.2.1')); $ch3->makeChildOf($ch2); $ch2 = Cluster::create(array('name' => 'B.2.3')); $ch2->makeChildOf($ch); $ch = Cluster::create(array('name' => 'B.3')); $ch->makeChildOf($b); $ch = Cluster::create(array('name' => 'C.1')); $ch->makeChildOf($c); $ch = Cluster::create(array('name' => 'C.2')); $ch->makeChildOf($c); $this->assertTrue(Cluster::isValidNestedSet()); // Build expectations (expected trees/subtrees) $expectedWholeTree = array('A' => array('A.1' => null, 'A.2' => null), 'B' => array('B.1' => null, 'B.2' => array('B.2.1' => null, 'B.2.2' => array('B.2.2.1' => null), 'B.2.3' => null), 'B.3' => null), 'C' => array('C.1' => null, 'C.2' => null), 'D' => null); $expectedSubtreeA = array('A' => array('A.1' => null, 'A.2' => null)); $expectedSubtreeB = array('B' => array('B.1' => null, 'B.2' => array('B.2.1' => null, 'B.2.2' => array('B.2.2.1' => null), 'B.2.3' => null), 'B.3' => null)); $expectedSubtreeC = array('C.1' => null, 'C.2' => null); $expectedSubtreeD = array('D' => null); // Perform assertions $wholeTree = hmap(Cluster::all()->toHierarchy()->toArray()); $this->assertArraysAreEqual($expectedWholeTree, $wholeTree); $subtreeA = hmap($this->clusters('A')->getDescendantsAndSelf()->toHierarchy()->toArray()); $this->assertArraysAreEqual($expectedSubtreeA, $subtreeA); $subtreeB = hmap($this->clusters('B')->getDescendantsAndSelf()->toHierarchy()->toArray()); $this->assertArraysAreEqual($expectedSubtreeB, $subtreeB); $subtreeC = hmap($this->clusters('C')->getDescendants()->toHierarchy()->toArray()); $this->assertArraysAreEqual($expectedSubtreeC, $subtreeC); $subtreeD = hmap($this->clusters('D')->getDescendantsAndSelf()->toHierarchy()->toArray()); $this->assertArraysAreEqual($expectedSubtreeD, $subtreeD); $this->assertTrue($this->clusters('D')->getDescendants()->toHierarchy()->isEmpty()); }