Completed
Push — master ( 2a6b50...9cebff )
by Chris
01:27
created

HasRoles   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 298
Duplicated Lines 20.81 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 62
loc 298
rs 8.4
c 0
b 0
f 0
wmc 50
lcom 1
cbo 4

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getRoleClass() 0 8 2
A roles() 0 10 1
A bootHasRoles() 0 10 3
B scopeRole() 0 29 7
B assignRole() 44 44 5
A removeRole() 0 10 1
A syncRoles() 0 6 1
C hasRole() 11 34 12
A hasAnyRole() 0 4 1
B hasAllRoles() 7 25 8
A getDirectPermissions() 0 4 1
A getRoleNames() 0 4 1
A getStoredRole() 0 14 3
A convertPipeToArray() 0 21 4

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 HasRoles 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 HasRoles, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Spatie\Permission\Traits;
4
5
use Illuminate\Support\Collection;
6
use Spatie\Permission\Contracts\Role;
7
use Illuminate\Database\Eloquent\Builder;
8
use Spatie\Permission\PermissionRegistrar;
9
use Illuminate\Database\Eloquent\Relations\MorphToMany;
10
11
trait HasRoles
12
{
13
    use HasPermissions;
14
15
    private $roleClass;
16
17
    public static function bootHasRoles()
18
    {
19
        static::deleting(function ($model) {
20
            if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
21
                return;
22
            }
23
24
            $model->roles()->detach();
25
        });
26
    }
27
28
    public function getRoleClass()
29
    {
30
        if (! isset($this->roleClass)) {
31
            $this->roleClass = app(PermissionRegistrar::class)->getRoleClass();
32
        }
33
34
        return $this->roleClass;
35
    }
36
37
    /**
38
     * A model may have multiple roles.
39
     */
40
    public function roles(): MorphToMany
41
    {
42
        return $this->morphToMany(
0 ignored issues
show
Bug introduced by
It seems like morphToMany() 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...
43
            config('permission.models.role'),
44
            'model',
45
            config('permission.table_names.model_has_roles'),
46
            config('permission.column_names.model_morph_key'),
47
            'role_id'
48
        );
49
    }
50
51
    /**
52
     * Scope the model query to certain roles only.
53
     *
54
     * @param \Illuminate\Database\Eloquent\Builder $query
55
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
56
     * @param string $guard
57
     *
58
     * @return \Illuminate\Database\Eloquent\Builder
59
     */
60
    public function scopeRole(Builder $query, $roles, $guard = null): Builder
61
    {
62
        if ($roles instanceof Collection) {
63
            $roles = $roles->all();
64
        }
65
66
        if (! is_array($roles)) {
67
            $roles = [$roles];
68
        }
69
70
        $roles = array_map(function ($role) use ($guard) {
71
            if ($role instanceof Role) {
72
                return $role;
73
            }
74
75
            $method = is_numeric($role) ? 'findById' : 'findByName';
76
            $guard = $guard ?: $this->getDefaultGuardName();
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $guard, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
77
78
            return $this->getRoleClass()->{$method}($role, $guard);
79
        }, $roles);
80
81
        return $query->whereHas('roles', function ($query) use ($roles) {
82
            $query->where(function ($query) use ($roles) {
83
                foreach ($roles as $role) {
84
                    $query->orWhere(config('permission.table_names.roles').'.id', $role->id);
85
                }
86
            });
87
        });
88
    }
89
90
    /**
91
     * Assign the given role to the model.
92
     *
93
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
94
     *
95
     * @return $this
96
     */
97 View Code Duplication
    public function assignRole(...$roles)
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...
98
    {
99
        $roles = collect($roles)
100
            ->flatten()
101
            ->map(function ($role) {
102
                if (empty($role)) {
103
                    return false;
104
                }
105
106
                return $this->getStoredRole($role);
107
            })
108
            ->filter(function ($role) {
109
                return $role instanceof Role;
110
            })
111
            ->each(function ($role) {
112
                $this->ensureModelSharesGuard($role);
113
            })
114
            ->map->id
115
            ->all();
116
117
        $model = $this->getModel();
0 ignored issues
show
Bug introduced by
It seems like getModel() 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...
118
119
        if ($model->exists) {
120
            $this->roles()->sync($roles, false);
121
            $model->load('roles');
122
        } else {
123
            $class = \get_class($model);
124
125
            $class::saved(
126
                function ($object) use ($roles, $model) {
127
                    static $modelLastFiredOn;
128
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
129
                        return;
130
                    }
131
                    $object->roles()->sync($roles, false);
132
                    $object->load('roles');
133
                    $modelLastFiredOn = $object;
134
                });
135
        }
136
137
        $this->forgetCachedPermissions();
138
139
        return $this;
140
    }
141
142
    /**
143
     * Revoke the given role from the model.
144
     *
145
     * @param string|\Spatie\Permission\Contracts\Role $role
146
     */
147
    public function removeRole($role)
