Improve performance.

This commit is contained in:
Pol Dellaiera 2021-07-10 07:50:15 +02:00
parent b33cb4946c
commit cc824faf54

View File

@ -16,33 +16,33 @@ final class FlatHierarchyEntityHydrator extends ObjectHydrator
return array_values(iterator_to_array($this->flatListGenerator($this->buildChildrenHashmap(parent::hydrateAllData())))); return array_values(iterator_to_array($this->flatListGenerator($this->buildChildrenHashmap(parent::hydrateAllData()))));
} }
private function flatListGenerator(array $hashMap, $parent = null): Generator private function flatListGenerator(array $hashMap, ?int $parent = null): Generator
{ {
$parent = null === $parent ? $parent ??= spl_object_id($parent);
null :
spl_object_hash($parent);
$hashMap += [$parent => []]; $hashMap += [$parent => []];
foreach ($hashMap[$parent] as $node) { foreach ($hashMap[$parent] as $node) {
yield $node->getId() => $node; yield spl_object_id($node) => $node;
yield from $this->flatListGenerator($hashMap, $node); yield from $this->flatListGenerator($hashMap, $node);
} }
} }
private function buildChildrenHashmap(array $nodes): array private function buildChildrenHashmap(array $nodes): array
{ {
$r = []; return array_reduce(
$nodes,
static function (array $collect, $node) {
$parentId = (null === $parent = $node->getParent()) ?
null :
spl_object_id($parent);
foreach ($nodes as $node) { $collect[$parentId][] = $node;
$parentId = (null !== $parent = $node->getParent())
? spl_object_hash($parent)
: null;
$r[$parentId][] = $node; return $collect;
} },
[]
return $r; );
} }
} }