Failed Conditions
Pull Request — master (#30)
by Maximo
04:14 queued 12s
created

Roles::exist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Gewaer\Models;
5
6
use Gewaer\Exception\ServerErrorHttpException;
7
use Phalcon\Di;
8
use Phalcon\Validation;
9
use Phalcon\Validation\Validator\PresenceOf;
10
use Phalcon\Validation\Validator\StringLength;
11
use Phalcon\Acl\Role as AclRole;
12
use Gewaer\Exception\ModelException;
13
14
class Roles extends AbstractModel
15
{
16
    /**
17
     *
18
     * @var integer
19
     */
20
    public $id;
21
22
    /**
23
     *
24
     * @var string
25
     */
26
    public $name;
27
28
    /**
29
     *
30
     * @var string
31
     */
32
    public $description;
33
34
    /**
35
     *
36
     * @var integer
37
     */
38
    public $scope;
39
40
    /**
41
     *
42
     * @var integer
43
     */
44
    public $companies_id;
45
46
    /**
47
     *
48
     * @var int
49
     */
50
    public $apps_id;
51
52
    /**
53
     *
54
     * @var string
55
     */
56
    public $created_at;
57
58
    /**
59
     *
60
     * @var string
61
     */
62
    public $updated_at;
63
64
    /**
65
     *
66
     * @var integer
67
     */
68
    public $is_deleted;
69
70
    /**
71
     * Default ACL company
72
     *
73
     */
74
    const DEFAULT_ACL_COMPANY_ID = 0;
75
    const DEFAULT_ACL_APP_ID = 0;
76
77
    /**
78
     * Initialize method for model.
79
     */
80 20
    public function initialize()
81
    {
82 20
        $this->setSource('roles');
83
84 20
        $this->hasMany(
85 20
            'id',
86 20
            'Gewaer\Models\AccessList',
87 20
            'roles_id',
88 20
            ['alias' => 'accesList']
89
        );
90 20
    }
91
92
    /**
93
     * Validations and business logic
94
     */
95 3
    public function validation()
96
    {
97 3
        $validator = new Validation();
98
99 3
        $validator->add(
100 3
            'name',
101 3
            new PresenceOf([
102 3
                'field' => 'name',
103
                'required' => true,
104
            ])
105
        );
106
107 3
        $validator->add(
108 3
            'description',
109 3
            new PresenceOf([
110 3
                'field' => 'description',
111
                'required' => true,
112
            ])
113
        );
114
115 3
        $validator->add(
116 3
            'name',
117 3
            new StringLength([
118 3
                'max' => 32,
119 3
                'messageMinimum' => _('Role Name. Maxium 32 characters.'),
120
            ])
121
        );
122
123 3
        return $this->validate($validator);
124
    }
125
126
    /**
127
     * Returns table name mapped in the model.
128
     *
129
     * @return string
130
     */
131 19
    public function getSource(): string
132
    {
133 19
        return 'roles';
134
    }
135
136
    /**
137
     * Check if the role existe in the db
138
     *
139
     * @param AclRole $role
140
     * @return int
141
     */
142 3
    public static function exist(AclRole $role): int
143
    {
144 3
        return self::count([
145 3
            'conditions' => 'name = ?0 AND companies_id = ?1 AND apps_id = ?2',
146 3
            'bind' => [$role->getName(), Di::getDefault()->getAcl()->getCompany()->getId(), Di::getDefault()->getAcl()->getApp()->getId()]
147
        ]);
148
    }
149
150
    /**
151
     * check if this string is already a role
152
     * whats the diff with exist or why not merge them? exist uses the alc object and only check
153
     * with your current app, this also check with de defautl company ap
154
     *
155
     * @param string $roleName
156
     * @return boolean
157
     */
158 4
    public function isRole(string $roleName) : bool
159
    {
160 4
        return (bool) self::count([
161 4
            'conditions' => 'name = ?0 AND apps_id = ?1 AND companies_id in (?2, ?3)',
162 4
            'bind' => [$roleName, Di::getDefault()->getAcl()->getApp()->getId(), Di::getDefault()->getAcl()->getCompany()->getId(), Apps::GEWAER_DEFAULT_APP_ID]
163
        ]);
164
    }
165
166
    /**
167
     * Get the entity by its name
168
     *
169
     * @param string $name
170
     * @return void
171
     */
172 8
    public static function getByName(string $name): Roles
173
    {
174 8
        $role = self::findFirst([
175 8
            'conditions' => 'name = ?0 AND apps_id = ?1 AND companies_id in (?2, ?3) AND is_deleted = 0',
176 8
            'bind' => [$name, Di::getDefault()->getAcl()->getApp()->getId(), Di::getDefault()->getAcl()->getCompany()->getId(), Apps::GEWAER_DEFAULT_APP_ID]
177
        ]);
178
179 8
        if (!is_object($role)) {
180
            throw new ModelException(_('Roles ' . $role . ' not found on this app ' . Di::getDefault()->getAcl()->getApp()->getId() . ' AND Company' . Di::getDefault()->getAcl()->getCompany()->getId()));
181
        }
182
183 8
        return $role;
184
    }
185
186
    /**
187
     * Get the entity by its name
188
     *
189
     * @param string $name
190
     * @return void
191
     */
192 1
    public static function getById(int $id)
193
    {
194 1
        return self::findFirst([
195 1
            'conditions' => 'id = ?0 AND companies_id in (?1, ?2) AND apps_id in (?3, ?4) AND is_deleted = 0',
196 1
            'bind' => [$id, Di::getDefault()->getUserData()->default_company, Apps::GEWAER_DEFAULT_APP_ID, Di::getDefault()->getApp()->getId(), Apps::GEWAER_DEFAULT_APP_ID]
197
        ]);
198
    }
199
200
    /**
201
     * Get the Role by it app name
202
     *
203
     * @param string $role
204
     * @return Roles
205
     */
206 7
    public static function getByAppName(string $role, Companies $company): Roles
207
    {
208
        //echeck if we have a dot , taht means we are sending the specific app to use
209 7
        if (strpos($role, '.') === false) {
210
            throw new ServerErrorHttpException('ACL - We are expecting the app for this role');
211
        }
212
213 7
        $appRole = explode('.', $role);
214 7
        $role = $appRole[1];
1 ignored issue
show
Unused Code introduced by
The assignment to $role is dead and can be removed.
Loading history...
215 7
        $appName = $appRole[0];
216
217
        //look for the app and set it
218 7
        if (!$app = Apps::getACLApp($appName)) {
219
            throw new ServerErrorHttpException('ACL - No app found for this role');
220
        }
221
222 7
        return self::findFirst([
223 7
            'conditions' => 'apps_id in (?0, ?1) AND companies_id in (?2 , ?3)',
224 7
            'bind' => [$app->getId(), self::DEFAULT_ACL_APP_ID, $company->getId(), self::DEFAULT_ACL_COMPANY_ID]
225
        ]);
226
    }
227
228
    /**
229
     * Duplicate a role with it access list
230
     *
231
     * @return bool
232
     */
233
    public function copy(): Roles
234
    {
235
        $accesList = $this->accesList;
0 ignored issues
show
Bug Best Practice introduced by
The property accesList does not exist on Gewaer\Models\Roles. Since you implemented __get, consider adding a @property annotation.
Loading history...
236
237
        //remove id to create new record
238
        $this->name .= 'Copie';
239
        $this->scope = 1;
240
        $this->id = null;
241
        $this->companies_id = $this->di->getUserData()->default_company;
0 ignored issues
show
Bug Best Practice introduced by
The property di does not exist on Gewaer\Models\Roles. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method getUserData() does not exist on Phalcon\Mvc\Model\Resultset. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

241
        $this->companies_id = $this->di->/** @scrutinizer ignore-call */ getUserData()->default_company;

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
242
        $this->apps_id = $this->di->getApp()->getId();
0 ignored issues
show
Bug introduced by
The method getApp() does not exist on Phalcon\Mvc\Model\Resultset. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

242
        $this->apps_id = $this->di->/** @scrutinizer ignore-call */ getApp()->getId();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
243
        $this->save();
244
245
        foreach ($accesList as $access) {
246
            $copyAccessList = new AccessList();
247
            $copyAccessList->apps_id = $this->apps_id;
248
            $copyAccessList->roles_id = $this->getId();
249
            $copyAccessList->roles_name = $this->name;
250
            $copyAccessList->resources_name = $access->resources_name;
251
            $copyAccessList->access_name = $access->access_name;
252
            $copyAccessList->allowed = $access->allowed;
253
            $copyAccessList->create();
254
        }
255
256
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type Gewaer\Models\Roles which is incompatible with the documented return type boolean.
Loading history...
257
    }
258
259
    /**
260
     * Add inherit to a given role
261
     *
262
     * @param string $roleName
263
     * @param string $roleToInherit
264
     * @return boolean
265
     */
266
    public static function addInherit(string $roleName, string $roleToInherit) : bool
267
    {
268
        $role = RolesDB::findFirstByName($roleName);
0 ignored issues
show
Bug introduced by
The type Gewaer\Models\RolesDB 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...
269
270
        if (!$is_ojbject($role)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $is_ojbject seems to be never defined.
Loading history...
271
            throw new Exception("Role '{$roleName}' does not exist in the role list");
0 ignored issues
show
Bug introduced by
The type Gewaer\Models\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
272
        }
273
274
        $inheritExist = RolesInherits::count([
275
            'conditions' => 'roles_name = ?0 and roles_inherit = ?1',
276
            'bind' => [$role->name, $roleToInherit]
277
        ]);
278
279
        if (!$inheritExist) {
280
            $rolesInHerits = new RolesInherits();
281
            $rolesInHerits->roles_id = $role->getId();
282
            $rolesInHerits->roles_inherit = $roleToInherit;
0 ignored issues
show
Documentation Bug introduced by
The property $roles_inherit was declared of type integer, but $roleToInherit is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
283
284
            if (!$rolesInHerits->save()) {
285
                throw new ModelException((string) current($rolesInHerits->getMessages()));
286
            }
287
288
            return true;
289
        }
290
291
        return false;
292
    }
293
}
294