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()))));
}
private function flatListGenerator(array $hashMap, $parent = null): Generator
private function flatListGenerator(array $hashMap, ?int $parent = null): Generator
{
$parent = null === $parent ?
null :
spl_object_hash($parent);
$parent ??= spl_object_id($parent);
$hashMap += [$parent => []];
foreach ($hashMap[$parent] as $node) {
yield $node->getId() => $node;
yield spl_object_id($node) => $node;
yield from $this->flatListGenerator($hashMap, $node);
}
}
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) {
$parentId = (null !== $parent = $node->getParent())
? spl_object_hash($parent)
: null;
$collect[$parentId][] = $node;
$r[$parentId][] = $node;
}
return $r;
return $collect;
},
[]
);
}
}