Passed
Push — master ( 86cfdb...e29dd4 )
by nguereza
03:59 queued 01:47
created

RoleAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
c 1
b 0
f 0
nc 1
nop 9
dl 0
loc 20
rs 9.9666

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Platine\App\Http\Action\Role;
6
7
use Exception;
8
use Platine\App\Helper\StatusList;
9
use Platine\App\Param\RoleParam;
10
use Platine\App\Validator\RoleValidator;
11
use Platine\Framework\Auth\Entity\Role;
12
use Platine\Framework\Auth\Repository\PermissionRepository;
13
use Platine\Framework\Auth\Repository\RoleRepository;
14
use Platine\Framework\Helper\Flash;
15
use Platine\Framework\Http\RequestData;
16
use Platine\Framework\Http\Response\RedirectResponse;
17
use Platine\Framework\Http\Response\TemplateResponse;
18
use Platine\Framework\Http\RouteHelper;
19
use Platine\Http\ResponseInterface;
20
use Platine\Http\ServerRequestInterface;
21
use Platine\Lang\Lang;
22
use Platine\Logger\LoggerInterface;
23
use Platine\Pagination\Pagination;
24
use Platine\Stdlib\Helper\Arr;
25
use Platine\Template\Template;
26
27
/**
28
* @class RoleAction
29
* @package Platine\App\Http\Action\Role
30
*/
31
class RoleAction
32
{
33
    /**
34
    * The Lang instance
35
    * @var Lang
36
    */
37
    protected Lang $lang;
38
39
    /**
40
    * The Pagination instance
41
    * @var Pagination
42
    */
43
    protected Pagination $pagination;
44
45
    /**
46
    * The Template instance
47
    * @var Template
48
    */
49
    protected Template $template;
50
51
    /**
52
    * The Flash instance
53
    * @var Flash
54
    */
55
    protected Flash $flash;
56
57
    /**
58
    * The RouteHelper instance
59
    * @var RouteHelper
60
    */
61
    protected RouteHelper $routeHelper;
62
63
    /**
64
    * The LoggerInterface instance
65
    * @var LoggerInterface
66
    */
67
    protected LoggerInterface $logger;
68
69
    /**
70
    * The PermissionRepository instance
71
    * @var PermissionRepository
72
    */
73
    protected PermissionRepository $permissionRepository;
74
75
    /**
76
    * The RoleRepository instance
77
    * @var RoleRepository
78
    */
79
    protected RoleRepository $roleRepository;
80
81
    /**
82
    * The StatusList instance
83
    * @var StatusList
84
    */
85
    protected StatusList $statusList;
86
87
    /**
88
    * Create new instance
89
    * @param Lang $lang
90
    * @param Pagination $pagination
91
    * @param Template $template
92
    * @param Flash $flash
93
    * @param RouteHelper $routeHelper
94
    * @param LoggerInterface $logger
95
    * @param PermissionRepository $permissionRepository
96
    * @param RoleRepository $roleRepository
97
    * @param StatusList $statusList
98
    */
99
    public function __construct(
100
        Lang $lang,
101
        Pagination $pagination,
102
        Template $template,
103
        Flash $flash,
104
        RouteHelper $routeHelper,
105
        LoggerInterface $logger,
106
        PermissionRepository $permissionRepository,
107
        RoleRepository $roleRepository,
108
        StatusList $statusList
109
    ) {
110
        $this->lang = $lang;
111
        $this->pagination = $pagination;
112
        $this->template = $template;
113
        $this->flash = $flash;
114
        $this->routeHelper = $routeHelper;
115
        $this->logger = $logger;
116
        $this->permissionRepository = $permissionRepository;
117
        $this->roleRepository = $roleRepository;
118
        $this->statusList = $statusList;
119
    }
120
121
    /**
122
    * List all entities
123
    * @param ServerRequestInterface $request
124
    * @return ResponseInterface
125
    */
126
    public function index(ServerRequestInterface $request): ResponseInterface
127
    {
128
        $context = [];
129
        $param = new RequestData($request);
130
        $totalItems = $this->roleRepository->query()
131
                                               ->count('id');
132
133
        $currentPage = (int) $param->get('page', 1);
134
135
        $this->pagination->setTotalItems($totalItems)
136
                        ->setCurrentPage($currentPage);
137
138
        $limit = $this->pagination->getItemsPerPage();
139
        $offset = $this->pagination->getOffset();
140
141
        $results = $this->roleRepository->query()
142
                                            ->offset($offset)
143
                                            ->limit($limit)
144
                                            ->orderBy('name', 'ASC')
145
                                            ->all();
146
147
        $context['list'] = $results;
148
        $context['pagination'] = $this->pagination->render();
149
150
151
        return new TemplateResponse(
152
            $this->template,
153
            'role/list',
154
            $context
155
        );
156
    }
157
158
    /**
159
    * List entity detail
160
    * @param ServerRequestInterface $request
161
    * @return ResponseInterface
162
    */
163
    public function detail(ServerRequestInterface $request): ResponseInterface
164
    {
165
        $context = [];
166
        $id = (int) $request->getAttribute('id');
167
168
        /** @var Role|null $role */
169
        $role = $this->roleRepository->find($id);
170
171
        if ($role === null) {
172
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
173
174
            return new RedirectResponse(
175
                $this->routeHelper->generateUrl('role_list')
176
            );
177
        }
178
        $context['role'] = $role;
179
        $context['user_status'] = $this->statusList->getUserStatus();
180
181
        return new TemplateResponse(
182
            $this->template,
183
            'role/detail',
184
            $context
185
        );
186
    }
187
188
    /**
189
    * Create new entity
190
    * @param ServerRequestInterface $request
191
    * @return ResponseInterface
192
    */
193
    public function create(ServerRequestInterface $request): ResponseInterface
194
    {
195
        $context = [];
196
        $param = new RequestData($request);
197
198
        $formParam = new RoleParam($param->posts());
199
        $context['param'] = $formParam;
200
201
        $permissions = $this->permissionRepository->orderBy('code')
202
                                                  ->all();
203
204
        $context['permissions'] = $permissions;
205
206
        if ($request->getMethod() === 'GET') {
207
            return new TemplateResponse(
208
                $this->template,
209
                'role/create',
210
                $context
211
            );
212
        }
213
214
        $validator = new RoleValidator($formParam, $this->lang);
215
        if ($validator->validate() === false) {
216
            $context['errors'] = $validator->getErrors();
217
218
            return new TemplateResponse(
219
                $this->template,
220
                'role/create',
221
                $context
222
            );
223
        }
224
225
        $entityExist = $this->roleRepository->findBy([
226
                                               'name' => $formParam->getName(),
227
                                           ]);
228
229
        if ($entityExist !== null) {
230
            $this->flash->setError($this->lang->tr('This record already exist'));
231
232
            return new TemplateResponse(
233
                $this->template,
234
                'role/create',
235
                $context
236
            );
237
        }
238
239
        /** @var Role $role */
240
        $role = $this->roleRepository->create([
241
           'name' => $formParam->getName(),
242
        'description' => $formParam->getDescription(),
243
        ]);
244
245
        $permissionsId = $formParam->getPermissions();
246
        if (count($permissionsId) > 0) {
247
            $selectedPermissions = $this->permissionRepository->findAll(...$permissionsId);
248
            $role->setPermissions($selectedPermissions);
249
        }
250
251
        try {
252
            $this->roleRepository->save($role);
253
254
            $this->flash->setSuccess($this->lang->tr('Data successfully created'));
255
256
            return new RedirectResponse(
257
                $this->routeHelper->generateUrl('role_list')
258
            );
259
        } catch (Exception $ex) {
260
            $this->logger->error('Error when saved the data {error}', ['error' => $ex->getMessage()]);
261
262
            $this->flash->setError($this->lang->tr('Data processing error'));
263
264
            return new TemplateResponse(
265
                $this->template,
266
                'role/create',
267
                $context
268
            );
269
        }
270
    }
271
272
    /**
273
    * Update existing entity
274
    * @param ServerRequestInterface $request
275
    * @return ResponseInterface
276
    */
277
    public function update(ServerRequestInterface $request): ResponseInterface
278
    {
279
        $context = [];
280
        $param = new RequestData($request);
281
282
        $id = (int) $request->getAttribute('id');
283
284
        /** @var Role|null $role */
285
        $role = $this->roleRepository->find($id);
286
287
        if ($role === null) {
288
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
289
290
            return new RedirectResponse(
291
                $this->routeHelper->generateUrl('role_list')
292
            );
293
        }
294
        $context['role'] = $role;
295
        $context['param'] = (new RoleParam())->fromEntity($role);
296
297
        $currentPermissionsId = Arr::getColumn($role->permissions, 'id');
298
        $context['param']->setPermissions($currentPermissionsId);
299
300
        $permissions = $this->permissionRepository->orderBy('code')
301
                                                  ->all();
302
303
        $context['permissions'] = $permissions;
304
305
        if ($request->getMethod() === 'GET') {
306
            return new TemplateResponse(
307
                $this->template,
308
                'role/update',
309
                $context
310
            );
311
        }
312
        $formParam = new RoleParam($param->posts());
313
        $context['param'] = $formParam;
314
315
        $validator = new RoleValidator($formParam, $this->lang);
316
        if ($validator->validate() === false) {
317
            $context['errors'] = $validator->getErrors();
318
319
            return new TemplateResponse(
320
                $this->template,
321
                'role/update',
322
                $context
323
            );
324
        }
325
326
        $entityExist = $this->roleRepository->findBy([
327
                                               'name' => $formParam->getName(),
328
                                           ]);
329
330
        if ($entityExist !== null && $entityExist->id !== $id) {
331
            $this->flash->setError($this->lang->tr('This record already exist'));
332
333
            return new TemplateResponse(
334
                $this->template,
335
                'role/update',
336
                $context
337
            );
338
        }
339
340
        $role->name = $formParam->getName();
341
        $role->description = $formParam->getDescription();
342
343
        $permissionsId = $formParam->getPermissions();
344
345
        //Delete Handle
346
        $permissionsIdToDelete = array_diff($currentPermissionsId, $permissionsId);
347
        if (count($permissionsIdToDelete) > 0) {
348
            $deletedPermissions = $this->permissionRepository->findAll(...$permissionsIdToDelete);
349
            $role->removePermissions($deletedPermissions);
350
        }
351
352
        //New Handle
353
        $permissionsIdToAdd = array_diff($permissionsId, $currentPermissionsId);
354
        if (count($permissionsIdToAdd) > 0) {
355
            $addedPermissions = $this->permissionRepository->findAll(...$permissionsIdToAdd);
356
            $role->setPermissions($addedPermissions);
357
        }
358
359
        try {
360
            $this->roleRepository->save($role);
361
362
            $this->flash->setSuccess($this->lang->tr('Data successfully updated'));
363
364
            return new RedirectResponse(
365
                $this->routeHelper->generateUrl('role_detail', ['id' => $id])
366
            );
367
        } catch (Exception $ex) {
368
            $this->logger->error('Error when saved the data {error}', ['error' => $ex->getMessage()]);
369
370
            $this->flash->setError($this->lang->tr('Data processing error'));
371
372
            return new TemplateResponse(
373
                $this->template,
374
                'role/update',
375
                $context
376
            );
377
        }
378
    }
379
380
    /**
381
    * Delete the entity
382
    * @param ServerRequestInterface $request
383
    * @return ResponseInterface
384
    */
385
    public function delete(ServerRequestInterface $request): ResponseInterface
386
    {
387
        $id = (int) $request->getAttribute('id');
388
389
        /** @var Role|null $role */
390
        $role = $this->roleRepository->find($id);
391
392
        if ($role === null) {
393
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
394
395
            return new RedirectResponse(
396
                $this->routeHelper->generateUrl('role_list')
397
            );
398
        }
399
400
        try {
401
            $this->roleRepository->delete($role);
402
403
            $this->flash->setSuccess($this->lang->tr('Data successfully deleted'));
404
405
            return new RedirectResponse(
406
                $this->routeHelper->generateUrl('role_list')
407
            );
408
        } catch (Exception $ex) {
409
            $this->logger->error('Error when delete the data {error}', ['error' => $ex->getMessage()]);
410
411
            $this->flash->setError($this->lang->tr('Data processing error'));
412
413
            return new RedirectResponse(
414
                $this->routeHelper->generateUrl('role_list')
415
            );
416
        }
417
    }
418
}
419