Skip to content

Commit f204540

Browse files
committed
added Container::getComponentTree()
1 parent fa48b49 commit f204540

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/ComponentModel/Container.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,23 @@ final public function getComponents(bool $deep = false, ?string $filterType = nu
196196
}
197197

198198

199+
/**
200+
* Retrieves the entire hierarchy of components, including all nested child components (depth-first).
201+
* @return list<IComponent>
202+
*/
203+
final public function getComponentTree(): array
204+
{
205+
$res = [];
206+
foreach ($this->components as $component) {
207+
$res[] = $component;
208+
if ($component instanceof self) {
209+
$res = array_merge($res, $component->getComponentTree());
210+
}
211+
}
212+
return $res;
213+
}
214+
215+
199216
/**
200217
* Descendant can override this method to disallow insert a child by throwing an Nette\InvalidStateException.
201218
* @throws Nette\InvalidStateException
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\ComponentModel\Container::getComponentTree()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\ComponentModel\Component;
10+
use Nette\ComponentModel\Container;
11+
use Tester\Assert;
12+
13+
require __DIR__ . '/../bootstrap.php';
14+
15+
16+
class Button extends Component
17+
{
18+
}
19+
20+
class ComponentX extends Component
21+
{
22+
}
23+
24+
$c = new Container;
25+
26+
$c->addComponent(new Container, 'one');
27+
$c->addComponent(new ComponentX, 'two');
28+
$c->addComponent(new Button, 'button1');
29+
30+
$c->getComponent('one')->addComponent(new ComponentX, 'inner');
31+
$c->getComponent('one')->addComponent(new Container, 'inner2');
32+
$c->getComponent('one')->getComponent('inner2')->addComponent(new Button, 'button2');
33+
34+
35+
$list = $c->getComponentTree();
36+
Assert::same([
37+
'one',
38+
'inner',
39+
'inner2',
40+
'button2',
41+
'two',
42+
'button1',
43+
], array_map(fn($c) => $c->getName(), $list));

0 commit comments

Comments
 (0)