Test Failed
Pull Request — master (#160)
by Maximo
07:00
created

Roles::validation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 17
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 29
ccs 0
cts 25
cp 0
crap 2
rs 9.7
1
<?php
2
declare(strict_types=1);
3
4
namespace Canvas\Models;
5
6
use Canvas\Exception\ServerErrorHttpException;
7
use Phalcon\Di;
8
use Phalcon\Validation;
9
use Phalcon\Validation\Validator\PresenceOf;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\PresenceOf was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Phalcon\Validation\Validator\StringLength;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\StringLength was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Phalcon\Acl\Role as AclRole;
0 ignored issues
show
Bug introduced by
The type Phalcon\Acl\Role was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Canvas\Exception\ModelException;
13
14
/**
15
 * Class Roles.
16
 *
17
 * @package Canvas\Models
18
 *
19
 * @property AccesList $accesList
20
 * @property \Phalcon\Di $di
21
 */
22
class Roles extends AbstractModel
23
{
24
    /**
25
     *
26
     * @var integer
27
     */
28
    public $id;
29
30
    /**
31
     *
32
     * @var string
33
     */
34
    public $name;
35
36
    /**
37
     *
38
     * @var string
39
     */
40
    public $description;
41
42
    /**
43
     *
44
     * @var integer
45
     */
46
    public $scope;
47
48
    /**
49
     *
50
     * @var integer
51
     */
52
    public $companies_id;
53
54
    /**
55
     *
56
     * @var int
57
     */
58
    public $apps_id;
59
60
    /**
61
     *
62
     * @var string
63
     */
64
    public $created_at;
65
66
    /**
67
     *
68
     * @var string
69
     */
70
    public $updated_at;
71
72
    /**
73
     *
74
     * @var integer
75
     */
76
    public $is_deleted;
77
78
    /**
79
     * Default ACL company.
80
     *
81
     */
82
    const DEFAULT_ACL_COMPANY_ID = 1;
83
    const DEFAULT_ACL_APP_ID = 1;
84
    const DEFAULT = 'Admins';
85
86
    /**
87
     * Initialize method for model.
88
     */
89
    public function initialize()
90
    {
91
        $this->setSource('roles');
92
93
        $this->hasMany(
94
            'id',
95
            'Canvas\Models\AccessList',
96
            'roles_id',
97
            ['alias' => 'accesList']
98
        );
99
    }
100
101
    /**
102
     * Validations and business logic.
103
     */
104
    public function validation()
105
    {
106
        $validator = new Validation();
107
108
        $validator->add(
109
            'name',
110
            new PresenceOf([
111
                'field' => 'name',
112
                'required' => true,
113
            ])
114
        );
115
116
        $validator->add(
117
            'description',
118
            new PresenceOf([
119
                'field' => 'description',
120
                'required' => true,
121
            ])
122
        );
123
124
        $validator->add(
125
            'name',
126
            new StringLength([
127
                'max' => 32,
128
                'messageMinimum' => _('Role Name. Maxium 32 characters.'),
129
            ])
130
        );
131
132
        return $this->validate($validator);
133
    }
134
135
    /**
136
     * Returns table name mapped in the model.
137
     *
138
     * @return string
139
     */
140
    public function getSource(): string
141
    {
142
        return 'roles';
143
    }
144
145
    /**
146
     * Check if the role existe in the db.
147
     *
148
     * @param AclRole $role
149
     * @return int
150
     */
151
    public static function exist(AclRole $role): int
152
    {
153
        return self::count([
154
            'conditions' => 'name = ?0 AND companies_id = ?1 AND apps_id = ?2',
155
            'bind' => [$role->getName(), Di::getDefault()->getAcl()->getCompany()->getId(), Di::getDefault()->getAcl()->getApp()->getId()]
156
        ]);
157
    }
158
159
    /**
160
     * check if this string is already a role
161
     * whats the diff with exist or why not merge them? exist uses the alc object and only check
162
     * with your current app, this also check with de defautl company ap.
163
     *
164
     * @param string $roleName
165
     * @return boolean
166
     */
167
    public static function isRole(string $roleName) : bool
168
    {
169
        return (bool) self::count([
170
            'conditions' => 'name = ?0 AND apps_id in (?1, ?3) AND companies_id in (?2, ?3)',
171
            'bind' => [$roleName, Di::getDefault()->getAcl()->getApp()->getId(), Di::getDefault()->getAcl()->getCompany()->getId(), Apps::CANVAS_DEFAULT_APP_ID]
172
        ]);
173
    }
174
175
    /**
176
     * Get the entity by its name.
177
     *
178
     * @param string $name
179
     * @return Roles
180
     */
181
    public static function getByName(string $name): Roles
182
    {
183
        $role = self::findFirst([
184
            'conditions' => 'name = ?0 AND apps_id in (?1, ?3) AND companies_id in (?2, ?3) AND is_deleted = 0',
185
            'bind' => [$name, Di::getDefault()->getAcl()->getApp()->getId(), Di::getDefault()->getAcl()->getCompany()->getId(), Apps::CANVAS_DEFAULT_APP_ID],
186
            'order' => 'apps_id DESC'
187
        ]);
188
189
        if (!is_object($role)) {
190
            throw new ModelException(_('Roles ' . $name . ' not found on this app ' . Di::getDefault()->getAcl()->getApp()->getId() . ' AND Company' . Di::getDefault()->getAcl()->getCompany()->getId()));
191
        }
192
193
        return $role;
194
    }
195
196
    /**
197
     * Get the entity by its name.
198
     *
199
     * @param string $name
200
     * @return Roles
201
     */
202
    public static function getById(int $id): Roles
203
    {
204
        return self::findFirst([
205
            'conditions' => 'id = ?0 AND companies_id in (?1, ?2) AND apps_id in (?3, ?4) AND is_deleted = 0',
206
            'bind' => [$id, Di::getDefault()->getUserData()->currentCompanyId(), Apps::CANVAS_DEFAULT_APP_ID, Di::getDefault()->getApp()->getId(), Apps::CANVAS_DEFAULT_APP_ID],
207
            'order' => 'apps_id DESC'
208
        ]);
209
    }
210
211
    /**
212
     * Get the Role by it app name.
213
     *
214
     * @param string $role
215
     * @return Roles
216
     */
217
    public static function getByAppName(string $role, Companies $company): Roles
218
    {
219
        //echeck if we have a dot , taht means we are sending the specific app to use
220
        if (strpos($role, '.') === false) {
221
            throw new ServerErrorHttpException('ACL - We are expecting the app for this role');
222
        }
223
224
        $appRole = explode('.', $role);
225
        $role = $appRole[1];
0 ignored issues
show
Unused Code introduced by
The assignment to $role is dead and can be removed.
Loading history...
226
        $appName = $appRole[0];
227
228
        //look for the app and set it
229
        if (!$app = Apps::getACLApp($appName)) {
230
            throw new ServerErrorHttpException('ACL - No app found for this role');
231
        }
232
233
        return self::findFirst([
234
            'conditions' => 'apps_id in (?0, ?1) AND companies_id in (?2 , ?3)',
235
            'bind' => [$app->getId(), self::DEFAULT_ACL_APP_ID, $company->getId(), self::DEFAULT_ACL_COMPANY_ID]
236
        ]);
237
    }
238
239
    /**
240
     * Duplicate a role with it access list.
241
     *
242
     * @return Roles
243
     */
244
    public function copy(): Roles
245
    {
246
        $accesList = $this->accesList;
247
248
        //remove id to create new record
249
        $this->name .= 'Copie';
250
        $this->scope = 1;
251
        $this->id = null;
252
        $this->companies_id = $this->di->getUserData()->currentCompanyId();
253
        $this->apps_id = $this->di->getApp()->getId();
254
        $this->save();
255
256
        foreach ($accesList as $access) {
257
            $copyAccessList = new AccessList();
258
            $copyAccessList->apps_id = $this->apps_id;
259
            $copyAccessList->roles_id = $this->getId();
260
            $copyAccessList->roles_name = $this->name;
261
            $copyAccessList->resources_name = $access->resources_name;
262
            $copyAccessList->access_name = $access->access_name;
263
            $copyAccessList->allowed = $access->allowed;
264
            $copyAccessList->create();
265
        }
266
267
        return $this;
268
    }
269
270
    /**
271
     * Add inherit to a given role.
272
     *
273
     * @param string $roleName
274
     * @param string $roleToInherit
275
     * @return boolean
276
     */
277
    public static function addInherit(string $roleName, string $roleToInherit) : bool
278
    {
279
        $role = self::findFirstByName($roleName);
280
281
        if (!is_object($role)) {
282
            throw new ModelException("Role '{$roleName}' does not exist in the role list");
283
        }
284
285
        $inheritExist = RolesInherits::count([
286
            'conditions' => 'roles_name = ?0 and roles_inherit = ?1',
287
            'bind' => [$role->name, $roleToInherit]
288
        ]);
289
290
        if (!$inheritExist) {
291
            $rolesInHerits = new RolesInherits();
292
            $rolesInHerits->roles_id = $role->getId();
293
            $rolesInHerits->roles_inherit = (int) $roleToInherit;
294
295
            if (!$rolesInHerits->save()) {
296
                throw new ModelException((string) current($rolesInHerits->getMessages()));
297
            }
298
299
            return true;
300
        }
301
302
        return false;
303
    }
304
305
    /**
306
     * After update.
307
     *
308
     * @return void
309
     */
310
    public function afterUpdate()
311
    {
312
        //if we deleted the role
313
        if ($this->is_deleted) {
314
            //delete
315
            foreach ($this->accesList as $access) {
316
                $access->softDelete();
317
            }
318
        }
319
    }
320
321
    /**
322
     * Check if role exists by its id.
323
     * @param integer $role_id
324
     * @return Roles
325
     */
326
    public static function existsById(int $id): Roles
327
    {
328
        $role = self::getById($id);
329
330
        if (!is_object($role)) {
331
            throw new ModelException('Role does not exist');
332
        }
333
334
        return $role;
335
    }
336
337
    /**
338
     * Assign the default app role to a given user.
339
     *
340
     * @param Users $user
341
     * @return bool
342
     */
343
    public static function assignDefault(Users $user): bool
344
    {
345
        $apps = Di::getDefault()->getApp();
346
        $userRoles = UserRoles::findFirst([
347
            'conditions' => 'users_id = ?0 AND apps_id = ?1 AND companies_id = ?2 AND is_deleted = 0',
348
            'bind' => [$user->getId(), $apps->getId(), $user->getDefaultCompany()->getId()]
349
        ]);
350
351
        if (!is_object($userRoles)) {
352
            $userRole = new UserRoles();
353
            $userRole->users_id = $user->getId();
354
            $userRole->roles_id = Roles::getByName(Roles::DEFAULT)->getId();
355
            $userRole->apps_id = $apps->getId();
356
            $userRole->companies_id = $user->getDefaultCompany()->getId();
357
            return $userRole->saveOrFail();
358
        }
359
360
        return true;
361
    }
362
}
363