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,30 +47,36 @@ $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?')); $twig->addGlobal('delete_category_confirm', $translator->trans('Are you sure you want to delete this category?'));
// Build category tree for sidebar // Build category tree for sidebar
$db = App\Database\Database::getInstance(); try {
$categories = App\Models\Category::getAll($db); $db = App\Database\Database::getInstance();
$items = App\Models\Item::getAll($db); $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 = []; $tree = [];
foreach ($categories as $cat) { foreach ($categories as $cat) {
if ($cat['parent_id'] == $parentId) { if ($cat['parent_id'] == $parentId && !in_array($cat['id'], $visited)) {
$node = [ $visited[] = $cat['id'];
'id' => $cat['id'], $node = [
'name' => $cat['name'], 'id' => $cat['id'],
'children' => buildTree($categories, $items, $cat['id']), 'name' => $cat['name'],
'items' => [] 'children' => buildTree($categories, $items, $cat['id'], $visited),
]; 'items' => []
foreach ($items as $item) { ];
if ($item['category_id'] == $cat['id']) { foreach ($items as $item) {
$node['items'][] = $item; if ($item['category_id'] == $cat['id']) {
$node['items'][] = $item;
}
} }
$tree[] = $node;
} }
$tree[] = $node;
} }
return $tree;
} }
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); $twig->addGlobal('category_tree', $categoryTree);