Completed
Push — master ( 5c55d7...79e99a )
by Fèvre
28s queued 15s
created

Permissions   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 243
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 67
c 1
b 0
f 0
dl 0
loc 243
rs 10
wmc 20

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getRowsQueryProperty() 0 6 1
A generateSlug() 0 3 1
A fireFlash() 0 26 6
A rules() 0 7 1
A render() 0 4 1
A makeBlankModel() 0 3 1
A getSelectedRowsQueryProperty() 0 5 1
A create() 0 10 2
A save() 0 10 2
A getRowsProperty() 0 4 1
A edit() 0 10 2
A mount() 0 3 1
1
<?php
2
3
namespace Xetaravel\Http\Livewire\Admin\Roles;
4
5
use Illuminate\Contracts\Database\Query\Builder;
6
use Illuminate\Contracts\View\View;
7
use Illuminate\Pagination\LengthAwarePaginator;
8
use Illuminate\Support\Str;
9
use Livewire\Component;
10
use Livewire\WithPagination;
11
use Xetaravel\Http\Livewire\Traits\WithCachedRows;
12
use Xetaravel\Http\Livewire\Traits\WithSorting;
13
use Xetaravel\Http\Livewire\Traits\WithBulkActions;
14
use Xetaravel\Http\Livewire\Traits\WithPerPagePagination;
15
use Xetaravel\Models\Permission;
16
17
class Permissions extends Component
18
{
19
    use WithPagination;
0 ignored issues
show
Bug introduced by
The trait Livewire\WithPagination requires the property $paginationTheme which is not provided by Xetaravel\Http\Livewire\Admin\Roles\Permissions.
Loading history...
20
    use WithSorting;
21
    use WithCachedRows;
22
    use WithBulkActions;
0 ignored issues
show
introduced by
The trait Xetaravel\Http\Livewire\Traits\WithBulkActions requires some properties which are not provided by Xetaravel\Http\Livewire\Admin\Roles\Permissions: $selectedRowsQuery, $rows, $rowsQuery
Loading history...
23
    use WithPerPagePagination;
0 ignored issues
show
Bug introduced by
The trait Xetaravel\Http\Livewire\...s\WithPerPagePagination requires the property $paginationTheme which is not provided by Xetaravel\Http\Livewire\Admin\Roles\Permissions.
Loading history...
24
25
    /**
26
     * The string to search.
27
     *
28
     * @var string
29
     */
30
    public string $search = '';
31
32
    /**
33
     * Used to update in URL the query string.
34
     *
35
     * @var string[]
36
     */
37
    protected $queryString = [
38
        'sortField' => ['as' => 'f'],
39
        'sortDirection' => ['as' => 'd'],
40
        'search' => ['except' => '', 'as' => 's']
41
    ];
42
43
    /**
44
     * The model used in the component.
45
     *
46
     * @var Permission
47
     */
48
    public Permission $model;
49
50
    /**
51
     * Used to show the Edit/Create modal.
52
     *
53
     * @var bool
54
     */
55
    public bool $showModal = false;
56
57
    /**
58
     * Used to show the delete modal.
59
     *
60
     * @var bool
61
     */
62
    public bool $showDeleteModal = false;
63
64
    /**
65
     * Used to set the modal to Create action (true) or Edit action (false).
66
     * @var bool
67
     */
68
    public bool $isCreating = false;
69
70
    /**
71
     * Number of rows displayed on a page.
72
     * @var int
73
     */
74
    public int $perPage = 10;
75
76
    /**
77
     * The Livewire Component constructor.
78
     *
79
     * @return void
80
     */
81
    public function mount(): void
82
    {
83
        $this->model = $this->makeBlankModel();
84
    }
85
86
    /**
87
     * Rules used for validating the model.
88
     *
89
     * @return string[]
90
     */
91
    public function rules()
92
    {
93
        return [
94
            'model.name' => 'required|min:5|max:30|unique:permissions,name,' . $this->model->id,
95
            'model.slug' => 'unique:permissions,slug,' . $this->model->id,
96
            'model.description' => 'required|min:5|max:150',
97
            'model.is_deletable' => 'required|boolean',
98
        ];
99
    }
100
101
    /**
102
     * Generate the slug from the `slugStrategy()` function and assign it to the model.
103
     *
104
     * @return void
105
     */
106
    public function generateSlug(): void
107
    {
108
        $this->model->slug = Str::slug($this->model->{$this->model->slugStrategy()}, config('roles.separator'));
0 ignored issues
show
Bug Best Practice introduced by
The property slug does not exist on Xetaravel\Models\Permission. Since you implemented __set, consider adding a @property annotation.
Loading history...
109
    }
110
111
    /**
112
     * Create a blank model and return it.
113
     *
114
     * @return Permission
115
     */
116
    public function makeBlankModel(): Permission
117
    {
118
        return Permission::make();
119
    }
120
121
    /**
122
     * Function to render the component.
123
     *
124
     * @return View
125
     */
126
    public function render()
127
    {
128
        return view('livewire.admin.roles.permissions', [
129
            'permissions' => $this->rows
0 ignored issues
show
Bug Best Practice introduced by
The property rows does not exist on Xetaravel\Http\Livewire\Admin\Roles\Permissions. Since you implemented __get, consider adding a @property annotation.
Loading history...
130
        ]);
131
    }
132
133
    /**
134
     * Create and return the query for the items.
135
     *
136
     * @return Builder
137
     */
138
    public function getRowsQueryProperty(): Builder
139
    {
140
        $query = Permission::query()
141
            ->search('name', $this->search);
142
143
        return $this->applySorting($query);
144
    }
145
146
    /**
147
     * Build the query or get it from the cache and paginate it.
148
     *
149
     * @return LengthAwarePaginator
150
     */
151
    public function getRowsProperty(): LengthAwarePaginator
152
    {
153
        return $this->cache(function () {
154
            return $this->applyPagination($this->rowsQuery);
0 ignored issues
show
Bug Best Practice introduced by
The property rowsQuery does not exist on Xetaravel\Http\Livewire\Admin\Roles\Permissions. Since you implemented __get, consider adding a @property annotation.
Loading history...
155
        });
156
    }
157
158
    /**
159
     * Create a blank model and assign it to the model. (Used in create modal)
160
     *
161
     * @return void
162
     */
163
    public function create(): void
164
    {
165
        $this->isCreating = true;
166
        $this->useCachedRows();
167
168
        // Reset the model to a blank model before showing the creating modal.
169
        if ($this->model->getKey()) {
170
            $this->model = $this->makeBlankModel();
171
        }
172
        $this->showModal = true;
173
    }
174
175
    /**
176
     * Set the model (used in modal) to the permission we want to edit.
177
     *
178
     * @param Permission $permission The permission id to update.
179
     * (Livewire will automatically fetch the model by the id)
180
     *
181
     * @return void
182
     */
183
    public function edit(Permission $permission): void
184
    {
185
        $this->isCreating = false;
186
        $this->useCachedRows();
187
188
        // Set the model to the permission we want to edit.
189
        if ($this->model->isNot($permission)) {
190
            $this->model = $permission;
191
        }
192
        $this->showModal = true;
193
    }
194
195
    /**
196
     * Validate and save the model.
197
     *
198
     * @return void
199
     */
200
    public function save(): void
201
    {
202
        $this->validate();
203
204
        if ($this->model->save()) {
205
            $this->fireFlash('save', 'success');
206
        } else {
207
            $this->fireFlash('save', 'danger');
208
        }
209
        $this->showModal = false;
210
    }
211
212
    /**
213
     * Display a flash message regarding the action that fire it and the type of the message, then emit an
214
     * `alert ` event.
215
     *
216
     * @param string $action The action that fire the flash message.
217
     * @param string $type The type of the message, success or danger.
218
     * @param int $deleteCount If set, the number of permissions that has been deleted.
219
     *
220
     * @return void
221
     */
222
    public function fireFlash(string $action, string $type, int $deleteCount = 0)
223
    {
224
        switch ($action) {
225
            case 'save':
226
                if ($type == 'success') {
227
                    session()->flash(
228
                        'success',
229
                        $this->isCreating ? "The permission has been created successfully !" :
230
                            "The permission <b>{$this->model->title}</b> has been edited successfully !"
0 ignored issues
show
Bug Best Practice introduced by
The property title does not exist on Xetaravel\Models\Permission. Since you implemented __get, consider adding a @property annotation.
Loading history...
231
                    );
232
                } else {
233
                    session()->flash('danger', "An error occurred while saving the permission !");
234
                }
235
                break;
236
237
            case 'delete':
238
                if ($type == 'success') {
239
                    session()->flash('success', "<b>{$deleteCount}</b> permissions has been deleted successfully !");
240
                } else {
241
                    session()->flash('danger', "An error occurred while deleting the permissions !");
242
                }
243
                break;
244
        }
245
246
        // Emit the alert event to the front so the DIsmiss can trigger the flash message.
247
        $this->emit('alert');
248
    }
249
250
    /**
251
     * Get all select rows that are deletable by their id, preparing for deleting them.
252
     *
253
     * @return mixed
254
     */
255
    public function getSelectedRowsQueryProperty()
256
    {
257
        return (clone $this->rowsQuery)
0 ignored issues
show
Bug Best Practice introduced by
The property rowsQuery does not exist on Xetaravel\Http\Livewire\Admin\Roles\Permissions. Since you implemented __get, consider adding a @property annotation.
Loading history...
258
            ->unless($this->selectAll, fn($query) => $query->whereKey($this->selected))
259
            ->where('is_deletable', '=', true);
260
    }
261
}
262