Test Failed
Push — develop ( f013d6...41fb7d )
by nguereza
02:54
created

EditAction::handle()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 88
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 52
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 88
rs 8.1138

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 EditAction.php
34
 *
35
 *  The Edit action class
36
 *
37
 *  @package    Platine\Framework\Demo\Action\Permission
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\Permission;
49
50
use Platine\Framework\Auth\Entity\Permission;
51
use Platine\Framework\Auth\Repository\PermissionRepository;
52
use Platine\Framework\Demo\Form\Param\PermissionParam;
53
use Platine\Framework\Demo\Form\Validator\PermissionValidator;
54
use Platine\Framework\Http\RequestData;
55
use Platine\Framework\Http\Response\RedirectResponse;
56
use Platine\Framework\Http\Response\TemplateResponse;
57
use Platine\Framework\Http\RouteHelper;
58
use Platine\Http\Handler\RequestHandlerInterface;
59
use Platine\Http\ResponseInterface;
60
use Platine\Http\ServerRequestInterface;
61
use Platine\Logger\LoggerInterface;
62
use Platine\Session\Session;
63
use Platine\Stdlib\Helper\Str;
64
use Platine\Template\Template;
65
66
/**
67
 * @class EditAction
68
 * @package Platine\Framework\Demo\Action\Permission
69
 * @template T
70
 */
71
class EditAction implements RequestHandlerInterface
72
{
73
74
    /**
75
     * The 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 permission repository
88
     * @var PermissionRepository
89
     */
90
    protected PermissionRepository $permissionRepository;
91
92
    /**
93
     * The template instance
94
     * @var Template
95
     */
96
    protected Template $template;
97
98
    /**
99
     * The route helper instance
100
     * @var RouteHelper
101
     */
102
    protected RouteHelper $routeHelper;
103
104
    /**
105
     * Create new instance
106
     * @param LoggerInterface $logger
107
     * @param Session $session
108
     * @param Template $template
109
     * @param PermissionRepository $permissionRepository
110
     * @param RouteHelper $routeHelper
111
     */
112
    public function __construct(
113
        LoggerInterface $logger,
114
        Session $session,
115
        Template $template,
116
        PermissionRepository $permissionRepository,
117
        RouteHelper $routeHelper
118
    ) {
119
        $this->logger = $logger;
120
        $this->session = $session;
121
        $this->permissionRepository = $permissionRepository;
122
        $this->template = $template;
123
        $this->routeHelper = $routeHelper;
124
    }
125
126
    /**
127
     * {@inheritodc}
128
     */
129
    public function handle(ServerRequestInterface $request): ResponseInterface
130
    {
131
        $id = (int) $request->getAttribute('id');
132
133
        /** @var Permission $permission */
134
        $permission = $this->permissionRepository->find($id);
135
        if (!$permission) {
0 ignored issues
show
introduced by
$permission is of type Platine\Framework\Auth\Entity\Permission, thus it always evaluated to true.
Loading history...
136
            $this->session->setFlash('error', 'Can not find the permission');
137
            $this->logger->warning('Can not find permission with id {id}', ['id' => $id]);
138
139
            return new RedirectResponse(
140
                $this->routeHelper->generateUrl('permission_list')
141
            );
142
        }
143
144
        $permissions = $this->permissionRepository
145
                                                  ->orderBy('code')
146
                                                  ->all();
147
148
149
        $entityToFormParam = (new PermissionParam())->fromEntity($permission);
150
151
        if ($request->getMethod() === 'GET') {
152
            return new TemplateResponse(
153
                $this->template,
154
                'permission/edit',
155
                [
156
                    'param' => $entityToFormParam,
157
                    'permissions' => $permissions
158
                ]
159
            );
160
        }
161
162
        $param = new RequestData($request);
163
        $formParam = new PermissionParam($param->posts());
164
        $validator = new PermissionValidator($formParam);
165
166
        if (!$validator->validate()) {
167
            return new TemplateResponse(
168
                $this->template,
169
                'permission/edit',
170
                [
171
                    'errors' => $validator->getErrors(),
172
                    'param' => $formParam,
173
                    'permissions' => $permissions
174
                ]
175
            );
176
        }
177
178
        $code = $param->post('code');
179
        $permissionExist = $this->permissionRepository->findBy(['code' => $code]);
180
181
        if ($permissionExist && $permissionExist->id != $id) {
182
            $this->session->setFlash('error', 'This permission already exists');
183
            $this->logger->error('Permission with code {code} already exists', ['code' => $code]);
184
            return new TemplateResponse(
185
                $this->template,
186
                'permission/edit',
187
                [
188
                   'param' => $formParam,
189
                   'permissions' => $permissions
190
                ]
191
            );
192
        }
193
194
        $permission->code = $formParam->getCode();
0 ignored issues
show
Bug Best Practice introduced by
The property code does not exist on Platine\Framework\Auth\Entity\Permission. Since you implemented __set, consider adding a @property annotation.
Loading history...
195
        $permission->description = $formParam->getDescription();
0 ignored issues
show
Bug Best Practice introduced by
The property description does not exist on Platine\Framework\Auth\Entity\Permission. Since you implemented __set, consider adding a @property annotation.
Loading history...
196
        $permission->depend = $formParam->getDepend();
0 ignored issues
show
Bug Best Practice introduced by
The property depend does not exist on Platine\Framework\Auth\Entity\Permission. Since you implemented __set, consider adding a @property annotation.
Loading history...
197
198
        $result = $this->permissionRepository->save($permission);
199
200
        if (!$result) {
201
            $this->session->setFlash('error', 'Error when saved the permission');
202
            $this->logger->error('Error when saved the permission');
203
            return new TemplateResponse(
204
                $this->template,
205
                'permission/edit',
206
                [
207
                   'param' => $formParam,
208
                   'permissions' => $permissions
209
                ]
210
            );
211
        }
212
213
        $this->session->setFlash('success', 'Permission saved successfully');
214
215
        return new RedirectResponse(
216
            $this->routeHelper->generateUrl('permission_list')
217
        );
218
    }
219
}
220