Fix category tree building to prevent infinite recursion on circular references

This commit is contained in:
Edwin Noorlander 2025-11-12 08:37:50 +01:00
parent 5549c67eb5
commit 7c5ecd4b9b

View File

@ -47,18 +47,20 @@ $twig->addGlobal('delete_part_confirm', $translator->trans('Are you sure you wan
$twig->addGlobal('delete_category_confirm', $translator->trans('Are you sure you want to delete this category?'));
// Build category tree for sidebar
$db = App\Database\Database::getInstance();
$categories = App\Models\Category::getAll($db);
$items = App\Models\Item::getAll($db);
try {
$db = App\Database\Database::getInstance();
$categories = App\Models\Category::getAll($db);
$items = App\Models\Item::getAll($db);
function buildTree($categories, $items, $parentId = null) {
function buildTree($categories, $items, $parentId = null, &$visited = []) {
$tree = [];
foreach ($categories as $cat) {
if ($cat['parent_id'] == $parentId) {
if ($cat['parent_id'] == $parentId && !in_array($cat['id'], $visited)) {
$visited[] = $cat['id'];
$node = [
'id' => $cat['id'],
'name' => $cat['name'],
'children' => buildTree($categories, $items, $cat['id']),
'children' => buildTree($categories, $items, $cat['id'], $visited),
'items' => []
];
foreach ($items as $item) {
@ -70,7 +72,11 @@ function buildTree($categories, $items, $parentId = null) {
}
}
return $tree;
}
}
$categoryTree = buildTree($categories, $items);
$categoryTree = buildTree($categories, $items);
} catch (Exception $e) {
error_log('Error building category tree: ' . $e->getMessage());
$categoryTree = [];
}
$twig->addGlobal('category_tree', $categoryTree);