Passed
Pull Request — master (#55)
by Rafael
05:48
created

RolesAccesListController::edit()   B

Complexity

Conditions 7
Paths 15

Size

Total Lines 47
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7.5034

Importance

Changes 0
Metric Value
cc 7
eloc 22
nc 15
nop 1
dl 0
loc 47
ccs 18
cts 23
cp 0.7826
crap 7.5034
rs 8.6346
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Models\AccessList;
8
use Phalcon\Http\Response;
9
use Phalcon\Acl\Role;
10
use Phalcon\Validation;
11
use Phalcon\Validation\Validator\PresenceOf;
12
use Gewaer\Models\Apps;
13
use Gewaer\Exception\NotFoundHttpException;
14
use Gewaer\Exception\ServerErrorHttpException;
15
use Gewaer\Models\Roles;
16
use Baka\Http\QueryParser;
17
18
/**
19
 * Class RolesController
20
 *
21
 * @package Gewaer\Api\Controllers
22
 *
23
 * @property Users $userData
24
 * @property Request $request
25
 * @property Config $config
26
 * @property \Gewaer\Acl\Manager  $acl
27
 * @property \Baka\Mail\Message $mail
28
 * @property Apps $app
29
 *
30
 */
31
class RolesAccesListController extends BaseController
32
{
33
    /*
34
     * fields we accept to create
35
     *
36
     * @var array
37
     */
38
    protected $createFields = [];
39
40
    /*
41
     * fields we accept to create
42
     *
43
     * @var array
44
     */
45
    protected $updateFields = [];
46
47
    /**
48
     * set objects
49
     *
50
     * @return void
51
     */
52 6
    public function onConstruct()
53
    {
54 6
        $this->model = new AccessList();
55
56
        //get the list of roes for the systema + my company
57 6
        $this->additionalSearchFields = [
58 6
            ['is_deleted', ':', '0'],
59 6
            ['apps_id', ':', '0|' . $this->app->getId()],
60
        ];
61 6
    }
62
63
    /**
64
     * Add a new item
65
     *
66
     * @method POST
67
     * @url /v1/roles-acceslist
68
     *
69
     * @return Response
70
     */
71 1
    public function create() : Response
72
    {
73 1
        $request = $this->request->getPost();
74
75 1
        if (empty($request)) {
76
            $request = $this->request->getJsonRawBody(true);
77
        }
78
79
        //Ok let validate user password
80 1
        $validation = new Validation();
81 1
        $validation->add('roles', new PresenceOf(['message' => _('Role information is required.')]));
82 1
        $validation->add('access', new PresenceOf(['message' => _('Access list is required.')]));
83
84
        //validate this form for password
85 1
        $messages = $validation->validate($request);
86 1
        if (count($messages)) {
87
            foreach ($messages as $message) {
88
                throw new ServerErrorHttpException((string)$message);
89
            }
90
        }
91
92
        //set the company and app
93 1
        $this->acl->setCompany($this->userData->DefaultCompany);
94 1
        $this->acl->setApp($this->app);
95
96 1
        $scope = 1;
97
        //create the role , the scope is level 1 , that means user
98 1
        $this->acl->addRole(new Role($request['roles']['name'], $request['roles']['description']), $scope);
99
100
        /**
101
         * we always deny permision, by default the canvas set allow to all
102
         * so we only have to take away permissions
103
         */
104 1
        foreach ($request['access'] as $access) {
105 1
            $this->acl->deny($request['roles']['name'], $access['resources_name'], $access['access_name']);
106
        }
107
108 1
        return $this->response($request['roles']);
109
    }
110
111
    /**
112
     * get item
113
     *
114
     * @param mixed $id
115
     *
116
     * @method GET
117
     * @url /v1/roles-acceslist/{id}
118
     *
119
     * @return Response
120
     */
121 1
    public function getById($id) : Response
122
    {
123 1
        $objectInfo = $this->model->findFirst([
124 1
            'roles_id = ?0 AND is_deleted = 0 AND apps_id in (?1, ?2)',
125 1
            'bind' => [$id, $this->app->getId(), Apps::GEWAER_DEFAULT_APP_ID],
126
        ]);
127
128
        //get relationship
129 1
        if ($this->request->hasQuery('relationships')) {
130
            $relationships = $this->request->getQuery('relationships', 'string');
131
132
            $objectInfo = QueryParser::parseRelationShips($relationships, $objectInfo);
133
        }
134
135 1
        if ($objectInfo) {
136 1
            return $this->response($objectInfo);
137
        } else {
138
            throw new NotFoundHttpException('Record not found');
139
        }
140
    }
141
142
    /**
143
     * Update a new Entry
144
     *
145
     * @method PUT
146
     * @url /v1/roles-acceslist/{id}
147
     *
148
     * @return Response
149
     */
150 1
    public function edit($id) : Response
151
    {
152 1
        if (!$role = Roles::getById((int) $id)) {
153
            throw new NotFoundHttpException('Record not found');
154
        }
155
156 1
        $request = $this->request->getPut();
157
158 1
        if (empty($request)) {
159
            $request = $this->request->getJsonRawBody(true);
160
        }
161
162
        //Ok let validate user password
163 1
        $validation = new Validation();
164 1
        $validation->add('roles', new PresenceOf(['message' => _('Role information is required.')]));
165 1
        $validation->add('access', new PresenceOf(['message' => _('Access list is required.')]));
166
167
        //validate this form for password
168 1
        $messages = $validation->validate($request);
169 1
        if (count($messages)) {
170
            foreach ($messages as $message) {
171
                throw new ServerErrorHttpException((string)$message);
172
            }
173
        }
174
175
        //set the company and app
176 1
        $this->acl->setCompany($this->userData->DefaultCompany);
177 1
        $this->acl->setApp($this->app);
178
179 1
        $role->name = $request['roles']['name'];
180 1
        $role->description = $request['roles']['description'];
181 1
        if (!$role->update()) {
182
            throw new ServerErrorHttpException((string) current($role->getMessages()));
183
        }
184
185
        //clean previous records
186 1
        $role->accesList->delete();
187
188
        /**
189
         * we always deny permision, by default the canvas set allow to all
190
         * so we only have to take away permissions
191
         */
192 1
        foreach ($request['access'] as $access) {
193 1
            $this->acl->deny($request['roles']['name'], $access['resources_name'], $access['access_name']);
194
        }
195
196 1
        return $this->response($role);
197
    }
198
199
    /**
200
     * Copy a existen
201
     *
202
     * @param int $id
203
     * @return Response
204
     */
205 1
    public function copy($id) : Response
206
    {
207 1
        if (!$role = Roles::getById((int) $id)) {
208
            throw new NotFoundHttpException('Record not found');
209
        }
210
211 1
        return $this->response($role->copy());
212
    }
213
214
    /**
215
     * delete a new Entry
216
     *
217
     * @method DELETE
218
     * @url /v1/roles-acceslist/{id}
219
     *
220
     * @return Response
221
     */
222 1
    public function delete($id) : Response
223
    {
224 1
        if ($role = Roles::findFirst($id)) {
225 1
            if ($this->softDelete == 1) {
226 1
                $role->softDelete();
227
            } else {
228
                $role->delete();
229
            }
230
231 1
            return $this->response(['Delete Successfully']);
232
        } else {
233
            throw new NotFoundHttpException('Record not found');
234
        }
235
    }
236
}
237