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

CreateAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 6
dl 0
loc 14
rs 10
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\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\Auth\Repository\RoleRepository;
53
use Platine\Framework\Demo\Form\Param\PermissionParam;
54
use Platine\Framework\Demo\Form\Validator\PermissionValidator;
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\Permission
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 permission repository instance
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 RoleRepository $roleRepository
111
     * @param RouteHelper $routeHelper
112
     */
113
    public function __construct(
114
        LoggerInterface $logger,
115
        Session $session,
116
        Template $template,
117
        PermissionRepository $permissionRepository,
118
        RoleRepository $roleRepository,
119
        RouteHelper $routeHelper
120
    ) {
121
        $this->logger = $logger;
122
        $this->session = $session;
123
        $this->permissionRepository = $permissionRepository;
124
        $this->roleRepository = $roleRepository;
0 ignored issues
show
Bug Best Practice introduced by
The property roleRepository does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
125
        $this->template = $template;
126
        $this->routeHelper = $routeHelper;
127
    }
128
129
    /**
130
     * {@inheritodc}
131
     */
132
    public function handle(ServerRequestInterface $request): ResponseInterface
133
    {
134
        $permissions = $this->permissionRepository
135
                                                  ->orderBy('code')
136
                                                  ->all();
137
138
        if ($request->getMethod() === 'GET') {
139
            return new TemplateResponse(
140
                $this->template,
141
                'permission/create',
142
                [
143
                    'param' => new PermissionParam([]),
144
                    'permissions' => $permissions
145
                ]
146
            );
147
        }
148
149
        $param = new RequestData($request);
150
        $formParam = new PermissionParam($param->posts());
151
        $validator = new PermissionValidator($formParam);
152
153
        if (!$validator->validate()) {
154
            return new TemplateResponse(
155
                $this->template,
156
                'permission/create',
157
                [
158
                    'errors' => $validator->getErrors(),
159
                    'param' => $formParam,
160
                    'permissions' => $permissions
161
                ]
162
            );
163
        }
164
165
        $code = $param->post('code');
166
        $permissionExist = $this->permissionRepository->findBy(['code' => $code]);
167
168
        if ($permissionExist) {
169
            $this->logger->error('Permission with code {code} already exists', ['code' => $code]);
170
            $this->session->setFlash('error', 'This permission already exists');
171
            return new TemplateResponse(
172
                $this->template,
173
                'permission/create',
174
                [
175
                   'param' => $formParam,
176
                   'permissions' => $permissions
177
                ]
178
            );
179
        }
180
181
        /** @var Permission $permission */
182
        $permission = $this->permissionRepository->create([
183
            'code' => $formParam->getCode(),
184
            'description' => $formParam->getDescription(),
185
            'depend' => $formParam->getDepend(),
186
        ]);
187
188
        $result = $this->permissionRepository->save($permission);
189
190
        if (!$result) {
191
            $this->session->setFlash('error', 'Error when saved the permission');
192
            $this->logger->error('Error when saved the permission');
193
            return new TemplateResponse(
194
                $this->template,
195
                'permission/create',
196
                [
197
                   'param' => $formParam,
198
                   'permissions' => $permissions
199
                ]
200
            );
201
        }
202
203
204
        $this->session->setFlash('success', 'Permission saved successfully');
205
206
        return new RedirectResponse(
207
            $this->routeHelper->generateUrl('permission_list')
208
        );
209
    }
210
}
211