CategoryAction::index()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 20
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 29
rs 9.6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Platine\App\Http\Action\Product;
6
7
use Exception;
8
use Platine\Http\ResponseInterface;
9
use Platine\Http\ServerRequestInterface;
10
use Platine\Framework\Http\RequestData;
11
use Platine\Framework\Http\Response\TemplateResponse;
12
use Platine\Framework\Http\Response\RedirectResponse;
13
use Platine\Lang\Lang;
14
use Platine\Pagination\Pagination;
15
use Platine\Template\Template;
16
use Platine\Framework\Helper\Flash;
17
use Platine\Framework\Http\RouteHelper;
18
use Platine\Logger\LoggerInterface;
19
use Platine\App\Model\Repository\ProductCategoryRepository;
20
use Platine\App\Model\Entity\ProductCategory;
21
use Platine\App\Param\ProductCategoryParam;
22
use Platine\App\Validator\ProductCategoryValidator;
23
24
/**
25
* @class CategoryAction
26
* @package Platine\App\Http\Action\Product
27
*/
28
class CategoryAction
29
{
30
    /**
31
    * Create new instance
32
    * @param Lang $lang
33
    * @param Pagination $pagination
34
    * @param Template $template
35
    * @param Flash $flash
36
    * @param RouteHelper $routeHelper
37
    * @param LoggerInterface $logger
38
    * @param ProductCategoryRepository $productCategoryRepository
39
    */
40
    public function __construct(
41
        protected Lang $lang,
42
        protected Pagination $pagination,
43
        protected Template $template,
44
        protected Flash $flash,
45
        protected RouteHelper $routeHelper,
46
        protected LoggerInterface $logger,
47
        protected ProductCategoryRepository $productCategoryRepository
48
    ) {
49
    }
50
51
    /**
52
    * List all entities
53
    * @param ServerRequestInterface $request
54
    * @return ResponseInterface
55
    */
56
    public function index(ServerRequestInterface $request): ResponseInterface
57
    {
58
        $context = [];
59
        $param = new RequestData($request);
60
        $totalItems = $this->productCategoryRepository->query()
61
                                               ->count('id');
62
63
        $currentPage = (int) $param->get('page', 1);
64
65
        $this->pagination->setTotalItems($totalItems)
66
                        ->setCurrentPage($currentPage);
67
68
        $limit = $this->pagination->getItemsPerPage();
69
        $offset = $this->pagination->getOffset();
70
71
        $results = $this->productCategoryRepository->query()
72
                                            ->offset($offset)
73
                                            ->limit($limit)
74
                                            ->orderBy('name', 'ASC')
75
                                            ->all();
76
77
        $context['list'] = $results;
78
        $context['pagination'] = $this->pagination->render();
79
80
81
        return new TemplateResponse(
82
            $this->template,
83
            'product/category/list',
84
            $context
85
        );
86
    }
87
88
    /**
89
    * List entity detail
90
    * @param ServerRequestInterface $request
91
    * @return ResponseInterface
92
    */
93
    public function detail(ServerRequestInterface $request): ResponseInterface
94
    {
95
        $context = [];
96
        $id = (int) $request->getAttribute('id');
97
98
        /** @var ProductCategory|null $category */
99
        $category = $this->productCategoryRepository->find($id);
100
101
        if ($category === null) {
102
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
103
104
            return new RedirectResponse(
105
                $this->routeHelper->generateUrl('product_category_list')
106
            );
107
        }
108
        $context['category'] = $category;
109
110
        return new TemplateResponse(
111
            $this->template,
112
            'product/category/detail',
113
            $context
114
        );
115
    }
116
117
    /**
118
    * Create new entity
119
    * @param ServerRequestInterface $request
120
    * @return ResponseInterface
121
    */
122
    public function create(ServerRequestInterface $request): ResponseInterface
123
    {
124
        $context = [];
125
        $param = new RequestData($request);
126
127
        $formParam = new ProductCategoryParam($param->posts());
128
        $context['param'] = $formParam;
129
130
        if ($request->getMethod() === 'GET') {
131
            return new TemplateResponse(
132
                $this->template,
133
                'product/category/create',
134
                $context
135
            );
136
        }
137
138
        $validator = new ProductCategoryValidator($formParam, $this->lang);
139
        if ($validator->validate() === false) {
140
            $context['errors'] = $validator->getErrors();
141
142
            return new TemplateResponse(
143
                $this->template,
144
                'product/category/create',
145
                $context
146
            );
147
        }
148
149
        $entityExist = $this->productCategoryRepository->findBy([
150
                                               'name' => $formParam->getName(),
151
                                           ]);
152
153
        if ($entityExist !== null) {
154
            $this->flash->setError($this->lang->tr('This record already exist'));
155
156
            return new TemplateResponse(
157
                $this->template,
158
                'product/category/create',
159
                $context
160
            );
161
        }
162
163
        /** @var ProductCategory $category */
164
        $category = $this->productCategoryRepository->create([
165
           'name' => $formParam->getName(),
166
        'description' => $formParam->getDescription(),
167
        ]);
168
169
        try {
170
            $this->productCategoryRepository->save($category);
171
172
            $this->flash->setSuccess($this->lang->tr('Data successfully created'));
173
174
            return new RedirectResponse(
175
                $this->routeHelper->generateUrl('product_category_list')
176
            );
177
        } catch (Exception $ex) {
178
            $this->logger->error('Error when saved the data {error}', ['error' => $ex->getMessage()]);
179
180
            $this->flash->setError($this->lang->tr('Data processing error'));
181
182
            return new TemplateResponse(
183
                $this->template,
184
                'product/category/create',
185
                $context
186
            );
187
        }
188
    }
189
190
    /**
191
    * Update existing entity
192
    * @param ServerRequestInterface $request
193
    * @return ResponseInterface
194
    */
195
    public function update(ServerRequestInterface $request): ResponseInterface
196
    {
197
        $context = [];
198
        $param = new RequestData($request);
199
200
        $id = (int) $request->getAttribute('id');
201
202
        /** @var ProductCategory|null $category */
203
        $category = $this->productCategoryRepository->find($id);
204
205
        if ($category === null) {
206
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
207
208
            return new RedirectResponse(
209
                $this->routeHelper->generateUrl('product_category_list')
210
            );
211
        }
212
        $context['category'] = $category;
213
        $context['param'] = (new ProductCategoryParam())->fromEntity($category);
214
        if ($request->getMethod() === 'GET') {
215
            return new TemplateResponse(
216
                $this->template,
217
                'product/category/update',
218
                $context
219
            );
220
        }
221
        $formParam = new ProductCategoryParam($param->posts());
222
        $context['param'] = $formParam;
223
224
        $validator = new ProductCategoryValidator($formParam, $this->lang);
225
        if ($validator->validate() === false) {
226
            $context['errors'] = $validator->getErrors();
227
228
            return new TemplateResponse(
229
                $this->template,
230
                'product/category/update',
231
                $context
232
            );
233
        }
234
235
        $entityExist = $this->productCategoryRepository->findBy([
236
                                               'name' => $formParam->getName(),
237
                                           ]);
238
239
        if ($entityExist !== null && $entityExist->id !== $id) {
240
            $this->flash->setError($this->lang->tr('This record already exist'));
241
242
            return new TemplateResponse(
243
                $this->template,
244
                'product/category/update',
245
                $context
246
            );
247
        }
248
249
        $category->name = $formParam->getName();
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on Platine\App\Model\Entity\ProductCategory. Since you implemented __set, consider adding a @property annotation.
Loading history...
250
        $category->description = $formParam->getDescription();
0 ignored issues
show
Bug Best Practice introduced by
The property description does not exist on Platine\App\Model\Entity\ProductCategory. Since you implemented __set, consider adding a @property annotation.
Loading history...
251
252
        try {
253
            $this->productCategoryRepository->save($category);
254
255
            $this->flash->setSuccess($this->lang->tr('Data successfully updated'));
256
257
            return new RedirectResponse(
258
                $this->routeHelper->generateUrl('product_category_detail', ['id' => $id])
259
            );
260
        } catch (Exception $ex) {
261
            $this->logger->error('Error when saved the data {error}', ['error' => $ex->getMessage()]);
262
263
            $this->flash->setError($this->lang->tr('Data processing error'));
264
265
            return new TemplateResponse(
266
                $this->template,
267
                'product/category/update',
268
                $context
269
            );
270
        }
271
    }
272
273
    /**
274
    * Delete the entity
275
    * @param ServerRequestInterface $request
276
    * @return ResponseInterface
277
    */
278
    public function delete(ServerRequestInterface $request): ResponseInterface
279
    {
280
        $id = (int) $request->getAttribute('id');
281
282
        /** @var ProductCategory|null $category */
283
        $category = $this->productCategoryRepository->find($id);
284
285
        if ($category === null) {
286
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
287
288
            return new RedirectResponse(
289
                $this->routeHelper->generateUrl('product_category_list')
290
            );
291
        }
292
293
        try {
294
            $this->productCategoryRepository->delete($category);
295
296
            $this->flash->setSuccess($this->lang->tr('Data successfully deleted'));
297
298
            return new RedirectResponse(
299
                $this->routeHelper->generateUrl('product_category_list')
300
            );
301
        } catch (Exception $ex) {
302
            $this->logger->error('Error when delete the data {error}', ['error' => $ex->getMessage()]);
303
304
            $this->flash->setError($this->lang->tr('Data processing error'));
305
306
            return new RedirectResponse(
307
                $this->routeHelper->generateUrl('product_category_list')
308
            );
309
        }
310
    }
311
}
312