|
4 | 4 |
|
5 | 5 | namespace Hyde\Framework\Features\Navigation; |
6 | 6 |
|
| 7 | +use Illuminate\Support\Arr; |
7 | 8 | use Illuminate\Support\Collection; |
8 | 9 | use Illuminate\Contracts\Support\Arrayable; |
9 | 10 |
|
|
19 | 20 | */ |
20 | 21 | class NavigationMenu |
21 | 22 | { |
22 | | - use HasNavigationItems; |
23 | | - |
24 | 23 | public const DEFAULT = 500; |
25 | 24 | public const LAST = 999; |
26 | 25 |
|
| 26 | + /** @var \Illuminate\Support\Collection<\Hyde\Framework\Features\Navigation\NavigationItem|\Hyde\Framework\Features\Navigation\NavigationGroup> */ |
| 27 | + protected Collection $items; |
| 28 | + |
27 | 29 | public function __construct(Arrayable|array $items = []) |
28 | 30 | { |
29 | 31 | $this->items = new Collection(); |
30 | 32 |
|
31 | 33 | $this->add(evaluate_arrayable($items)); |
32 | 34 | } |
| 35 | + |
| 36 | + /** |
| 37 | + * Get the navigation items in the menu. |
| 38 | + * |
| 39 | + * Items are automatically sorted by their priority, falling back to the order they were added. |
| 40 | + * |
| 41 | + * @return \Illuminate\Support\Collection<\Hyde\Framework\Features\Navigation\NavigationItem|\Hyde\Framework\Features\Navigation\NavigationGroup> |
| 42 | + */ |
| 43 | + public function getItems(): Collection |
| 44 | + { |
| 45 | + // The reason we sort them here is that navigation items can be added from different sources, |
| 46 | + // so any sorting we do in generator actions will only be partial. This way, we can ensure |
| 47 | + // that the items are always freshly sorted by their priorities when they are retrieved. |
| 48 | + |
| 49 | + return $this->items->sortBy(fn (NavigationItem|NavigationGroup $item) => $item->getPriority())->values(); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Add one or more navigation items to the navigation menu. |
| 54 | + * |
| 55 | + * @param \Hyde\Framework\Features\Navigation\NavigationItem|\Hyde\Framework\Features\Navigation\NavigationGroup|array<\Hyde\Framework\Features\Navigation\NavigationItem|\Hyde\Framework\Features\Navigation\NavigationGroup> $items |
| 56 | + */ |
| 57 | + public function add(NavigationItem|NavigationGroup|array $items): static |
| 58 | + { |
| 59 | + foreach (Arr::wrap($items) as $item) { |
| 60 | + $this->addItem($item); |
| 61 | + } |
| 62 | + |
| 63 | + return $this; |
| 64 | + } |
| 65 | + |
| 66 | + protected function addItem(NavigationItem|NavigationGroup $item): void |
| 67 | + { |
| 68 | + $this->items->push($item); |
| 69 | + } |
33 | 70 | } |
0 commit comments