Completed
Push — master ( d0a2fb...24f446 )
by Chris
14s queued 12s
created

HasPermissions   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 454
Duplicated Lines 24.45 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 111
loc 454
rs 3.36
c 0
b 0
f 0
wmc 63
lcom 1
cbo 6

25 Methods

Rating   Name   Duplication   Size   Complexity  
A getPermissionClass() 0 8 2
A permissions() 0 10 1
A scopePermission() 0 27 4
A bootHasPermissions() 10 10 3
A convertToPermissionModels() 0 16 4
A hasPermissionTo() 0 24 5
A hasUncachedPermissionTo() 0 4 1
A checkPermissionTo() 0 8 2
A hasAnyPermission() 14 14 4
A hasAllPermissions() 14 14 4
A hasPermissionViaRole() 0 4 1
A hasDirectPermission() 0 18 4
A getPermissionsViaRoles() 0 7 1
A getAllPermissions() 0 11 2
B givePermissionTo() 45 45 5
A syncPermissions() 0 6 1
A revokePermissionTo() 0 10 1
A getPermissionNames() 0 4 1
A getStoredPermission() 0 21 4
A ensureModelSharesGuard() 0 6 2
A getGuardNames() 0 4 1
A getDefaultGuardName() 0 4 1
A forgetCachedPermissions() 0 4 1
A hasAllDirectPermissions() 14 14 4
A hasAnyDirectPermission() 14 14 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 HasPermissions 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 HasPermissions, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Spatie\Permission\Traits;
4
5
use Spatie\Permission\Guard;
6
use Illuminate\Support\Collection;
7
use Illuminate\Database\Eloquent\Builder;
8
use Spatie\Permission\PermissionRegistrar;
9
use Spatie\Permission\Contracts\Permission;
10
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
11
use Illuminate\Database\Eloquent\Relations\MorphToMany;
12
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
13
14
trait HasPermissions
15
{
16
    private $permissionClass;
17
18 View Code Duplication
    public static function bootHasPermissions()
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...
19
    {
20
        static::deleting(function ($model) {
21
            if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
22
                return;
23
            }
24
25
            $model->permissions()->detach();
26
        });
27
    }
28
29
    public function getPermissionClass()
30
    {
31
        if (! isset($this->permissionClass)) {
32
            $this->permissionClass = app(PermissionRegistrar::class)->getPermissionClass();
33
        }
34
35
        return $this->permissionClass;
36
    }
37
38
    /**
39
     * A model may have multiple direct permissions.
40
     */
41
    public function permissions(): MorphToMany
42
    {
43
        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...
44
            config('permission.models.permission'),
45
            'model',
46
            config('permission.table_names.model_has_permissions'),
47
            config('permission.column_names.model_morph_key'),
48
            'permission_id'
49
        );
50
    }
51
52
    /**
53
     * Scope the model query to certain permissions only.
54
     *
55
     * @param \Illuminate\Database\Eloquent\Builder $query
56
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
57
     *
58
     * @return \Illuminate\Database\Eloquent\Builder
59
     */
60
    public function scopePermission(Builder $query, $permissions): Builder
61
    {
62
        $permissions = $this->convertToPermissionModels($permissions);
63
64
        $rolesWithPermissions = array_unique(array_reduce($permissions, function ($result, $permission) {
65
            return array_merge($result, $permission->roles->all());
66
        }, []));
67
68
        return $query->where(function ($query) use ($permissions, $rolesWithPermissions) {
69
            $query->whereHas('permissions', function ($query) use ($permissions) {
70
                $query->where(function ($query) use ($permissions) {
71
                    foreach ($permissions as $permission) {
72
                        $query->orWhere(config('permission.table_names.permissions').'.id', $permission->id);
73
                    }
74
                });
75
            });
76
            if (count($rolesWithPermissions) > 0) {
77
                $query->orWhereHas('roles', function ($query) use ($rolesWithPermissions) {
78
                    $query->where(function ($query) use ($rolesWithPermissions) {
79
                        foreach ($rolesWithPermissions as $role) {
80
                            $query->orWhere(config('permission.table_names.roles').'.id', $role->id);
81
                        }
82
                    });
83
                });
84
            }
85
        });
86
    }
87
88
    /**
89
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
90
     *
91
     * @return array
92
     */
93
    protected function convertToPermissionModels($permissions): array
94
    {
95
        if ($permissions instanceof Collection) {
96
            $permissions = $permissions->all();
97
        }
98
99
        $permissions = is_array($permissions) ? $permissions : [$permissions];
100
101
        return array_map(function ($permission) {
102
            if ($permission instanceof Permission) {
103
                return $permission;
104
            }
105
106
            return $this->getPermissionClass()->findByName($permission, $this->getDefaultGuardName());
107
        }, $permissions);
108
    }
109
110
    /**
111
     * Determine if the model may perform the given permission.
112
     *
113
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
114
     * @param string|null $guardName
115
     *
116
     * @return bool
117
     * @throws PermissionDoesNotExist
118
     */
