Skip to content

Commit

Permalink
Container::getComponents() implemented using ArrayIterator or Generator
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Dec 8, 2023
1 parent 8a1c8d0 commit 53693c3
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 63 deletions.
20 changes: 13 additions & 7 deletions src/ComponentModel/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,16 +182,22 @@ protected function createComponent(string $name): ?IComponent
*/
final public function getComponents(bool $deep = false, ?string $filterType = null): \Iterator
{
$iterator = new RecursiveComponentIterator($this->components);
if ($deep) {
$iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
}

if ($filterType) {
$iterator = new \CallbackFilterIterator($iterator, fn($item) => $item instanceof $filterType);
return (function () use ($filterType) {
foreach ($this->components as $name => $component) {
if (!$filterType || $component instanceof $filterType) {
yield $name => $component;
}
if ($component instanceof IContainer) {
yield from $component->getComponents(true, $filterType);
}
}
})();
}

return $iterator;
return $filterType
? new \ArrayIterator(array_filter($this->components, fn($item) => $item instanceof $filterType))
: new \ArrayIterator($this->components);
}


Expand Down
44 changes: 0 additions & 44 deletions src/ComponentModel/RecursiveComponentIterator.php

This file was deleted.

12 changes: 0 additions & 12 deletions tests/ComponentModel/Container.iterator.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,6 @@ Assert::same([
], array_keys(iterator_to_array($list)));


// RecursiveIteratorIterator
$list = new RecursiveIteratorIterator($c->getComponents(), 1);
Assert::same([
'one',
'inner',
'inner2',
'button2',
'two',
'button1',
], array_keys(iterator_to_array($list)));


// Recursive
$list = $c->getComponents(deep: true);
Assert::same([
Expand Down

0 comments on commit 53693c3

Please sign in to comment.