Skip to content

Commit

Permalink
Merge pull request #1 from UncleCoder/feature/roots
Browse files Browse the repository at this point in the history
Feature/roots
  • Loading branch information
AidasK committed Aug 16, 2013
2 parents 2626548 + f103d48 commit c2a1e7a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
26 changes: 26 additions & 0 deletions ClosureTableBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,32 @@ class ClosureTableBehavior extends CActiveRecordBehavior
public $parentAttribute = 'parent';
public $depthAttribute = 'depth';
public $isLeafParameter = 'leaf';

/**
* Finds roots
* @return CActiveRecord the owner.
*/
public function roots()
{
$owner = $this->getOwner();
$db = $owner->getDbConnection();
$criteria = $owner->getDbCriteria();
$alias = $owner->getTableAlias(true);
$closureTable = $db->quoteTableName($this->closureTableName);
$childAttribute = $db->quoteColumnName($this->childAttribute);
$parentAttribute = $db->quoteColumnName($this->parentAttribute);
$primaryKeyName = $db->quoteColumnName($owner->tableSchema->primaryKey);
$criteria->mergeWith(array(
'join' => 'LEFT JOIN ' . $closureTable . ' ct1'
. ' ON ' . $alias . '.' . $primaryKeyName . '=ct1.' . $childAttribute
. ' LEFT JOIN ' . $closureTable . ' ct2'
. ' ON ct1.' . $childAttribute . '=ct2.' . $childAttribute
. ' AND ct2.' . $parentAttribute . '<>ct1.' . $parentAttribute,
'condition' => 'ct2.' . $parentAttribute . 'IS NULL'
));
return $owner;
}


/**
* Finds descendants
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/ClosureTableBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ class ClosureTableBehaviorTest extends CDbTestCase
'folder_tree' => ':folder_tree',
'Related'
);

public function testRoots() {
$folder = Folder::model()->findByPk(1);
$this->assertTrue($folder instanceof Folder);
$rootFolders= Folder::model()->roots()->findAll();
$this->assertEquals(1, count($rootFolders));
$ancestorsCount=0;
foreach ($rootFolders as $row){
$ancestorsCount+=$row->ancestors()->count();
}
$this->assertEquals(0, $ancestorsCount);

}

public function testDescendants()
{
Expand Down

0 comments on commit c2a1e7a

Please sign in to comment.