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?')); $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)) {
$visited[] = $cat['id'];
$node = [ $node = [
'id' => $cat['id'], 'id' => $cat['id'],
'name' => $cat['name'], 'name' => $cat['name'],
'children' => buildTree($categories, $items, $cat['id']), 'children' => buildTree($categories, $items, $cat['id'], $visited),
'items' => [] 'items' => []
]; ];
foreach ($items as $item) { foreach ($items as $item) {
@ -70,7 +72,11 @@ function buildTree($categories, $items, $parentId = null) {
} }
} }
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);