Completed
Push — master ( 80411a...1281a7 )
by wen
03:35
created

EntrustUserTrait   C

Complexity

Total Complexity 61

Size/Duplication

Total Lines 298
Duplicated Lines 31.54 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 61
lcom 1
cbo 1
dl 94
loc 298
rs 6.018
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A cachedRoles() 13 13 2
A save() 0 7 2
A delete() 0 7 2
A restore() 0 7 2
A roles() 0 7 1
A bootEntrustUserTrait() 0 12 2
D hasRole() 27 27 9
D can() 30 30 10
D ability() 0 68 20
A attachRole() 12 12 3
A detachRole() 12 12 3
A attachRoles() 0 6 2
A detachRoles() 0 10 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like EntrustUserTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EntrustUserTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Sco\Admin\Traits;
4
5
/**
6
 * This file is part of Entrust,
7
 * a role & permission management solution for Laravel.
8
 *
9
 * @license MIT
10
 * @package Zizaco\Entrust
11
 */
12
13
use Illuminate\Cache\TaggableStore;
14
use Illuminate\Support\Facades\Cache;
15
use Illuminate\Support\Facades\Config;
16
use InvalidArgumentException;
17
18
trait EntrustUserTrait
19
{
20
    //Big block of caching functionality.
21 View Code Duplication
    public function cachedRoles()
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...
22
    {
23
        $userPrimaryKey = $this->primaryKey;
0 ignored issues
show
Bug introduced by
The property primaryKey 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...
24
        $cacheKey       = 'entrust_roles_for_user_' . $this->$userPrimaryKey;
25
        if (Cache::getStore() instanceof TaggableStore) {
26
            return Cache::tags(Config::get('admin.role_user_table'))->remember($cacheKey,
27
                Config::get('cache.ttl'), function () {
28
                    return $this->roles()->get();
29
                });
30
        } else {
31
            return $this->roles()->get();
32
        }
33
    }
34
35
    public function save(array $options = [])
36
    {   //both inserts and updates
37
        if (Cache::getStore() instanceof TaggableStore) {
38
            Cache::tags(Config::get('admin.role_user_table'))->flush();
39
        }
40
        return parent::save($options);
41
    }
42
43
    public function delete(array $options = [])
44
    {   //soft or hard
45
        parent::delete($options);
46
        if (Cache::getStore() instanceof TaggableStore) {
47
            Cache::tags(Config::get('admin.role_user_table'))->flush();
48
        }
49
    }
50
51
    public function restore()
52
    {   //soft delete undo's
53
        parent::restore();
54
        if (Cache::getStore() instanceof TaggableStore) {
55
            Cache::tags(Config::get('admin.role_user_table'))->flush();
56
        }
57
    }
58
59
    /**
60
     * Many-to-Many relations with Role.
61
     *
62
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
63
     */
64
    public function roles()
65
    {
66
        return $this->belongsToMany(Config::get('admin.role'),
0 ignored issues
show
Bug introduced by
It seems like belongsToMany() 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...
67
            Config::get('admin.role_user_table'),
68
            Config::get('admin.user_foreign_key'),
69
            Config::get('admin.role_foreign_key'));
70
    }
71
72
    /**
73
     * Boot the user model
74
     * Attach event listener to remove the many-to-many records when trying to
75
     * delete Will NOT delete any records if the user model uses soft deletes.
76
     *
77
     * @return void|bool
78
     */
79
    public static function bootEntrustUserTrait()
80
    {
81
        static::deleting(function ($user) {
82
            if (!method_exists(Config::get('admin.user'),
83
                'bootSoftDeletes')
84
            ) {
85
                $user->roles()->sync([]);
86
            }
87
88
            return true;
89
        });
90
    }
91
92
    /**
93
     * Checks if the user has a role by its name.
94
     *
95
     * @param string|array $name       Role name or array of role names.
96
     * @param bool         $requireAll All roles in the array are required.
97
     *
98
     * @return bool
99
     */
100 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...
101
    {
102
        if (is_array($name)) {
103
            foreach ($name as $roleName) {
104
                $hasRole = $this->hasRole($roleName);
105
106
                if ($hasRole && !$requireAll) {
107
                    return true;
108
                } elseif (!$hasRole && $requireAll) {
109
                    return false;
110
                }
111
            }
112
113
            // If we've made it this far and $requireAll is FALSE, then NONE of the roles were found
114
            // If we've made it this far and $requireAll is TRUE, then ALL of the roles were found.
115
            // Return the value of $requireAll;
116
            return $requireAll;
117
        } else {
118
            foreach ($this->cachedRoles() as $role) {
119
                if ($role->name == $name) {
120
                    return true;
121
                }
122
            }
123
        }
124
125
        return false;
126
    }
127
128
    /**
129
     * Check if user has a permission by its name.
130
     *
131
     * @param string|array $permission Permission string or array of
132
     *                                 permissions.
133
     * @param bool         $requireAll All permissions in the array are
134
     *                                 required.
135
     *
136
     * @return bool
137
     */
138 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...
139
    {
140
        if (is_array($permission)) {
141
            foreach ($permission as $permName) {
142
                $hasPerm = $this->can($permName);
143
144
                if ($hasPerm && !$requireAll) {
145
                    return true;
146
                } elseif (!$hasPerm && $requireAll) {
147
                    return false;
148
                }
149
            }
150
151
            // If we've made it this far and $requireAll is FALSE, then NONE of the perms were found
152
            // If we've made it this far and $requireAll is TRUE, then ALL of the perms were found.
153
            // Return the value of $requireAll;
154
            return $requireAll;
155
        } else {
156
            foreach ($this->cachedRoles() as $role) {
157
                // Validate against the Permission table
158
                foreach ($role->cachedPermissions() as $perm) {
159
                    if (str_is($permission, $perm->name)) {
160
                        return true;
161
                    }
162
                }
163
            }
164
        }
165
166
        return false;
167
    }
168
169
    /**
170
     * Checks role(s) and permission(s).
171
     *
172
     * @param string|array $roles       Array of roles or comma separated
173
     *                                  string
174
     * @param string|array $permissions Array of permissions or comma separated
175
     *                                  string.
176
     * @param array        $options     validate_all (true|false) or
177
     *                                  return_type (boolean|array|both)
178
     *
179
     * @throws \InvalidArgumentException
180
     * @return array|bool
181
     */
182
    public function ability($roles, $permissions, $options = [])
183
    {
184
        // Convert string to array if that's what is passed in.
185
        if (!is_array($roles)) {
186
            $roles = explode(',', $roles);
187
        }
188
        if (!is_array($permissions)) {
189
            $permissions = explode(',', $permissions);
190
        }
191
192
        // Set up default values and validate options.
193
        if (!isset($options['validate_all'])) {
194
            $options['validate_all'] = false;
195
        } else {
196
            if ($options['validate_all'] !== true && $options['validate_all'] !== false) {
197
                throw new InvalidArgumentException();
198
            }
199
        }
200
        if (!isset($options['return_type'])) {
201
            $options['return_type'] = 'boolean';
202
        } else {
203
            if ($options['return_type'] != 'boolean' &&
204
                $options['return_type'] != 'array' &&
205
                $options['return_type'] != 'both'
206
            ) {
207
                throw new InvalidArgumentException();
208
            }
209
        }
210
211
        // Loop through roles and permissions and check each.
212
        $checkedRoles       = [];
213
        $checkedPermissions = [];
214
        foreach ($roles as $role) {
215
            $checkedRoles[$role] = $this->hasRole($role);
216
        }
217
        foreach ($permissions as $permission) {
218
            $checkedPermissions[$permission] = $this->can($permission);
219
        }
220
221
        // If validate all and there is a false in either
222
        // Check that if validate all, then there should not be any false.
223
        // Check that if not validate all, there must be at least one true.
224
        if (($options['validate_all'] && !(in_array(false,
225
                        $checkedRoles) || in_array(false,
226
                        $checkedPermissions))) ||
227
            (!$options['validate_all'] && (in_array(true,
228
                        $checkedRoles) || in_array(true, $checkedPermissions)))
229
        ) {
230
            $validateAll = true;
231
        } else {
232
            $validateAll = false;
233
        }
234
235
        // Return based on option
236
        if ($options['return_type'] == 'boolean') {
237
            return $validateAll;
238
        } elseif ($options['return_type'] == 'array') {
239
            return [
240
                'roles' => $checkedRoles, 'permissions' => $checkedPermissions,
241
            ];
242
        } else {
243
            return [
244
                $validateAll,
245
                ['roles' => $checkedRoles, 'permissions' => $checkedPermissions],
246
            ];
247
        }
248
249
    }
250
251
    /**
252
     * Alias to eloquent many-to-many relation's attach() method.
253
     *
254
     * @param mixed $role
255
     */
256 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...
257
    {
258
        if (is_object($role)) {
259
            $role = $role->getKey();
260
        }
261
262
        if (is_array($role)) {
263
            $role = $role['id'];
264
        }
265
266
        $this->roles()->attach($role);
267
    }
268
269
    /**
270
     * Alias to eloquent many-to-many relation's detach() method.
271
     *
272
     * @param mixed $role
273
     */
274 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...
275
    {
276
        if (is_object($role)) {
277
            $role = $role->getKey();
278
        }
279
280
        if (is_array($role)) {
281
            $role = $role['id'];
282
        }
283
284
        $this->roles()->detach($role);
285
    }
286
287
    /**
288
     * Attach multiple roles to a user
289
     *
290
     * @param mixed $roles
291
     */
292
    public function attachRoles($roles)
293
    {
294
        foreach ($roles as $role) {
295
            $this->attachRole($role);
296
        }
297
    }
298
299
    /**
300
     * Detach multiple roles from a user
301
     *
302
     * @param mixed $roles
303
     */
304
    public function detachRoles($roles = null)
305
    {
306
        if (!$roles) {
307
            $roles = $this->roles()->get();
308
        }
309
310
        foreach ($roles as $role) {
311
            $this->detachRole($role);
312
        }
313
    }
314
315
}
316