Passed
Push — 0.3 ( a188cc...3c900f )
by Philippe
27:26
created

Menu::label()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Thinktomorrow\Chief\Menu;
5
6
use Illuminate\Support\Collection;
7
8
class Menu
9
{
10
    /** @var string */
11
    private $key;
12
13
    /** @var string */
14
    private $label;
15
16
    /** @var string */
17
    private $view_path;
18
19 4
    public function __construct(string $key, string $label, string $view_path)
20
    {
21 4
        $this->label = $label;
22 4
        $this->view_path = $view_path;
23 4
        $this->key = $key;
24 4
    }
25
26 4
    public static function all(): Collection
27
    {
28 4
        $types = config('thinktomorrow.chief.menus', []);
29
30
        return collect($types)->map(function ($menu, $key) {
31 4
            return new static($key, $menu['label'], $menu['view']);
32 4
        });
33
    }
34
35 2
    public static function find($key): ?self
36
    {
37
        return static::all()->filter(function ($menu) use ($key) {
38 2
            return $menu->key() == $key;
39 2
        })->first();
40
    }
41
42 3
    public function key()
43
    {
44 3
        return $this->key;
45
    }
46
47 3
    public function label()
48
    {
49 3
        return $this->label;
50
    }
51
52
    public function viewPath()
53
    {
54
        return $this->view_path;
55
    }
56
57
    public function menu(): ChiefMenu
58
    {
59
        return ChiefMenu::fromMenuItems($this->key);
60
    }
61
62
    public function items()
63
    {
64
        return $this->menu()->items();
65
    }
66
67
    public function render()
68
    {
69
        if (view()->exists($this->view_path)) {
70
            return view($this->view_path, [
71
                'menu' => $this,
72
            ])->render();
73
        }
74
75
        if (file_exists($this->view_path)) {
76
            return file_get_contents($this->view_path);
77
        }
78
79
        return $this->fallbackRender();
80
    }
81
82
    private function fallbackRender()
83
    {
84
        $menu = [];
85
86
        $this->items()->each(function ($item) use (&$menu) {
87
            $menu[] = sprintf('<li><a href="%s">%s</a></li>', $item->url, $item->label);
88
        });
89
90
        return '<ul>'.implode('', $menu).'</ul>';
91
    }
92
}
93