75 lines
2.1 KiB
PHP
Executable File
75 lines
2.1 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
class NavbarService
|
|
{
|
|
/**
|
|
* Build a hierarchical tree of nav items grouped by parent_id.
|
|
*
|
|
* @param array $items
|
|
* @return array
|
|
*/
|
|
public function buildTree(array $items): array
|
|
{
|
|
$normalized = array_map([$this, 'normalizeItem'], $items);
|
|
$grouped = [];
|
|
|
|
foreach ($normalized as $item) {
|
|
$parentId = $this->castParentId($item['parent_id'] ?? null);
|
|
$grouped[$parentId][] = $item;
|
|
}
|
|
|
|
$buildLevel = function ($parentId) use (&$grouped, &$buildLevel) {
|
|
if (!isset($grouped[$parentId])) {
|
|
return [];
|
|
}
|
|
|
|
$children = $grouped[$parentId];
|
|
usort($children, fn ($a, $b) => ($a['order'] ?? 0) <=> ($b['order'] ?? 0));
|
|
|
|
return array_map(function ($child) use ($buildLevel) {
|
|
$child['children'] = $buildLevel($child['id']);
|
|
return $child;
|
|
}, $children);
|
|
};
|
|
|
|
return $buildLevel(null);
|
|
}
|
|
|
|
private function normalizeItem($item): array
|
|
{
|
|
if (is_object($item)) {
|
|
$item = (array) $item;
|
|
}
|
|
|
|
return [
|
|
'id' => (int) ($item['id'] ?? 0),
|
|
'label' => (string) ($item['label'] ?? ''),
|
|
'url' => $item['url'] ?? '',
|
|
'icon' => $item['icon'] ?? $item['icon_class'] ?? null,
|
|
'parent_id' => $item['parent_id'] ?? $item['menu_parent_id'] ?? null,
|
|
'order' => (int) ($item['order'] ?? $item['sort_order'] ?? 0),
|
|
'is_enabled'=> (bool) ($item['is_enabled'] ?? true),
|
|
];
|
|
}
|
|
|
|
private function castParentId($value): ?int
|
|
{
|
|
if ($value === null || $value === '') {
|
|
return null;
|
|
}
|
|
|
|
return (int) $value;
|
|
}
|
|
|
|
/**
|
|
* Clear navigation cache (placeholder for future caching implementation)
|
|
*/
|
|
public function clearCache(): void
|
|
{
|
|
// TODO: Implement cache clearing if caching is added
|
|
// For now, this is a no-op to maintain compatibility
|
|
}
|
|
}
|