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

Roles::fireFlash()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 17
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 26
rs 9.0777
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
use Xetaravel\Models\Role;
17
18
class Roles extends Component
19
{
20
    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\Roles.
Loading history...
21
    use WithSorting;
22
    use WithCachedRows;
23
    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\Roles: $selectedRowsQuery, $rows, $rowsQuery
Loading history...
24
    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\Roles.
Loading history...
25
26
    /**
27
     * The string to search.
28
     *
29
     * @var string
30
     */
31
    public string $search = '';
32
33
    /**
34
     * Used to update in URL the query string.
35
     *
36
     * @var string[]
37
     */
38
    protected $queryString = [
39
        'sortField' => ['as' => 'f'],
40
        'sortDirection' => ['as' => 'd'],
41
        'search' => ['except' => '', 'as' => 's']
42
    ];
43
44
    /**
45
     * The model used in the component.
46
     *
47
     * @var Role
48
     */
49
    public Role $model;
50
51
    /**
52
     * Used to show the Edit/Create modal.
53
     *
54
     * @var bool
55
     */
56
    public bool $showModal = false;
57
58
    /**
59
     * Used to show the delete modal.
60
     *
61
     * @var bool
62
     */
63
    public bool $showDeleteModal = false;
64
65
    /**
66
     * Used to set the modal to Create action (true) or Edit action (false).
67
     * @var bool
68
     */
69
    public bool $isCreating = false;
70
71
    /**
72
     * Number of rows displayed on a page.
73
     * @var int
74
     */
75
    public int $perPage = 10;
76
77
    /**
78
     * The selected permissions for the editing role or the new role.
79
     *
80
     * @var array
81
     */
82
    public array $permissionsSelected = [];
83
84
    /**
85
     * The Livewire Component constructor.
86
     *
87
     * @return void
88
     */
89
    public function mount(): void
90
    {
91
        $this->model = $this->makeBlankModel();
92
    }
93
94
    /**
95
     * Rules used for validating the model.
96
     *
97
     * @return string[]
98
     */
99
    public function rules()
100
    {
101
        return [
102
            'model.name' => 'required|min:2|max:20|unique:roles,name,' . $this->model->id,
103
            'model.slug' => 'unique:roles,slug,' . $this->model->id,
104
            'model.description' => 'required|min:5|max:150',
105
            'model.level' => 'required|integer',
106
            'model.css' => 'string',
107
            'model.is_deletable' => 'required|boolean',
108
            'permissionsSelected' => 'required'
109
        ];
110
    }
111
112
    /**
113
     * Generate the slug from the `slugStrategy()` function and assign it to the model.
114
     *
115
     * @return void
116
     */
117
    public function generateSlug(): void
118
    {
119
        $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\Role. Since you implemented __set, consider adding a @property annotation.
Loading history...
120
    }
121
122
    /**
123
     * Create a blank model and return it.
124
     *
125
     * @return Role
126
     */
127
    public function makeBlankModel(): Role
128
    {
129
        return Role::make();
130
    }
131
132
    /**
133
     * Function to render the component.
134
     *
135
     * @return View
136
     */
137
    public function render()
138
    {
139
        return view('livewire.admin.roles.roles', [
140
            'roles' => $this->rows,
0 ignored issues
show
Bug Best Practice introduced by
The property rows does not exist on Xetaravel\Http\Livewire\Admin\Roles\Roles. Since you implemented __get, consider adding a @property annotation.
Loading history...
141
            'permissions' => Permission::pluck('name', 'id')->toArray()
142
        ]);
143
    }
144
145
    /**
146
     * Create and return the query for the items.
147
     *
148
     * @return Builder
149
     */
150
    public function getRowsQueryProperty(): Builder
151
    {
152
        $query = Role::query()
153
            ->search('name', $this->search);
154
155
        return $this->applySorting($query);
156
    }
157
158
    /**
159
     * Build the query or get it from the cache and paginate it.
160
     *
161
     * @return LengthAwarePaginator
162
     */
163
    public function getRowsProperty(): LengthAwarePaginator
164
    {
165
        return $this->cache(function () {
166
            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\Roles. Since you implemented __get, consider adding a @property annotation.
Loading history...
167
        });
168
    }
169
170
    /**
171
     * Create a blank model and assign it to the model. (Used in create modal)
172
     *
173
     * @return void
174
     */
175
    public function create(): void
176
    {
177
        $this->isCreating = true;
178
        $this->useCachedRows();
179
180
        // Reset the model to a blank model before showing the creating modal.
181
        if ($this->model->getKey()) {
182
            $this->model = $this->makeBlankModel();
183
            $this->permissionsSelected = [];
184
        }
185
        $this->showModal = true;
186
    }
187
188
    /**
189
     * Set the model (used in modal) to the role we want to edit.
190
     *
191
     * @param Role $role The role id to update.
192
     * (Livewire will automatically fetch the model by the id)
193
     *
194
     * @return void
195
     */
196
    public function edit(Role $role): void
197
    {
198
        $this->isCreating = false;
199
        $this->useCachedRows();
200
201
        // Set the model to the role we want to edit and set the related permissions.
202
        if ($this->model->isNot($role)) {
203
            $this->model = $role;
204
            $this->permissionsSelected = $role->permissions->pluck('id')->toArray();
0 ignored issues
show
Bug introduced by
The method pluck() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

204
            $this->permissionsSelected = $role->permissions->/** @scrutinizer ignore-call */ pluck('id')->toArray();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug Best Practice introduced by
The property permissions does not exist on Xetaravel\Models\Role. Since you implemented __get, consider adding a @property annotation.
Loading history...
205
        }
206
        $this->showModal = true;
207
    }
208
209
    /**
210
     * Validate and save the model.
211
     *
212
     * @return void
213
     */
214
    public function save(): void
215
    {
216
        $this->validate();
217
218
        if ($this->model->save()) {
219
            $this->model->syncPermissions($this->permissionsSelected);
220
221
            $this->fireFlash('save', 'success');
222
        } else {
223
            $this->fireFlash('save', 'danger');
224
        }
225
        $this->showModal = false;
226
    }
227
228
    /**
229
     * Display a flash message regarding the action that fire it and the type of the message, then emit an
230
     * `alert ` event.
231
     *
232
     * @param string $action The action that fire the flash message.
233
     * @param string $type The type of the message, success or danger.
234
     * @param int $deleteCount If set, the number of roles that has been deleted.
235
     *
236
     * @return void
237
     */
238
    public function fireFlash(string $action, string $type, int $deleteCount = 0)
239
    {
240
        switch ($action) {
241
            case 'save':
242
                if ($type == 'success') {
243
                    session()->flash(
244
                        'success',
245
                        $this->isCreating ? "The role has been created successfully !" :
246
                            "The role <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\Role. Since you implemented __get, consider adding a @property annotation.
Loading history...
247
                    );
248
                } else {
249
                    session()->flash('danger', "An error occurred while saving the role !");
250
                }
251
                break;
252
253
            case 'delete':
254
                if ($type == 'success') {
255
                    session()->flash('success', "<b>{$deleteCount}</b> roles has been deleted successfully !");
256
                } else {
257
                    session()->flash('danger', "An error occurred while deleting the roles !");
258
                }
259
                break;
260
        }
261
262
        // Emit the alert event to the front so the DIsmiss can trigger the flash message.
263
        $this->emit('alert');
264
    }
265
266
    /**
267
     * Get all select rows that are deletable by their id, preparing for deleting them.
268
     *
269
     * @return mixed
270
     */
271
    public function getSelectedRowsQueryProperty()
272
    {
273
        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\Roles. Since you implemented __get, consider adding a @property annotation.
Loading history...
274
            ->unless($this->selectAll, fn($query) => $query->whereKey($this->selected))
275
            ->where('is_deletable', '=', true);
276
    }
277
}
278