forked from CuyZ/Valinor
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: introduce helper
NodeTraverser
for recursive operations on nodes
- Loading branch information
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace CuyZ\Valinor\Mapper\Tree; | ||
|
||
/** | ||
* @template T | ||
*/ | ||
final class NodeTraverser | ||
{ | ||
/** @var callable(Node): T */ | ||
private $callback; | ||
|
||
/** | ||
* @param callable(Node): T $callback | ||
*/ | ||
public function __construct(callable $callback) | ||
{ | ||
$this->callback = $callback; | ||
} | ||
|
||
/** | ||
* @return iterable<T> | ||
*/ | ||
public function traverse(Node $node): iterable | ||
{ | ||
return $this->recurse($node); | ||
} | ||
|
||
/** | ||
* @return iterable<T> | ||
*/ | ||
private function recurse(Node $node): iterable | ||
{ | ||
yield ($this->callback)($node); | ||
|
||
foreach ($node->children() as $child) { | ||
yield from $this->recurse($child); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace CuyZ\Valinor\Tests\Unit\Mapper\Tree; | ||
|
||
use CuyZ\Valinor\Mapper\Tree\Node; | ||
use CuyZ\Valinor\Mapper\Tree\NodeTraverser; | ||
use CuyZ\Valinor\Tests\Fake\Mapper\FakeNode; | ||
use PHPUnit\Framework\TestCase; | ||
|
||
final class NodeTraverserTest extends TestCase | ||
{ | ||
public function test_nodes_are_visited(): void | ||
{ | ||
$node = FakeNode::branch([ | ||
'foo' => [], | ||
'bar' => [], | ||
]); | ||
|
||
$visited = [...(new NodeTraverser( | ||
fn (Node $node) => $node | ||
))->traverse($node)]; | ||
|
||
self::assertContains($node, $visited); | ||
self::assertContains($node->children()['foo'], $visited); | ||
self::assertContains($node->children()['bar'], $visited); | ||
} | ||
} |