Skip to content

Commit 2155a46

Browse files
committed
Added rootNodes() method
1 parent b8ac9db commit 2155a46

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

src/Ems/Contracts/Tree/NodeProvider.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,11 @@ public function parent(CanHaveParent $child);
112112
* @return Node[]
113113
*/
114114
public function ancestors(CanHaveParent $child);
115+
116+
/**
117+
* Return all known root nodes.
118+
*
119+
* @return Node[]
120+
*/
121+
public function rootNodes();
115122
}

src/Ems/Tree/Eloquent/NodeRepository.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,25 @@ public function ancestors(CanHaveParent $child)
308308

309309
}
310310

311+
/**
312+
* {@inheritdoc}
313+
*
314+
* @return Node[]
315+
*/
316+
public function rootNodes()
317+
{
318+
$query = $this->model->newQuery()->whereNull($this->parentIdKey);
319+
320+
$this->callBeforeListeners('rootNodes', [$query]);
321+
322+
$nodes = $query->get()->all();
323+
324+
$this->callAfterListeners('rootNodes', [$nodes]);
325+
326+
return $nodes;
327+
}
328+
329+
311330
/**
312331
* @inheritDoc
313332
*/

tests/integration/Tree/Eloquent/EloquentNodeRepositoryIntegrationTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,37 @@ public function parent_returns_null_on_no_parent()
296296

297297
}
298298

299+
/**
300+
* @test
301+
*/
302+
public function rootNodes_returns_one_rootNode()
303+
{
304+
$repo = $this->newRepository();
305+
306+
$rootNodes = $repo->rootNodes();
307+
308+
$this->assertCount(1, $rootNodes);
309+
310+
}
311+
312+
/**
313+
* @test
314+
*/
315+
public function rootNodes_returns_many_rootNodes()
316+
{
317+
$repo = $this->newRepository();
318+
319+
$rootNode2 = $repo->store(['name' => 'root-2']);
320+
321+
$rootNodes = $repo->rootNodes();
322+
323+
$this->assertCount(2, $rootNodes);
324+
325+
$this->assertEquals('root-1', $rootNodes[0]->getPathSegment());
326+
$this->assertEquals('root-2', $rootNodes[1]->getPathSegment());
327+
328+
}
329+
299330
/**
300331
* @test
301332
*/

0 commit comments

Comments
 (0)