PermissionAction::delete()   A
last analyzed

Complexity

Conditions 3
Paths 5

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 16
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 30
rs 9.7333
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
    * 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 PermissionRepository $permissionRepository
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 PermissionRepository $permissionRepository
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->permissionRepository->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->permissionRepository->query()
72
                                            ->offset($offset)
73
                                            ->limit($limit)
74
                                            ->orderBy('code', 'ASC')
75
                                            ->all();
76
77
        $context['list'] = $results;
78
        $context['pagination'] = $this->pagination->render();
79
80
81
        return new TemplateResponse(
82
            $this->template,
83
            'permission/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 Permission|null $permission */
99
        $permission = $this->permissionRepository->find($id);
100
101
        if ($permission === null) {
102
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
103
104
            return new RedirectResponse(
105
                $this->routeHelper->generateUrl('permission_list')
106
            );
107
        }
108
        $context['permission'] = $permission;
109
110
        return new TemplateResponse(
111
            $this->template,
112
            'permission/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 PermissionParam($param->posts());
128
        $context['param'] = $formParam;
129
130
        $permissions = $this->permissionRepository->orderBy('code')
131
                                                  ->all();
132
133
        $context['permissions'] = $permissions;
134
135
        if ($request->getMethod() === 'GET') {
136
            return new TemplateResponse(
137
                $this->template,
138
                'permission/create',
139
                $context
140
            );
141
        }
142
143
        $validator = new PermissionValidator($formParam, $this->lang);
144
        if ($validator->validate() === false) {
145
            $context['errors'] = $validator->getErrors();
146
147
            return new TemplateResponse(
148
                $this->template,
149
                'permission/create',
150
                $context
151
            );
152
        }
153
154
        $entityExist = $this->permissionRepository->findBy([
155
                                               'code' => $formParam->getCode(),
156
                                           ]);
157
158
        if ($entityExist !== null) {
159
            $this->flash->setError($this->lang->tr('This record already exist'));
160
161
            return new TemplateResponse(
162
                $this->template,
163
                'permission/create',
164
                $context
165
            );
166
        }
167
168
        /** @var Permission $permission */
169
        $permission = $this->permissionRepository->create([
170
           'code' => $formParam->getCode(),
171
           'description' => $formParam->getDescription(),
172
        ]);
173
174
        try {
175
            $this->permissionRepository->save($permission);
176
177
            $this->flash->setSuccess($this->lang->tr('Data successfully created'));
178
179
            return new RedirectResponse(
180
                $this->routeHelper->generateUrl('permission_list')
181
            );
182
        } catch (Exception $ex) {
183
            $this->logger->error('Error when saved the data {error}', ['error' => $ex->getMessage()]);
184
185
            $this->flash->setError($this->lang->tr('Data processing error'));
186
187
            return new TemplateResponse(
188
                $this->template,
189
                'permission/create',
190
                $context
191
            );
192
        }
193
    }
194
195
    /**
196
    * Update existing entity
197
    * @param ServerRequestInterface $request
198
    * @return ResponseInterface
199
    */
200
    public function update(ServerRequestInterface $request): ResponseInterface
201
    {
202
        $context = [];
203
        $param = new RequestData($request);
204
205
        $id = (int) $request->getAttribute('id');
206
207
        /** @var Permission|null $permission */
208
        $permission = $this->permissionRepository->find($id);
209
210
        if ($permission === null) {
211
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
212
213
            return new RedirectResponse(
214
                $this->routeHelper->generateUrl('permission_list')
215
            );
216
        }
217
        $context['permission'] = $permission;
218
        $context['param'] = (new PermissionParam())->fromEntity($permission);
219
220
        $permissions = $this->permissionRepository->orderBy('code')
221
                                                  ->all();
222
223
        $context['permissions'] = $permissions;
224
225
        if ($request->getMethod() === 'GET') {
226
            return new TemplateResponse(
227
                $this->template,
228
                'permission/update',
229
                $context
230
            );
231
        }
232
        $formParam = new PermissionParam($param->posts());
233
        $context['param'] = $formParam;
234
235
        $validator = new PermissionValidator($formParam, $this->lang);
236
        if ($validator->validate() === false) {
237
            $context['errors'] = $validator->getErrors();
238
239
            return new TemplateResponse(
240
                $this->template,
241
                'permission/update',
242
                $context
243
            );
244
        }
245
246
        $entityExist = $this->permissionRepository->findBy([
247
                                               'code' => $formParam->getCode(),
248
                                           ]);
249
250
        if ($entityExist !== null && $entityExist->id !== $id) {
251
            $this->flash->setError($this->lang->tr('This record already exist'));
252
253
            return new TemplateResponse(
254
                $this->template,
255
                'permission/update',
256
                $context
257
            );
258
        }
259
260
        $permission->code = $formParam->getCode();
261
        $permission->description = $formParam->getDescription();
262
263
        try {
264
            $this->permissionRepository->save($permission);
265
266
            $this->flash->setSuccess($this->lang->tr('Data successfully updated'));
267
268
            return new RedirectResponse(
269
                $this->routeHelper->generateUrl('permission_detail', ['id' => $id])
270
            );
271
        } catch (Exception $ex) {
272
            $this->logger->error('Error when saved the data {error}', ['error' => $ex->getMessage()]);
273
274
            $this->flash->setError($this->lang->tr('Data processing error'));
275
276
            return new TemplateResponse(
277
                $this->template,
278
                'permission/update',
279
                $context
280
            );
281
        }
282
    }
283
284
    /**
285
    * Delete the entity
286
    * @param ServerRequestInterface $request
287
    * @return ResponseInterface
288
    */
289
    public function delete(ServerRequestInterface $request): ResponseInterface
290
    {
291
        $id = (int) $request->getAttribute('id');
292
293
        /** @var Permission|null $permission */
294
        $permission = $this->permissionRepository->find($id);
295
296
        if ($permission === null) {
297
            $this->flash->setError($this->lang->tr('This record doesn\'t exist'));
298
299
            return new RedirectResponse(
300
                $this->routeHelper->generateUrl('permission_list')
301
            );
302
        }
303
304
        try {
305
            $this->permissionRepository->delete($permission);
306
307
            $this->flash->setSuccess($this->lang->tr('Data successfully deleted'));
308
309
            return new RedirectResponse(
310
                $this->routeHelper->generateUrl('permission_list')
311
            );
312
        } catch (Exception $ex) {
313
            $this->logger->error('Error when delete the data {error}', ['error' => $ex->getMessage()]);
314
315
            $this->flash->setError($this->lang->tr('Data processing error'));
316
317
            return new RedirectResponse(
318
                $this->routeHelper->generateUrl('permission_list')
319
            );
320
        }
321
    }
322
}
323