summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/libraries/ORM_MPTT.php18
-rw-r--r--core/tests/ORM_MPTT_Test.php19
2 files changed, 28 insertions, 9 deletions
diff --git a/core/libraries/ORM_MPTT.php b/core/libraries/ORM_MPTT.php
index 5cdf9c02..c9c29805 100644
--- a/core/libraries/ORM_MPTT.php
+++ b/core/libraries/ORM_MPTT.php
@@ -37,6 +37,7 @@ class ORM_MPTT_Core extends ORM {
private $parents = null;
private $children = null;
private $children_count = null;
+ private $descendants_count = array();
function __construct($id=null) {
parent::__construct($id);
@@ -165,19 +166,18 @@ class ORM_MPTT_Core extends ORM {
* @return integer child count
*/
function descendants_count($type=null) {
- // @todo create a unit test
- // @todo set up caching in an array;; using type=all allows us to cache as decendents[$type]
- $this->where("left >=", $this->left)
- ->where("right <=", $this->right);
- if ($type) {
- $this->where("type", $type);
+ if (!isset($this->descendants_count[$type])) {
+ $this->where("left >", $this->left)
+ ->where("right <=", $this->right);
+ if ($type) {
+ $this->where("type", $type);
+ }
+ $this->descendants_count[$type] = $this->count_all();
}
- // @todo does it make sense to order it before counting?
- return $this->count_all();
+ return $this->descendants_count[$type];
}
-
/**
* @see ORM::reload
*/
diff --git a/core/tests/ORM_MPTT_Test.php b/core/tests/ORM_MPTT_Test.php
index d66006f5..a053b61e 100644
--- a/core/tests/ORM_MPTT_Test.php
+++ b/core/tests/ORM_MPTT_Test.php
@@ -94,4 +94,23 @@ class ORM_MPTT_Test extends Unit_Test_Case {
$inner2->add_to_parent($outer->id);
$this->assert_equal(2, $outer->children_count());
}
+
+ public function descendant_count_test() {
+ $parent = album::create(1, "parent album", "parent album title");
+ photo::create($parent->id, DOCROOT . "themes/default/images/thumbnail.jpg", "photo1",
+ "photo1", "parent album photo");
+
+ $album1 = album::create($parent->id, "album1", "album1 title");
+ photo::create($album1->id, DOCROOT . "themes/default/images/thumbnail.jpg", "photo1",
+ "photo1", "album1 photo");
+
+ $album2 = album::create($parent->id, "album2", "album2 title");
+ photo::create($album2->id, DOCROOT . "themes/default/images/thumbnail.jpg", "photo2",
+ "photo2", "album2 photo");
+ $parent->reload();
+
+ $this->assert_equal(5, $parent->descendants_count());
+ $this->assert_equal(3, $parent->descendants_count("photo"));
+ $this->assert_equal(2, $parent->descendants_count("album"));
+ }
}