diff --git a/config.php b/config.php index 399aa48..7beda22 100755 --- a/config.php +++ b/config.php @@ -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?')); // 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) { - $tree = []; - foreach ($categories as $cat) { - if ($cat['parent_id'] == $parentId) { - $node = [ - 'id' => $cat['id'], - 'name' => $cat['name'], - 'children' => buildTree($categories, $items, $cat['id']), - 'items' => [] - ]; - foreach ($items as $item) { - if ($item['category_id'] == $cat['id']) { - $node['items'][] = $item; + function buildTree($categories, $items, $parentId = null, &$visited = []) { + $tree = []; + foreach ($categories as $cat) { + 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'], $visited), + 'items' => [] + ]; + foreach ($items as $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);