119
    public function hasPermissionTo($permission, $guardName = null): bool
120
    {
121
        $permissionClass = $this->getPermissionClass();
122
123
        if (is_string($permission)) {
124
            $permission = $permissionClass->findByName(
125
                $permission,
126
                $guardName ?? $this->getDefaultGuardName()
127
            );
128
        }
129
130
        if (is_int($permission)) {
131
            $permission = $permissionClass->findById(
132
                $permission,
133
                $guardName ?? $this->getDefaultGuardName()
134
            );
135
        }
136
137
        if (! $permission instanceof Permission) {
138
            throw new PermissionDoesNotExist;
139
        }
140
141
        return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
142
    }
143
144
    /**
145
     * @deprecated since 2.35.0
146
     * @alias of hasPermissionTo()
147
     */
148
    public function hasUncachedPermissionTo($permission, $guardName = null): bool
149
    {
150
        return $this->hasPermissionTo($permission, $guardName);
151
    }
152
153
    /**
154
     * An alias to hasPermissionTo(), but avoids throwing an exception.
155
     *
156
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
157
     * @param string|null $guardName
158
     *
159
     * @return bool
160
     */
161
    public function checkPermissionTo($permission, $guardName = null): bool
162
    {
163
        try {
164
            return $this->hasPermissionTo($permission, $guardName);
165
        } catch (PermissionDoesNotExist $e) {
166
            return false;
167
        }
168
    }
169
170
    /**
171
     * Determine if the model has any of the given permissions.
172
     *
173
     * @param array ...$permissions
174
     *
175
     * @return bool
176
     * @throws \Exception
177
     */
178 View Code Duplication
    public function hasAnyPermission(...$permissions): bool
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...
179
    {
180
        if (is_array($permissions[0])) {
181
            $permissions = $permissions[0];
182
        }
183
184
        foreach ($permissions as $permission) {
185
            if ($this->checkPermissionTo($permission)) {
186
                return true;
187
            }
188
        }
189
190
        return false;
191
    }
192
193
    /**
194
     * Determine if the model has all of the given permissions.
195
     *
196
     * @param array ...$permissions
197
     *
198
     * @return bool
199
     * @throws \Exception
200
     */
201 View Code Duplication
    public function hasAllPermissions(...$permissions): bool
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...
202
    {
203
        if (is_array($permissions[0])) {
204
            $permissions = $permissions[0];
205
        }
206
207
        foreach ($permissions as $permission) {
208
            if (! $this->hasPermissionTo($permission)) {
209
                return false;
210
            }
211
        }
212
213
        return true;
214
    }
215
216
    /**
217
     * Determine if the model has, via roles, the given permission.
218
     *
219
     * @param \Spatie\Permission\Contracts\Permission $permission
220
     *
221
     * @return bool
222
     */
223
    protected function hasPermissionViaRole(Permission $permission): bool
224
    {
225
        return $this->hasRole($permission->roles);
0 ignored issues
show
Bug introduced by
Accessing roles on the interface Spatie\Permission\Contracts\Permission 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...
Bug introduced by
It seems like hasRole() 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...
226
    }
227
228
    /**
229
     * Determine if the model has the given permission.
230
     *
231
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
232
     *
233
     * @return bool
234
     * @throws PermissionDoesNotExist
235
     */
236
    public function hasDirectPermission($permission): bool
237
    {
238
        $permissionClass = $this->getPermissionClass();
239
240
        if (is_string($permission)) {
241
            $permission = $permissionClass->findByName($permission, $this->getDefaultGuardName());
242
        }
243
244
        if (is_int($permission)) {
245
            $permission = $permissionClass->findById($permission, $this->getDefaultGuardName());
246
        }
247
248
        if (! $permission instanceof Permission) {
249
            throw new PermissionDoesNotExist;
250
        }
251
252
        return $this->permissions->contains('id', $permission->id);
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...
Bug introduced by
Accessing id on the interface Spatie\Permission\Contracts\Permission 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...
253
    }
254
255
    /**
256
     * Return all the permissions the model has via roles.
257
     */
258
    public function getPermissionsViaRoles(): Collection
259
    {
260
        return $this->loadMissing('roles', 'roles.permissions')
0 ignored issues
show
Bug introduced by
It seems like loadMissing() 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...
261
            ->roles->flatMap(function ($role) {
262
                return $role->permissions;
263
            })->sort()->values();
264
    }
265
266
    /**
267
     * Return all the permissions the model has, both directly and via roles.
268
     */
269
    public function getAllPermissions(): Collection
270
    {
271
        /** @var Collection $permissions */
272
        $permissions = $this->permissions;
273
274
        if ($this->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...
275
            $permissions = $permissions->merge($this->getPermissionsViaRoles());
276
        }
277
278
        return $permissions->sort()->values();
279
    }
