Test Failed
Push — develop ( c753fd...f013d6 )
by nguereza
02:45
created

CreateAction::handle()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 83
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 48
nc 7
nop 1
dl 0
loc 83
rs 8.5123
c 1
b 0
f 0

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
/**
4
 * Platine Framework
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant
7
 * PHP Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Framework
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file CreateAction.php
34
 *
35
 *  The Create action class
36
 *
37
 *  @package    Platine\Framework\Demo\Action\Role
38
 *  @author Platine Developers team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   http://www.iacademy.cf
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Framework\Demo\Action\Role;
49
50
use Platine\Framework\Auth\Entity\Role;
51
use Platine\Framework\Auth\Repository\PermissionRepository;
52
use Platine\Framework\Auth\Repository\RoleRepository;
53
use Platine\Framework\Demo\Form\Param\RoleParam;
54
use Platine\Framework\Demo\Form\Validator\RoleValidator;
55
use Platine\Framework\Http\RequestData;
56
use Platine\Framework\Http\Response\RedirectResponse;
57
use Platine\Framework\Http\Response\TemplateResponse;
58
use Platine\Framework\Http\RouteHelper;
59
use Platine\Http\Handler\RequestHandlerInterface;
60
use Platine\Http\ResponseInterface;
61
use Platine\Http\ServerRequestInterface;
62
use Platine\Logger\LoggerInterface;
63
use Platine\Session\Session;
64
use Platine\Template\Template;
65
66
/**
67
 * @class CreateAction
68
 * @package Platine\Framework\Demo\Action\Role
69
 * @template T
70
 */
71
class CreateAction implements RequestHandlerInterface
72
{
73
74
    /**
75
     * Logger instance
76
     * @var LoggerInterface
77
     */
78
    protected LoggerInterface $logger;
79
80
    /**
81
     * The session instance
82
     * @var Session
83
     */
84
    protected Session $session;
85
86
    /**
87
     * The role repository instance
88
     * @var RoleRepository
89
     */
90
    protected RoleRepository $roleRepository;
91
92
    /**
93
     * The permission repository
94
     * @var PermissionRepository
95
     */
96
    protected PermissionRepository $permissionRepository;
97
98
    /**
99
     * The template instance
100
     * @var Template
101
     */
102
    protected Template $template;
103
104
    /**
105
     * The route helper instance
106
     * @var RouteHelper
107
     */
108
    protected RouteHelper $routeHelper;
109
110
    /**
111
     * Create new instance
112
     * @param LoggerInterface $logger
113
     * @param Session $session
114
     * @param Template $template
115
     * @param RoleRepository $roleRepository
116
     * @param PermissionRepository $permissionRepository
117
     * @param RouteHelper $routeHelper
118
     */
119
    public function __construct(
120
        LoggerInterface $logger,
121
        Session $session,
122
        Template $template,
123
        RoleRepository $roleRepository,
124
        PermissionRepository $permissionRepository,
125
        RouteHelper $routeHelper
126
    ) {
127
        $this->logger = $logger;
128
        $this->session = $session;
129
        $this->roleRepository = $roleRepository;
130
        $this->permissionRepository = $permissionRepository;
131
        $this->template = $template;
132
        $this->routeHelper = $routeHelper;
133
    }
134
135
    /**
136
     * {@inheritodc}
137
     */
138
    public function handle(ServerRequestInterface $request): ResponseInterface
139
    {
140
        $permissions = $this->permissionRepository
141
                                                  ->orderBy('code')
142
                                                  ->all();
143
144
        if ($request->getMethod() === 'GET') {
145
            return new TemplateResponse(
146
                $this->template,
147
                'role/create',
148
                [
149
                    'param' => new RoleParam([]),
150
                    'permissions' => $permissions
151
                ]
152
            );
153
        }
154
155
        $param = new RequestData($request);
156
        $formParam = new RoleParam($param->posts());
157
        $validator = new RoleValidator($formParam);
158
159
        if (!$validator->validate()) {
160
            return new TemplateResponse(
161
                $this->template,
162
                'role/create',
163
                [
164
                    'errors' => $validator->getErrors(),
165
                    'param' => $formParam,
166
                    'permissions' => $permissions
167
                ]
168
            );
169
        }
170
171
        $name = $param->post('name');
172
        $roleExist = $this->roleRepository->findBy(['name' => $name]);
173
174
        if ($roleExist) {
175
            $this->logger->error('Role with name {name} already exists', ['name' => $name]);
176
            $this->session->setFlash('error', 'This role already exists');
177
            return new TemplateResponse(
178
                $this->template,
179
                'role/create',
180
                [
181
                   'param' => $formParam,
182
                   'permissions' => $permissions
183
                ]
184
            );
185
        }
186
187
        /** @var Role $role */
188
        $role = $this->roleRepository->create([
189
            'name' => $formParam->getName(),
190
            'description' => $formParam->getDescription()
191
        ]);
192
193
         //Handle permissions
194
        $permissionsId = $param->post('permissions', []);
195
        if (!empty($permissionsId)) {
196
            $selectedPermissions = $this->permissionRepository->findAll(...$permissionsId);
197
            $role->setPermissions($selectedPermissions);
198
        }
199
        ///////////////////
200
201
        $result = $this->roleRepository->save($role);
202
203
        if (!$result) {
204
            $this->session->setFlash('error', 'Error when saved the role');
205
            $this->logger->error('Error when saved the role');
206
            return new TemplateResponse(
207
                $this->template,
208
                'role/create',
209
                [
210
                   'param' => $formParam,
211
                    'permissions' => $permissions
212
                ]
213
            );
214
        }
215
216
217
        $this->session->setFlash('success', 'Role saved successfully');
218
219
        return new RedirectResponse(
220
            $this->routeHelper->generateUrl('role_list')
221
        );
222
    }
223
}
224