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

Settings::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;
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 Illuminate\Validation\Rule;
10
use Livewire\Component;
11
use Livewire\WithPagination;
12
use Xetaravel\Http\Livewire\Traits\WithCachedRows;
13
use Xetaravel\Http\Livewire\Traits\WithSorting;
14
use Xetaravel\Http\Livewire\Traits\WithBulkActions;
15
use Xetaravel\Http\Livewire\Traits\WithPerPagePagination;
16
use Xetaravel\Models\Setting;
17
18
class Settings 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\Settings.
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\Settings: $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\Settings.
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 Setting
48
     */
49
    public Setting $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
    public string $slug = '';
78
79
    public $type = 'value_bool';
80
    public $value = '';
81
82
    /**
83
     * The Livewire Component constructor.
84
     *
85
     * @return void
86
     */
87
    public function mount(): void
88
    {
89
        $this->model = $this->makeBlankModel();
90
    }
91
92
    /**
93
     * Rules used for validating the model.
94
     *
95
     * @return string[]
96
     */
97
    public function rules()
98
    {
99
        return [
100
            'model.name' => 'required|min:5|max:30|unique:settings,name,' . $this->model->id,
101
            'value' => 'required',
102
            'type' => 'required|in:' . collect(Setting::TYPES)->keys()->implode(','),
0 ignored issues
show
Bug introduced by
Xetaravel\Models\Setting::TYPES of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

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

102
            'type' => 'required|in:' . collect(/** @scrutinizer ignore-type */ Setting::TYPES)->keys()->implode(','),
Loading history...
103
            'model.description' => 'required|min:5|max:150',
104
            'model.is_deletable' => 'required|boolean',
105
        ];
106
    }
107
108
    /**
109
     * Create a blank model and return it.
110
     *
111
     * @return Setting
112
     */
113
    public function makeBlankModel(): Setting
114
    {
115
        return Setting::make();
116
    }
117
118
    /**
119
     * Generate the slug from the name and assign it to the slug variable.
120
     *
121
     * @return void
122
     */
123
    public function generateName(): void
124
    {
125
        $this->slug = Str::slug($this->model->name, '.');
0 ignored issues
show
Bug introduced by
It seems like $this->model->name can also be of type Illuminate\Database\Eloq...uent\Relations\Relation and Illuminate\Database\Eloq...uent\Relations\Relation and Illuminate\Database\Eloq...elations\HasManyThrough and Illuminate\Database\Eloq...Relations\HasOneThrough and Illuminate\Database\Eloquent\Relations\Relation; however, parameter $title of Illuminate\Support\Str::slug() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

125
        $this->slug = Str::slug(/** @scrutinizer ignore-type */ $this->model->name, '.');
Loading history...
Bug Best Practice introduced by
The property name does not exist on Xetaravel\Models\Setting. Since you implemented __get, consider adding a @property annotation.
Loading history...
126
    }
127
128
    /**
129
     * Function to render the component.
130
     *
131
     * @return View
132
     */
133
    public function render()
134
    {
135
        return view('livewire.admin.settings', [
136
            'settings' => $this->rows
0 ignored issues
show
Bug Best Practice introduced by
The property rows does not exist on Xetaravel\Http\Livewire\Admin\Settings. Since you implemented __get, consider adding a @property annotation.
Loading history...
137
        ]);
138
    }
139
140
    /**
141
     * Create and return the query for the items.
142
     *
143
     * @return Builder
144
     */
145
    public function getRowsQueryProperty(): Builder
146
    {
147
        $query = Setting::query()
148
            ->search('name', $this->search);
149
150
        return $this->applySorting($query);
151
    }
152
153
    /**
154
     * Build the query or get it from the cache and paginate it.
155
     *
156
     * @return LengthAwarePaginator
157
     */
158
    public function getRowsProperty(): LengthAwarePaginator
159
    {
160
        return $this->cache(function () {
161
            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\Settings. Since you implemented __get, consider adding a @property annotation.
Loading history...
162
        });
163
    }
