1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Hyde\Framework\Features\Navigation; |
6
|
|
|
|
7
|
|
|
use Illuminate\Support\Arr; |
8
|
|
|
use Illuminate\Support\Collection; |
9
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
10
|
|
|
|
11
|
|
|
use function Hyde\evaluate_arrayable; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Represents a site navigation menu, and contains all of its navigation items. |
15
|
|
|
* |
16
|
|
|
* The automatic navigation menus are stored within the service container and can be resolved by their identifiers. |
17
|
|
|
* |
18
|
|
|
* @example `$menu = app('navigation.main');` for the main navigation menu. |
19
|
|
|
* @example `$menu = app('navigation.sidebar');` for the documentation sidebar. |
20
|
|
|
* |
21
|
|
|
* @template T of NavigationItem|NavigationGroup |
22
|
|
|
*/ |
23
|
|
|
class NavigationMenu |
24
|
|
|
{ |
25
|
|
|
public const DEFAULT = 500; |
26
|
|
|
public const LAST = 999; |
27
|
|
|
|
28
|
|
|
/** @var \Illuminate\Support\Collection<array-key, T> */ |
29
|
|
|
protected Collection $items; |
30
|
|
|
|
31
|
|
|
/** @param \Illuminate\Contracts\Support\Arrayable<array-key, T>|array<T> $items */ |
32
|
|
|
public function __construct(Arrayable|array $items = []) |
33
|
|
|
{ |
34
|
|
|
$this->items = new Collection(); |
35
|
|
|
|
36
|
|
|
/** @var array<T> $items */ |
37
|
|
|
$items = evaluate_arrayable($items); |
38
|
|
|
|
39
|
|
|
$this->add($items); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Get the navigation items in the menu. |
44
|
|
|
* |
45
|
|
|
* Items are automatically sorted by their priority, falling back to the order they were added. |
46
|
|
|
* |
47
|
|
|
* @return \Illuminate\Support\Collection<array-key, T> |
48
|
|
|
*/ |
49
|
|
|
public function getItems(): Collection |
50
|
|
|
{ |
51
|
|
|
// The reason we sort them here is that navigation items can be added from different sources, |
52
|
|
|
// so any sorting we do in generator actions will only be partial. This way, we can ensure |
53
|
|
|
// that the items are always freshly sorted by their priorities when they are retrieved. |
54
|
|
|
|
55
|
|
|
return $this->items->sortBy(fn (NavigationItem|NavigationGroup $item) => $item->getPriority())->values(); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Add one or more navigation items to the navigation menu. |
60
|
|
|
* |
61
|
|
|
* @param T|array<T> $items |
62
|
|
|
*/ |
63
|
|
|
public function add(NavigationItem|NavigationGroup|array $items): static |
64
|
|
|
{ |
65
|
|
|
/** @var T $item */ |
66
|
|
|
foreach (Arr::wrap($items) as $item) { |
67
|
|
|
$this->addItem($item); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $this; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
protected function addItem(NavigationItem|NavigationGroup $item): void |
74
|
|
|
{ |
75
|
|
|
$this->items->push($item); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|