UserTrait::detachRole()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 1
dl 12
loc 12
ccs 0
cts 10
cp 0
crap 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Laravel Platfourm package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\Platfourm\User\Models\Eloquent;
12
13
use Cache;
14
use Config;
15
use InvalidArgumentException;
16
17
trait UserTrait
18
{
19
20
    //in EntrustUserTrait.php
21
    public function cachedRole()
22
    {
23
        $cacheKey = 'entrust_role_for_user_' . $this->getKey();
0 ignored issues
show
Bug introduced by
It seems like getKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
24
        return Cache::remember($cacheKey, Config::get('cache.ttl'), function () {
25
            return $this->role;
0 ignored issues
show
Bug introduced by
The property role does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
26
        });
27
    }
28
29 View Code Duplication
    public static function bootEntrustUserTrait()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
30
    {
31
        static::saved(function ($item) {
32
            //Cache::tags(Config::get('entrust.role_user_table'))->flush();
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
33
            Cache::forget('entrust_role_for_user_' . $item->getKey());
34
        });
35
        static::deleted(function ($item) {
36
            //Cache::tags(Config::get('entrust.role_user_table'))->flush();
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
37
            Cache::forget('entrust_role_for_user_' . $item->getKey());
38
        });
39
        if (method_exists(static::class, 'restored')) {
40
            static::restored(function ($item) {
41
                //Cache::tags(Config::get('entrust.role_user_table'))->flush();
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
42
                Cache::forget('entrust_role_for_user_' . $item->getKey());
43
            });
44
        }
45
    }
46
47
    /**
48
     * Many-to-Many relations with Role.
49
     *
50
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
51
     */
52
    public function role()
53
    {
54
        return $this->belongsTo(Config::get('entrust.role'));
0 ignored issues
show
Bug introduced by
It seems like belongsTo() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
55
    }
56
57
    /**
58
     * Checks if the user has a role by its name.
59
     *
60
     * @param  string|array $name       Role name or array of role names.
61
     * @param  bool         $requireAll All roles in the array are required.
62
     * @return bool
63
     */
64 View Code Duplication
    public function hasRole($name, $requireAll = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
65
    {
66
        if (is_array($name)) {
67
            foreach ($name as $roleName) {
68
                $hasRole = $this->hasRole($roleName);
69
70
                if ($hasRole && !$requireAll) {
71
                    return true;
72
                } elseif (!$hasRole && $requireAll) {
73
                    return false;
74
                }
75
            }
76
77
            // If we've made it this far and $requireAll is FALSE, then NONE of the roles were found
78
            // If we've made it this far and $requireAll is TRUE, then ALL of the roles were found.
79
            // Return the value of $requireAll;
80
            return $requireAll;
81
        } else {
82
            return $this->role->name == $name;
83
        }
84
85
        return false;
0 ignored issues
show
Unused Code introduced by
return false; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
86
    }
87
88
    /**
89
     * Check if user has a permission by its name.
90
     *
91
     * @param  string|array $permission Permission string or array of permissions.
92
     * @param  bool         $requireAll All permissions in the array are required.
93
     * @return bool
94
     */
95 View Code Duplication
    public function can($permission, $requireAll = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
96
    {
97
        if (is_array($permission)) {
98
            foreach ($permission as $permName) {
99
                $hasPerm = $this->can($permName);
100
101
                if ($hasPerm && !$requireAll) {
102
                    return true;
103
                } elseif (!$hasPerm && $requireAll) {
104
                    return false;
105
                }
106
            }
107
108
            // If we've made it this far and $requireAll is FALSE, then NONE of the perms were found
109
            // If we've made it this far and $requireAll is TRUE, then ALL of the perms were found.
110
            // Return the value of $requireAll;
111
            return $requireAll;
112
        } else {
113
            // Validate against the Permission table
114
            foreach ($this->role->cachedPermissions() as $perm) {
115
                if (str_is($permission, $perm->name)) {
116
                    return true;
117
                }
118
            }
119
        }
120
121
        return false;
122
    }
123
124
    /**
125
     * Checks role(s) and permission(s).
126
     *
127
     * @param  string|array                $roles       Array of roles or comma separated string
128
     * @param  string|array                $permissions Array of permissions or comma separated string.
129
     * @param  array                       $options     validate_all (true|false) or return_type (boolean|array|both)
130
     * @throws \InvalidArgumentException
131
     * @return array|bool
132
     */
133
    public function ability($roles, $permissions, $options = [])
134
    {
135
        // Convert string to array if that's what is passed in.
136
        if (!is_array($roles)) {
137
            $roles = explode(',', $roles);
138
        }
139
        if (!is_array($permissions)) {
140
            $permissions = explode(',', $permissions);
141
        }
142
143
        // Set up default values and validate options.
144
        if (!isset($options['validate_all'])) {
145
            $options['validate_all'] = false;
146
        } else {
147
            if ($options['validate_all'] !== true && $options['validate_all'] !== false) {
148
                throw new InvalidArgumentException();
149
            }
150
        }
151
        if (!isset($options['return_type'])) {
152
            $options['return_type'] = 'boolean';
153
        } else {
154
            if ($options['return_type'] != 'boolean'
155
                && $options['return_type'] != 'array'
156
                && $options['return_type'] != 'both'
157
            ) {
158
                throw new InvalidArgumentException();
159
            }
160
        }
161
162
        // Loop through roles and permissions and check each.
163
        $checkedRoles       = [];
164
        $checkedPermissions = [];
165
        foreach ($roles as $role) {
166
            $checkedRoles[$role] = $this->hasRole($role);
167
        }
168
        foreach ($permissions as $permission) {
169
            $checkedPermissions[$permission] = $this->can($permission);
170
        }
171
172
        // If validate all and there is a false in either
173
        // Check that if validate all, then there should not be any false.
174
        // Check that if not validate all, there must be at least one true.
175
        if (($options['validate_all'] && !(in_array(false, $checkedRoles) || in_array(false, $checkedPermissions)))
176
            || (!$options['validate_all'] && (in_array(true, $checkedRoles) || in_array(true, $checkedPermissions)))
177
        ) {
178
            $validateAll = true;
179
        } else {
180
            $validateAll = false;
181
        }
182
183
        // Return based on option
184
        if ($options['return_type'] == 'boolean') {
185
            return $validateAll;
186
        } elseif ($options['return_type'] == 'array') {
187
            return ['roles' => $checkedRoles, 'permissions' => $checkedPermissions];
188
        } else {
189
            return [$validateAll, ['roles' => $checkedRoles, 'permissions' => $checkedPermissions]];
190
        }
191
    }
192
193
    /**
194
     * Alias to eloquent many-to-many relation's attach() method.
195
     *
196
     * @param mixed $role
197
     */
198 View Code Duplication
    public function attachRole($role)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
199
    {
200
        if (is_object($role)) {
201
            $role = $role->getKey();
202
        }
203
204
        if (is_array($role)) {
205
            $role = $role['id'];
206
        }
207
208
        $this->role->attach($role);
209
    }
210
211
    /**
212
     * Alias to eloquent many-to-many relation's detach() method.
213
     *
214
     * @param mixed $role
215
     */
216 View Code Duplication
    public function detachRole($role)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
217
    {
218
        if (is_object($role)) {
219
            $role = $role->getKey();
220
        }
221
222
        if (is_array($role)) {
223
            $role = $role['id'];
224
        }
225
226
        $this->role->detach($role);
227
    }
228
229
    /**
230
     * Attach multiple roles to a user
231
     *
232
     * @param mixed $roles
233
     */
234
    public function attachRoles($roles)
235
    {
236
        foreach ($roles as $role) {
237
            $this->attachRole($role);
238
        }
239
    }
240
241
    /**
242
     * Detach multiple roles from a user
243
     *
244
     * @param mixed $roles
245
     */
246
    public function detachRoles($roles = null)
247
    {
248
        if (!$roles) {
249
            $roles = $this->role;
250
        }
251
252
        foreach ($roles as $role) {
253
            $this->detachRole($role);
254
        }
255
    }
256
}
257