148
    {
149
        $this->roles()->detach($this->getStoredRole($role));
150
151
        $this->load('roles');
0 ignored issues
show
Bug introduced by
It seems like load() 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...
152
153
        $this->forgetCachedPermissions();
154
155
        return $this;
156
    }
157
158
    /**
159
     * Remove all current roles and set the given ones.
160
     *
161
     * @param  array|\Spatie\Permission\Contracts\Role|string  ...$roles
162
     *
163
     * @return $this
164
     */
165
    public function syncRoles(...$roles)
166
    {
167
        $this->roles()->detach();
168
169
        return $this->assignRole($roles);
170
    }
171
172
    /**
173
     * Determine if the model has (one of) the given role(s).
174
     *
175
     * @param string|int|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
176
     * @param string|null $guard
177
     * @return bool
178
     */
179
    public function hasRole($roles, string $guard = null): bool
180
    {
181 View Code Duplication
        if (is_string($roles) && false !== strpos($roles, '|')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
182
            $roles = $this->convertPipeToArray($roles);
183
        }
184
185 View Code Duplication
        if (is_string($roles)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
186
            return $guard
187
                ? $this->roles->where('guard_name', $guard)->contains('name', $roles)
0 ignored issues
show
Bug introduced by
The property roles 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...
188
                : $this->roles->contains('name', $roles);
189
        }
190
191 View Code Duplication
        if (is_int($roles)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
192
            return $guard
193
                ? $this->roles->where('guard_name', $guard)->contains('id', $roles)
194
                : $this->roles->contains('id', $roles);
195
        }
196
197
        if ($roles instanceof Role) {
198
            return $this->roles->contains('id', $roles->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Spatie\Permission\Contracts\Role suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
199
        }
200
201
        if (is_array($roles)) {
202
            foreach ($roles as $role) {
203
                if ($this->hasRole($role, $guard)) {
204
                    return true;
205
                }
206
            }
207
208
            return false;
209
        }
210
211
        return $roles->intersect($guard ? $this->roles->where('guard_name', $guard) : $this->roles)->isNotEmpty();
212
    }
213
214
    /**
215
     * Determine if the model has any of the given role(s).
216
     *
217
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
218
     *
219
     * @return bool
220
     */
221
    public function hasAnyRole($roles): bool
222
    {
223
        return $this->hasRole($roles);
224
    }
225
226
    /**
227
     * Determine if the model has all of the given role(s).
228
     *
229
     * @param  string|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection  $roles
230
     * @param  string|null  $guard
231
     * @return bool
232
     */
233
    public function hasAllRoles($roles, string $guard = null): bool
234
    {
235 View Code Duplication
        if (is_string($roles) && false !== strpos($roles, '|')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
236
            $roles = $this->convertPipeToArray($roles);
237
        }
238
239 View Code Duplication
        if (is_string($roles)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
240
            return $guard
241
                ? $this->roles->where('guard_name', $guard)->contains('name', $roles)
242
                : $this->roles->contains('name', $roles);
243
        }
244
245
        if ($roles instanceof Role) {
246
            return $this->roles->contains('id', $roles->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Spatie\Permission\Contracts\Role suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
247
        }
248
249
        $roles = collect()->make($roles)->map(function ($role) {
250
            return $role instanceof Role ? $role->name : $role;
0 ignored issues
show
Bug introduced by
Accessing name on the interface Spatie\Permission\Contracts\Role suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
251
        });
252
253
        return $roles->intersect(
254
            $guard
255
                ? $this->roles->where('guard_name', $guard)->pluck('name')
256
                : $this->getRoleNames()) == $roles;
257
    }
258
259
    /**
260
     * Return all permissions directly coupled to the model.
261
     */
262
    public function getDirectPermissions(): Collection
263
    {
264
        return $this->permissions;
0 ignored issues
show
Bug introduced by
The property permissions 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...
265
    }
266
267
    public function getRoleNames(): Collection
268
    {
269
        return $this->roles->pluck('name');
270
    }
271
272
    protected function getStoredRole($role): Role
273
    {
274
        $roleClass = $this->getRoleClass();
275
276
        if (is_numeric($role)) {
277
            return $roleClass->findById($role, $this->getDefaultGuardName());
278
        }
279
280
        if (is_string($role)) {
281
            return $roleClass->findByName($role, $this->getDefaultGuardName());
282
        }
283
284
        return $role;
285
    }
286
287
    protected function convertPipeToArray(string $pipeString)
288
    {
289
        $pipeString = trim($pipeString);
290
291
        if (strlen($pipeString) <= 2) {
292
            return $pipeString;
293
        }
294
295
        $quoteCharacter = substr($pipeString, 0, 1);
296
        $endCharacter = substr($quoteCharacter, -1, 1);
297
298
        if ($quoteCharacter !== $endCharacter) {
299
            return explode('|', $pipeString);
300
        }
301
302
        if (! in_array($quoteCharacter, ["'", '"'])) {
303
            return explode('|', $pipeString);
304
        }
305
306
        return explode('|', trim($pipeString, $quoteCharacter));
307
    }
308
}
309