164
165
    /**
166
     * Create a blank model and assign it to the model. (Used in create modal)
167
     *
168
     * @return void
169
     */
170
    public function create(): void
171
    {
172
        $this->isCreating = true;
173
        $this->useCachedRows();
174
175
        // Reset the model to a blank model before showing the creating modal.
176
        if ($this->model->getKey()) {
177
            $this->model = $this->makeBlankModel();
178
            $this->value = '';
179
            $this->type = 'value_bool';
180
            //Reset the slug too.
181
            $this->generateName();
182
        }
183
        $this->showModal = true;
184
    }
185
186
    /**
187
     * Set the model (used in modal) to the setting we want to edit.
188
     *
189
     * @param Setting $setting The setting id to update.
190
     * (Livewire will automatically fetch the model by the id)
191
     *
192
     * @return void
193
     */
194
    public function edit(Setting $setting): void
195
    {
196
        $this->isCreating = false;
197
        $this->useCachedRows();
198
199
        // Set the model to the setting we want to edit.
200
        if ($this->model->isNot($setting)) {
201
            $this->model = $setting;
202
            $this->type = $this->model->type;
203
            $this->value = $this->model->value;
0 ignored issues
show
Bug Best Practice introduced by
The property value does not exist on Xetaravel\Models\Setting. Since you implemented __get, consider adding a @property annotation.
Loading history...
204
            $this->generateName();
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->model->name = $this->slug;
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on Xetaravel\Models\Setting. Since you implemented __set, consider adding a @property annotation.
Loading history...
217
218
        $this->validate();
219
        $this->model = Setting::castValue($this->value, $this->type, $this->model);
220
221
        unset($this->model->type, $this->model->value);
0 ignored issues
show
Bug Best Practice introduced by
The property value does not exist on Xetaravel\Models\Setting. Since you implemented __get, consider adding a @property annotation.
Loading history...
222
223
        if ($this->model->save()) {
224
            $this->fireFlash('save', 'success');
225
        } else {
226
            $this->fireFlash('save', 'danger');
227
        }
228
        $this->showModal = false;
229
    }
230
231
    /**
232
     * Display a flash message regarding the action that fire it and the type of the message, then emit an
233
     * `alert ` event.
234
     *
235
     * @param string $action The action that fire the flash message.
236
     * @param string $type The type of the message, success or danger.
237
     * @param int $deleteCount If set, the number of rows that has been deleted.
238
     *
239
     * @return void
240
     */
241
    public function fireFlash(string $action, string $type, int $deleteCount = 0)
242
    {
243
        switch ($action) {
244
            case 'save':
245
                if ($type == 'success') {
246
                    session()->flash(
247
                        'success',
248
                        $this->isCreating ? "The setting has been created successfully !" :
249
                            "The setting <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\Setting. Since you implemented __get, consider adding a @property annotation.
Loading history...
250
                    );
251
                } else {
252
                    session()->flash('danger', "An error occurred while saving the setting !");
253
                }
254
                break;
255
256
            case 'delete':
257
                if ($type == 'success') {
258
                    session()->flash('success', "<b>{$deleteCount}</b> settings has been deleted successfully !");
259
                } else {
260
                    session()->flash('danger', "An error occurred while deleting the settings !");
261
                }
262
                break;
263
        }
264
265
        // Emit the alert event to the front so the DIsmiss can trigger the flash message.
266
        $this->emit('alert');
267
    }
268
269
    /**
270
     * Get all select rows that are deletable by their id, preparing for deleting them.
271
     *
272
     * @return mixed
273
     */
274
    public function getSelectedRowsQueryProperty()
275
    {
276
        return (clone $this->rowsQuery)
0 ignored issues
show
Bug Best Practice introduced by
The property rowsQuery does not exist on Xetaravel\Http\Livewire\Admin\Settings. Since you implemented __get, consider adding a @property annotation.
Loading history...
277
            ->unless($this->selectAll, fn($query) => $query->whereKey($this->selected))
278
            ->where('is_deletable', '=', true);
279
    }
280
}
281