Skip to content

Commit 04f0094

Browse files
khaledkhamisAdrianSkierniewski
authored andcommitted
Added getLeafs function (#12)
* Added getLeafs function * Update README.md * fix typo * added test for getLeaves function * add another test case
1 parent ff353d2 commit 04f0094

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Schema::create(
6767

6868
- [Inserting and Updating new nodes](#inserting-and-updating-new-nodes)
6969
- [Getting tree nodes](#getting-tree-nodes)
70+
- [Finding Leaf nodes](#getting-leaf-nodes)
7071
- [Map from array](#map-from-array)
7172
- [Rendering tree](#rendering-tree)
7273

@@ -111,6 +112,11 @@ Building tree structure on PHP side - if some nodes will be missing, these branc
111112
$treeRoot = $root->buildTree($root->findDescendants()->get())
112113
```
113114

115+
### Getting leaf nodes
116+
```php
117+
Tree::getLeafs();
118+
```
119+
114120
### Map from array
115121

116122
Three new roots, first with descendants

src/Gzero/EloquentTree/Model/Tree.php

+11
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,17 @@ public static function getRoots()
344344
return static::whereNull(static::getTreeColumn('parent'));
345345
}
346346

347+
/**
348+
* Gets all leaf nodes
349+
*
350+
* @return \Illuminate\Database\Eloquent\Builder
351+
*/
352+
public static function getLeaves()
353+
{
354+
$parents = static::select('parent_id')->whereNotNull('parent_id')->distinct()->get()->pluck('parent_id')->all();
355+
return static::wherenotin('id',$parents);
356+
}
357+
347358
/**
348359
* @param null $name
349360
*

tests/Test.php

+35
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,41 @@ public function can_map_array()
336336
$this->assertEquals(4, Tree::find(5)->findAncestors()->count(), 'Expected numer of Ancestors'); // Most nested
337337
}
338338

339+
/**
340+
* getting leaf nodes
341+
*
342+
* @test
343+
*/
344+
public function get_leaf_nodes()
345+
{
346+
extract($this->_createSampleTree());
347+
$correct = [
348+
$child2,
349+
$child3,
350+
$child1_1_1
351+
];
352+
foreach($root->getLeaves()->get() as $key=>$node )
353+
{
354+
$this->assertEquals($correct[$key]->toArray(),$node->toArray());
355+
}
356+
}
357+
358+
359+
/**
360+
* getting leaf nodes if the tree is only one node(root)
361+
*
362+
* @test
363+
*/
364+
public function get_leaf_nodes_root_only()
365+
{
366+
$root= with(new Tree())->setAsRoot();
367+
$correct = [
368+
$root->toArray()
369+
];
370+
$this->assertEquals($correct,$root->getLeaves()->get()->toArray());
371+
}
372+
373+
339374
/**
340375
* Define environment setup.
341376
*

0 commit comments

Comments
 (0)