Passed
Push — master ( a77e6b...67a175 )
by Caen
13:07 queued 12s
created

NavigationMenu::canBeInDropdown()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
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->createDropdownsForGroupedItems();
23
        }
24
    }
25
26
    public function hasDropdowns(): bool
27
    {
28
        if (! $this->dropdownsEnabled()) {
29
            return false;
30
        }
31
32
        return count($this->getDropdowns()) >= 1;
33
    }
34
35
    /** @return array<string, DropdownNavItem> */
36
    public function getDropdowns(): array
37
    {
38
        if (! $this->dropdownsEnabled()) {
39
            throw new BadMethodCallException('Dropdowns are not enabled. Enable it by setting `hyde.navigation.subdirectories` to `dropdown`.');
40
        }
41
42
        return $this->items->filter(function (NavItem $item): bool {
43
            return $item instanceof DropdownNavItem;
44
        })->values()->all();
45
    }
46
47
    protected function createDropdownsForGroupedItems(): void
48
    {
49
        $dropdowns = [];
50
51
        /** @var \Hyde\Framework\Features\Navigation\NavItem $item */
52
        foreach ($this->items as $key => $item) {
53
            if ($this->canAddItemToDropdown($item)) {
54
                // Buffer the item in the dropdowns array
55
                $dropdowns[$item->getGroup()][] = $item;
56
57
                // Remove the item from the main items collection
58
                $this->items->forget($key);
59
            }
60
        }
61
62
        foreach ($dropdowns as $group => $items) {
63
            // Create a new dropdown item containing the buffered items
64
            $this->items->add(new DropdownNavItem($group, $items));
65
        }
66
    }
67
68
    protected function canAddRoute(Route $route): bool
69
    {
70
        return parent::canAddRoute($route) && (! $route->getPage() instanceof DocumentationPage || $route->is(DocumentationPage::homeRouteName()));
71
    }
72
73
    protected function canAddItemToDropdown(NavItem $item): bool
74
    {
75
        return $item->getGroup() !== null;
76
    }
77
78
    protected function dropdownsEnabled(): bool
79
    {
80
        return Config::getString('hyde.navigation.subdirectories', 'hidden') === 'dropdown';
81
    }
82
}
83