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

Categories   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 230
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 64
dl 0
loc 230
rs 10
c 1
b 0
f 0
wmc 19

11 Methods

Rating   Name   Duplication   Size   Complexity  
A mount() 0 4 1
A save() 0 10 2
A getRowsQueryProperty() 0 6 1
A render() 0 4 1
A fireFlash() 0 26 6
A makeBlankModel() 0 3 1
A getRowsProperty() 0 4 1
A create() 0 10 2
A rules() 0 6 1
A edit() 0 10 2
A generateSlug() 0 3 1
1
<?php
2
3
namespace Xetaravel\Http\Livewire\Admin\Blog;
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\Category;
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\Blog\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\Blog\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\Blog\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 Category
47
     */
48
    public Category $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
        $this->perPage = config('xetaravel.pagination.blog.article_per_page');
85
    }
86
87
    /**
88
     * Rules used for validating the model.
89
     *
90
     * @return string[]
91
     */
92
    public function rules()
93
    {
94
        return [
95
            'model.title' => 'required|min:5',
96
            'model.slug' => 'unique:categories,slug,' . $this->model->id,
97
            'model.description' => 'required|min:10'
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()});
109
    }
110
111
    /**
112
     * Create a blank model and return it.
113
     *
114
     * @return Category
115
     */
116
    public function makeBlankModel(): Category
117
    {
118
        return Category::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.blog.categories', [
129
            'categories' => $this->rows
0 ignored issues
show
Bug Best Practice introduced by
The property rows does not exist on Xetaravel\Http\Livewire\Admin\Blog\Categories. 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 = Category::query()
141
            ->search('title', $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\Blog\Categories. 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 category we want to edit.
177
     *
178
     * @param Category $category The category id to update. (Livewire will automatically fetch the model by the id)
179
     *
180
     * @return void
181
     */
182
    public function edit(Category $category): void
183
    {
184
        $this->isCreating = false;
185
        $this->useCachedRows();
186
187
        // Set the model to the category we want to edit.
188
        if ($this->model->isNot($category)) {
189
            $this->model = $category;
190
        }
191
        $this->showModal = true;
192
    }
193
194
    /**
195
     * Validate and save the model.
196
     *
197
     * @return void
198
     */
199
    public function save(): void
200
    {
201
        $this->validate();
202
203
        if ($this->model->save()) {
204
            $this->fireFlash('save', 'success');
205
        } else {
206
            $this->fireFlash('save', 'danger');
207
        }
208
        $this->showModal = false;
209
    }
210
211
    /**
212
     * Display a flash message regarding the action that fire it and the type of the message, then emit an
213
     * `alert ` event.
214
     *
215
     * @param string $action The action that fire the flash message.
216
     * @param string $type The type of the message, success or danger.
217
     * @param int $deleteCount If set, the number of categories that has been deleted.
218
     *
219
     * @return void
220
     */
221
    public function fireFlash(string $action, string $type, int $deleteCount = 0)
222
    {
223
        switch ($action) {
224
            case 'save':
225
                if ($type == 'success') {
226
                    session()->flash(
227
                        'success',
228
                        $this->isCreating ? "The category has been created successfully !" :
229
                            "The category <b>{$this->model->title}</b> has been edited successfully !"
230
                    );
231
                } else {
232
                    session()->flash('danger', "An error occurred while saving the category !");
233
                }
234
                break;
235
236
            case 'delete':
237
                if ($type == 'success') {
238
                    session()->flash('success', "<b>{$deleteCount}</b> categories has been deleted successfully !");
239
                } else {
240
                    session()->flash('danger', "An error occurred while deleting the categories !");
241
                }
242
                break;
243
        }
244
245
        // Emit the alert event to the front so the DIsmiss can trigger the flash message.
246
        $this->emit('alert');
247
    }
248
}
249