Browse Source

More correct populateTree()

tags/v1.0.6 v1.0.6
PaulZi 8 years ago
parent
commit
78d1aead3c
  1. 12
      NestedSetsBehavior.php
  2. 8
      tests/NestedSetsBehaviorTestCase.php

12
NestedSetsBehavior.php

@ -228,14 +228,13 @@ class NestedSetsBehavior extends Behavior
$key = $this->owner->getAttribute($this->leftAttribute); $key = $this->owner->getAttribute($this->leftAttribute);
$relates = []; $relates = [];
$relates[$key] = [];
$parents = [$key]; $parents = [$key];
$prev = $this->owner->getAttribute($this->depthAttribute); $prev = $this->owner->getAttribute($this->depthAttribute);
foreach($nodes as $node) foreach($nodes as $node)
{ {
$depth = $node->getAttribute($this->depthAttribute); $level = $node->getAttribute($this->depthAttribute);
if ($depth <= $prev) { if ($level <= $prev) {
$parents = array_slice($parents, 0, $depth - $prev - 1); $parents = array_slice($parents, 0, $level - $prev - 1);
} }
$key = end($parents); $key = end($parents);
@ -245,14 +244,17 @@ class NestedSetsBehavior extends Behavior
$relates[$key][] = $node; $relates[$key][] = $node;
$parents[] = $node->getAttribute($this->leftAttribute); $parents[] = $node->getAttribute($this->leftAttribute);
$prev = $depth; $prev = $level;
} }
$ownerDepth = $this->owner->getAttribute($this->depthAttribute);
$nodes[] = $this->owner; $nodes[] = $this->owner;
foreach ($nodes as $node) { foreach ($nodes as $node) {
$key = $node->getAttribute($this->leftAttribute); $key = $node->getAttribute($this->leftAttribute);
if (isset($relates[$key])) { if (isset($relates[$key])) {
$node->populateRelation('children', $relates[$key]); $node->populateRelation('children', $relates[$key]);
} elseif ($depth === null || $ownerDepth + $depth > $node->getAttribute($this->depthAttribute)) {
$node->populateRelation('children', []);
} }
} }

8
tests/NestedSetsBehaviorTestCase.php

@ -136,6 +136,14 @@ class NestedSetsBehaviorTestCase extends BaseTestCase
$node = Node::findOne(19); $node = Node::findOne(19);
$node->populateTree(1); $node->populateTree(1);
$this->assertEquals(true, $node->isRelationPopulated('children')); $this->assertEquals(true, $node->isRelationPopulated('children'));
$node = Node::findOne(1);
$node->populateTree(1);
$this->assertEquals(false, $node->children[1]->isRelationPopulated('children'));
$node = Node::findOne(1);
$node->populateTree(2);
$this->assertEquals(true, $node->children[1]->isRelationPopulated('children'));
} }
public function testIsRoot() public function testIsRoot()

Loading…
Cancel
Save