Test Setup Failed
Push — ft/command-palette ( 46b036...db4959 )
by
unknown
14:31 queued 17s
created

searchThroughAdminPages()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 51
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 29
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 51
rs 9.456

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Thinktomorrow\Chief\App\Http\Controllers\Back\CommandPalette;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Support\Str;
7
use Thinktomorrow\Chief\App\Http\Controllers\Controller;
8
use Thinktomorrow\Chief\Managers\Register\Registry;
9
10
class CommandPaletteController extends Controller
11
{
12
    public function __construct()
13
    {
14
        $this->pageModels = $this->getAllPageModels();
0 ignored issues
show
Bug Best Practice introduced by
The property pageModels does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
15
    }
16
17
    public function search(string $term = '')
18
    {
19
        $lowercaseTerm = Str::lower($term);
20
21
        // Is it possible to generate results based on visitable routes,
22
        // instead of getting models and keeping a static list of admin pages?
23
        $results = [
24
            ...$this->searchThroughPageModels($lowercaseTerm),
25
            ...$this->searchThroughAdminPages($lowercaseTerm),
26
        ];
27
28
        return response()->view('chief::layout.nav.command-palette._result', [
29
            'term' => $term,
30
            'results' => $results,
31
        ]);
32
    }
33
34
    public function searchThroughPageModels($term)
35
    {
36
        $results = [];
37
38
        foreach ($this->pageModels as $modelGroup) {
39
            $resultGroup = [];
40
41
            foreach ($modelGroup['models'] as $model) {
42
                if (
43
                    Str::contains(Str::lower($model->modelReference()), $term) ||
44
                    Str::contains(Str::lower($model->adminConfig()->getModelName()), $term) ||
45
                    Str::contains(Str::lower($model->adminConfig()->getIndexTitle()), $term) ||
46
                    Str::contains(Str::lower($model->adminConfig()->getNavTitle()), $term) ||
47
                    Str::contains(Str::lower($model->adminConfig()->getPageTitle()), $term) ||
48
                    Str::contains(Str::lower($model->title ?? ''), $term)
49
                ) {
50
                    $resultGroup[$model->modelReference()->getShort()] = [
51
                        'label' => $model->title,
52
                        'url' => '/admin/' . $model->managedModelKey() . '/' . $model->id . '/edit',
53
                    ];
54
                }
55
            }
56
57
            if (count($resultGroup) !== 0) {
58
                $firstModel = $modelGroup['models']->first();
59
60
                // Add model index page to result group
61
                array_push($resultGroup, [
62
                    'label' => ucfirst($modelGroup['label']) . ' overzicht',
63
                    'url' => '/admin/' . $firstModel->managedModelKey(),
64
                ]);
65
66
                // Add result group to search results
67
                array_push($results, [
68
                    'label' => $modelGroup['label'],
69
                    'results' => $resultGroup,
70
                ]);
71
            }
72
        }
73
74
        return $results;
75
    }
76
77
    public function searchThroughAdminPages($term)
78
    {
79
        // Can we generate this in a different way, or move these out of this method
80
        $adminPages = collect([
81
            [ 'label' => 'Dashboard', 'url' => route('chief.back.dashboard'), 'permission' => null, 'tags' => ['home'], ],
82
            [ 'label' => 'Menu', 'url' => route('chief.back.menus.index'), 'permission' => 'update-page', 'tags' => ['navigatie'], ],
83
            [ 'label' => 'Media', 'url' => route('chief.mediagallery.index'), 'permission' => 'update-page', 'tags' => ['mediagalerij', 'mediabibliotheek', 'assets'], ],
84
            [ 'label' => 'Teksten', 'url' => route('squanto.index'), 'permission' => 'view-squanto', 'tags' => ['squanto', 'mediagalerij', 'mediabibliotheek', 'assets'], ],
85
            [ 'label' => 'Sitemap', 'url' => route('chief.back.sitemap.show'), 'permission' => null, 'tags' => [], ],
86
            [ 'label' => 'Admins', 'url' => route('chief.back.users.index'), 'permission' => 'view-user', 'tags' => [], ],
87
            [ 'label' => 'Rechten', 'url' => route('chief.back.roles.index'), 'permission' => 'view-role', 'tags' => ['roles'], ],
88
            [ 'label' => 'Settings', 'url' => route('chief.back.settings.edit'), 'permission' => 'update-setting', 'tags' => ['instellingen'], ],
89
            [ 'label' => 'Audit', 'url' => route('chief.back.audit.index'), 'permission' => 'view-audit', 'tags' => [], ],
90
            [ 'label' => chiefAdmin()->firstname, 'url' => route('chief.back.you.edit'), 'permission' => 'update-you', 'tags' => ['account'], ],
0 ignored issues
show
Bug introduced by
Accessing firstname on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
91
            [ 'label' => 'Logout', 'url' => route('chief.back.logout'), 'permission' => null, 'tags' => [], ],
92
        ]);
93
94
        $results = $adminPages->filter(function ($adminPage) use ($term) {
95
            // TODO: check if current user has necessary permissions to view page
96
            // if(! chiefAdmin()->hasPermissionTo($adminPage['permission'])) {
97
            //     return false;
98
            // }
99
100
            // Check if label contains search term
101
            if (Str::contains(Str::lower($adminPage['label']), $term)) {
102
                return true;
103
            }
104
105
            // Check if any of tags contain search term
106
            if (collect($adminPage['tags'])->contains(function ($tag) use ($term) {
107
                return Str::contains(Str::lower($tag), $term);
108
            })) {
109
                return true;
110
            };
111
112
            return false;
113
        })->map(function ($adminPage) {
114
            return [
115
                'label' => $adminPage['label'],
116
                'url' => $adminPage['url'],
117
            ];
118
        })->toArray();
119
120
        if (count($results) === 0) {
121
            return [];
122
        }
123
124
        return [
125
            [
126
                'label' => 'Admin',
127
                'results' => $results,
128
            ],
129
        ];
130
    }
131
132
    private function getAllPageModels(): Collection
133
    {
134
        return collect(app(Registry::class)->models())
135
            // Filter out fragment models
136
            ->filter(function ($model) {
137
                return ! in_array('Thinktomorrow\Chief\Fragments\Fragmentable', class_implements($model));
138
                // Return all instances of the models
139
            })->map(function ($model) {
140
                $models = $model::all();
141
142
                return [
143
                    'label' => $model::make()->adminConfig()->getIndexTitle(),
144
                    'models' => $models,
145
                ];
146
            });
147
    }
148
}
149