Completed
Pull Request — master (#1381)
by Stefan
01:36
created

HasPermissions::hasWildcardPermission()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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