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

PermissionAction::create()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 70
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 43
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 70
rs 8.9208

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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