flatListGenerator($this->buildChildrenHashmap(parent::hydrateAllData())))); } private function flatListGenerator(array $hashMap, ?object $parent = null): Generator { $parent = null === $parent ? null : spl_object_id($parent); $hashMap += [$parent => []]; foreach ($hashMap[$parent] as $node) { yield spl_object_id($node) => $node; yield from $this->flatListGenerator($hashMap, $node); } } private function buildChildrenHashmap(array $nodes): array { return array_reduce( $nodes, static function (array $collect, $node): array { $parentId = (null === $parent = $node->getParent()) ? null : spl_object_id($parent); $collect[$parentId][] = $node; return $collect; }, [] ); } }