UserAction   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 367
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 188
c 1
b 0
f 0
dl 0
loc 367
rs 10
wmc 26

6 Methods

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