Passed
Push — tailwind ( 4c0702...098cf6 )
by Fèvre
05:11
created

Categories::getRowsQueryProperty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
namespace Xetaravel\Http\Livewire\Admin\Discuss;
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\DiscussCategory;
16
17
class Categories 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\Discuss\Categories.
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\Discuss\Categories: $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\Discuss\Categories.
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 DiscussCategory
47
     */
48
    public DiscussCategory $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 color of the category displayed in the modal in realtime.
78
     *
79
     * @var string
80
     */
81
    public $color = '#dddddd';
82
83
    /**
84
     * The Livewire Component constructor.
85
     *
86
     * @return void
87
     */
88
    public function mount(): void
89
    {
90
        $this->model = $this->makeBlankModel();
91
        $this->perPage = config('xetaravel.pagination.blog.article_per_page');
92
    }
93
94
    /**
95
     * Rules used for validating the model.
96
     *
97
     * @return string[]
98
     */
99
    public function rules()
100
    {
101
        return [
102
            'model.title' => 'required|min:5',
103
            'model.slug' => 'unique:discuss_categories,title,' . $this->model->id,
104
            'model.description' => 'required|min:10',
105
            'model.color' => 'min:7|max:9',
106
            'model.icon' => 'required',
107
            'model.level' => 'required|integer',
108
            'model.is_locked' => 'required|boolean',
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()});
120
    }
121
122
    public function generateColor(): void
123
    {
124
        $this->color = $this->model->color;
125
    }
126
127
    /**
128
     * Create a blank model and return it.
129
     *
130
     * @return DiscussCategory
131
     */
132
    public function makeBlankModel(): DiscussCategory
133
    {
134
        return DiscussCategory::make();
135
    }
136
137
    /**
138
     * Function to render the component.
139
     *
140
     * @return View
141
     */
142
    public function render()
143
    {
144
        return view('livewire.admin.discuss.categories', [
145
            'categories' => $this->rows
0 ignored issues
show
Bug Best Practice introduced by
The property rows does not exist on Xetaravel\Http\Livewire\Admin\Discuss\Categories. Since you implemented __get, consider adding a @property annotation.
Loading history...
146
        ]);
147
    }
148
149
    /**
150
     * Create and return the query for the items.
151
     *
152
     * @return Builder
153
     */
154
    public function getRowsQueryProperty(): Builder
155
    {
156
        $query = DiscussCategory::query()
157
            ->search('title', $this->search);
158
159
        return $this->applySorting($query);
160
    }
161
162
    /**
163
     * Build the query or get it from the cache and paginate it.
164
     *
165
     * @return LengthAwarePaginator
166
     */
167
    public function getRowsProperty(): LengthAwarePaginator
168
    {
169
        return $this->cache(function () {
170
            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\Discuss\Categories. Since you implemented __get, consider adding a @property annotation.
Loading history...
171
        });
172
    }
173
174
    /**
175
     * Create a blank model and assign it to the model. (Used in create modal)
176
     *
177
     * @return void
178
     */
179
    public function create(): void
180
    {
181
        $this->isCreating = true;
182
        $this->useCachedRows();
183
184
        // Reset the model to a blank model before showing the creating modal.
185
        if ($this->model->getKey()) {
186
            $this->model = $this->makeBlankModel();
187
            $this->color = '#dddddd';
188
        }
189
        $this->showModal = true;
190
    }
191
192
    /**
193
     * Set the model (used in modal) to the category we want to edit.
194
     *
195
     * @param DiscussCategory $category The category id to update.
196
     * (Livewire will automatically fetch the model by the id)
197
     *
198
     * @return void
199
     */
200
    public function edit(DiscussCategory $category): void
201
    {
202
        $this->isCreating = false;
203
        $this->useCachedRows();
204
205
        // Set the model to the category we want to edit.
206
        if ($this->model->isNot($category)) {
207
            $this->model = $category;
208
            $this->color = $category->color;
209
        }
210
        $this->showModal = true;
211
    }
212
213
    /**
214
     * Validate and save the model.
215
     *
216
     * @return void
217
     */
218
    public function save(): void
219
    {
220
        $this->validate();
221
222
        if ($this->model->save()) {
223
            $this->fireFlash('save', 'success');
224
        } else {
225
            $this->fireFlash('save', 'danger');
226
        }
227
        $this->showModal = false;
228
    }
229
230
    /**
231
     * Display a flash message regarding the action that fire it and the type of the message, then emit an
232
     * `alert ` event.
233
     *
234
     * @param string $action The action that fire the flash message.
235
     * @param string $type The type of the message, success or danger.
236
     * @param int $deleteCount If set, the number of categories that has been deleted.
237
     *
238
     * @return void
239
     */
240
    public function fireFlash(string $action, string $type, int $deleteCount = 0)
241
    {
242
        switch ($action) {
243
            case 'save':
244
                if ($type == 'success') {
245
                    session()->flash(
246
                        'success',
247
                        $this->isCreating ? "The category has been created successfully !" :
248
                            "The category <b>{$this->model->title}</b> has been edited successfully !"
249
                    );
250
                } else {
251
                    session()->flash('danger', "An error occurred while saving the category !");
252
                }
253
                break;
254
255
            case 'delete':
256
                if ($type == 'success') {
257
                    session()->flash('success', "<b>{$deleteCount}</b> categories has been deleted successfully !");
258
                } else {
259
                    session()->flash('danger', "An error occurred while deleting the categories !");
260
                }
261
                break;
262
        }
263
264
        // Emit the alert event to the front so the DIsmiss can trigger the flash message.
265
        $this->emit('alert');
266
    }
267
}
268