Passed
Push — master ( 32a4a2...da9bd5 )
by Caen
04:12 queued 14s
created

NavigationMenu::generate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Framework\Features\Navigation;
6
7
use Hyde\Facades\Config;
8
use Hyde\Support\Models\Route;
9
use Hyde\Pages\DocumentationPage;
10
use BadMethodCallException;
11
12
/**
13
 * @see \Hyde\Framework\Testing\Feature\NavigationMenuTest
14
 */
15
class NavigationMenu extends BaseNavigationMenu
16
{
17
    protected function generate(): void
18
    {
19
        parent::generate();
20
21
        if ($this->dropdownsEnabled()) {
22
            $this->moveGroupedItemsIntoDropdowns();
23
        }
24
    }
25
26
    public function hasDropdowns(): bool
27
    {
28
        return $this->dropdownsEnabled() && count($this->getDropdowns()) >= 1;
29
    }
30
31
    /** @return array<string, DropdownNavItem> */
32
    public function getDropdowns(): array
33
    {
34
        if (! $this->dropdownsEnabled()) {
35
            throw new BadMethodCallException('Dropdowns are not enabled. Enable it by setting `hyde.navigation.subdirectories` to `dropdown`.');
36
        }
37
38
        return $this->items->filter(function (NavItem $item): bool {
39
            return $item instanceof DropdownNavItem;
40
        })->values()->all();
41
    }
42
43
    protected function moveGroupedItemsIntoDropdowns(): void
44
    {
45
        $dropdowns = [];
46
47
        foreach ($this->items as $key => $item) {
48
            if ($this->canAddItemToDropdown($item)) {
49
                // Buffer the item in the dropdowns array
50
                $dropdowns[$item->getGroup()][] = $item;
51
52
                // Remove the item from the main items collection
53
                $this->items->forget($key);
54
            }
55
        }
56
57
        foreach ($dropdowns as $group => $items) {
58
            // Create a new dropdown item containing the buffered items
59
            $this->items->add(new DropdownNavItem($group, $items));
60
        }
61
    }
62
63
    protected function canAddRoute(Route $route): bool
64
    {
65
        return parent::canAddRoute($route) && (! $route->getPage() instanceof DocumentationPage || $route->is(DocumentationPage::homeRouteName()));
66
    }
67
68
    protected function canAddItemToDropdown(NavItem $item): bool
69
    {
70
        return $item->getGroup() !== null;
71
    }
72
73
    protected function dropdownsEnabled(): bool
74
    {
75
        return Config::getString('hyde.navigation.subdirectories', 'hidden') === 'dropdown';
76
    }
77
}
78