From cc1bc66bbece7f79dfec093e33e96d3e31bca4e9 Mon Sep 17 00:00:00 2001 From: Romain Canon Date: Fri, 31 Dec 2021 16:10:55 +0100 Subject: [PATCH] feat: introduce helper `NodeTraverser` for recursive operations on nodes --- src/Mapper/Tree/NodeTraverser.php | 42 ++++++++++++++++++++ tests/Unit/Mapper/Tree/NodeTraverserTest.php | 29 ++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 src/Mapper/Tree/NodeTraverser.php create mode 100644 tests/Unit/Mapper/Tree/NodeTraverserTest.php diff --git a/src/Mapper/Tree/NodeTraverser.php b/src/Mapper/Tree/NodeTraverser.php new file mode 100644 index 00000000..448fdb22 --- /dev/null +++ b/src/Mapper/Tree/NodeTraverser.php @@ -0,0 +1,42 @@ +callback = $callback; + } + + /** + * @return iterable + */ + public function traverse(Node $node): iterable + { + return $this->recurse($node); + } + + /** + * @return iterable + */ + private function recurse(Node $node): iterable + { + yield ($this->callback)($node); + + foreach ($node->children() as $child) { + yield from $this->recurse($child); + } + } +} diff --git a/tests/Unit/Mapper/Tree/NodeTraverserTest.php b/tests/Unit/Mapper/Tree/NodeTraverserTest.php new file mode 100644 index 00000000..6ed4c1d3 --- /dev/null +++ b/tests/Unit/Mapper/Tree/NodeTraverserTest.php @@ -0,0 +1,29 @@ + [], + '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); + } +}