280
281
    /**
282
     * Grant the given permission(s) to a role.
283
     *
284
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
285
     *
286
     * @return $this
287
     */
288 View Code Duplication
    public function givePermissionTo(...$permissions)
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...
289
    {
290
        $permissions = collect($permissions)
291
            ->flatten()
292
            ->map(function ($permission) {
293
                if (empty($permission)) {
294
                    return false;
295
                }
296
297
                return $this->getStoredPermission($permission);
298
            })
299
            ->filter(function ($permission) {
300
                return $permission instanceof Permission;
301
            })
302
            ->each(function ($permission) {
303
                $this->ensureModelSharesGuard($permission);
304
            })
305
            ->map->id
306
            ->all();
307
308
        $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...
309
310
        if ($model->exists) {
311
            $this->permissions()->sync($permissions, false);
312
            $model->load('permissions');
313
        } else {
314
            $class = \get_class($model);
315
316
            $class::saved(
317
                function ($object) use ($permissions, $model) {
318
                    static $modelLastFiredOn;
319
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
320
                        return;
321
                    }
322
                    $object->permissions()->sync($permissions, false);
323
                    $object->load('permissions');
324
                    $modelLastFiredOn = $object;
325
                }
326
            );
327
        }
328
329
        $this->forgetCachedPermissions();
330
331
        return $this;
332
    }
333
334
    /**
335
     * Remove all current permissions and set the given ones.
336
     *
337
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
338
     *
339
     * @return $this
340
     */
341
    public function syncPermissions(...$permissions)
342
    {
343
        $this->permissions()->detach();
344
345
        return $this->givePermissionTo($permissions);
346
    }
347
348
    /**
349
     * Revoke the given permission.
350
     *
351
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|string|string[] $permission
352
     *
353
     * @return $this
354
     */
355
    public function revokePermissionTo($permission)
356
    {
357
        $this->permissions()->detach($this->getStoredPermission($permission));
358
359
        $this->forgetCachedPermissions();
360
361
        $this->load('permissions');
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...
362
363
        return $this;
364
    }
365
366
    public function getPermissionNames(): Collection
367
    {
368
        return $this->permissions->pluck('name');
369
    }
370
371
    /**
372
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
373
     *
374
     * @return \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|\Illuminate\Support\Collection
375
     */
376
    protected function getStoredPermission($permissions)
377
    {
378
        $permissionClass = $this->getPermissionClass();
379
380
        if (is_numeric($permissions)) {
381
            return $permissionClass->findById($permissions, $this->getDefaultGuardName());
382
        }
383
384
        if (is_string($permissions)) {
385
            return $permissionClass->findByName($permissions, $this->getDefaultGuardName());
386
        }
387
388
        if (is_array($permissions)) {
389
            return $permissionClass
390
                ->whereIn('name', $permissions)
391
                ->whereIn('guard_name', $this->getGuardNames())
392
                ->get();
393
        }
394
395
        return $permissions;
396
    }
397
398
    /**
399
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Role $roleOrPermission
400
     *
401
     * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
402
     */
403
    protected function ensureModelSharesGuard($roleOrPermission)
404
    {
405
        if (! $this->getGuardNames()->contains($roleOrPermission->guard_name)) {
406
            throw GuardDoesNotMatch::create($roleOrPermission->guard_name, $this->getGuardNames());
407
        }
408
    }
409
410
    protected function getGuardNames(): Collection
411
    {
412
        return Guard::getNames($this);
413
    }
414
415
    protected function getDefaultGuardName(): string
416
    {
417
        return Guard::getDefaultName($this);
418
    }
419
420
    /**
421
     * Forget the cached permissions.
422
     */
423
    public function forgetCachedPermissions()
424
    {
425
        app(PermissionRegistrar::class)->forgetCachedPermissions();
426
    }
427
428
    /**
429
     * Check if the model has All of the requested Direct permissions.
430
     * @param array ...$permissions
431
     * @return bool
432
     */
433 View Code Duplication
    public function hasAllDirectPermissions(...$permissions) : bool
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...
434
    {
435
        if (is_array($permissions[0])) {
436
            $permissions = $permissions[0];
437
        }
438
439
        foreach ($permissions as $permission) {
440
            if (! $this->hasDirectPermission($permission)) {
441
                return false;
442
            }
443
        }
444
445
        return true;
446
    }
447
448
    /**
449
     * Check if the model has Any of the requested Direct permissions.
450
     * @param array ...$permissions
451
     * @return bool
452
     */
453 View Code Duplication
    public function hasAnyDirectPermission(...$permissions) : bool
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...
454
    {
455
        if (is_array($permissions[0])) {
456
            $permissions = $permissions[0];
457
        }
458
        
459
        foreach ($permissions as $permission) {
460
            if ($this->hasDirectPermission($permission)) {
461
                return true;
462
            }
463
        }
464
465
        return false;
466
    }
467
}
468