protected function TreeRebuilder::treeSort in Entity Reference Hierarchy 3.x
Same name and namespace in other branches
- 8.2 src/Storage/TreeRebuilder.php \Drupal\entity_hierarchy\Storage\TreeRebuilder::treeSort()
Sorts tree.
Parameters
string $field_name: Field name of parent field.
array $records: Records to sort.
string $idKey: Field name of ID.
Return value
array Sorted records.
1 call to TreeRebuilder::treeSort()
- TreeRebuilder::getRebuildTasks in src/
Storage/ TreeRebuilder.php - Gets rebuild tasks suitable for usage with batch_set().
File
- src/
Storage/ TreeRebuilder.php, line 178
Class
- TreeRebuilder
- Defines a class for rebuilding the tree.
Namespace
Drupal\entity_hierarchy\StorageCode
protected function treeSort($field_name, array $records, $idKey) {
$items = [];
$weights = [];
$sets = [];
foreach ($records as $ix => $item) {
$parent = $item["{$field_name}_target_id"];
$sets[$parent][] = $item[$idKey];
$items[$item[$idKey]] = $parent;
}
// Add in root items.
foreach (array_keys($sets) as $parent) {
if (!isset($items[$parent])) {
$items[$parent] = 0;
$sets[0][] = $parent;
}
}
$flipped_sets = array_map(function (array $items) {
return array_flip($items);
}, $sets);
foreach ($items as $id => $parent) {
$flipped = $flipped_sets[$parent];
if (isset($weights[$id])) {
// We've already done this one via a child.
continue;
}
$weights[$id] = [
$flipped[$id],
];
if (!isset($weights[$parent]) && isset($items[$parent])) {
$this
->buildThread($weights, $items, $parent, $items[$parent], $flipped_sets);
}
if (isset($weights[$parent])) {
$weights[$id] = array_merge($weights[$parent], $weights[$id]);
}
}
$sorted = array_map(function (array $item) {
return [
'materialized_path' => implode('.', array_map([
Number::class,
'intToAlphadecimal',
], $item)),
];
}, $weights);
// Sort.
uasort($sorted, [
$this,
'sortItems',
]);
// Remove root items.
return array_diff_key($sorted, array_flip($sets[0]));
}