Completed
Pull Request — master (#926)
by
unknown
02:11
created

HasPermissions::hasPermissionViaRole()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Permission\Traits;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Relations\MorphToMany;
7
use Illuminate\Support\Collection;
8
use Spatie\Permission\Contracts\Permission;
9
use Spatie\Permission\Exceptions\GuardDoesNotMatch;
10
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
11
use Spatie\Permission\Guard;
12
use Spatie\Permission\PermissionRegistrar;
13
14
trait HasPermissions
15
{
16
    private $permissionClass;
17
18
    public static function bootHasPermissions()
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 = array_wrap($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 \Exception
118
     */
119
    public function hasPermissionTo($permission, $guardName = null): bool
120
    {
121
        $config = config('permission');
122
123
        if (PermissionRegistrar::$cacheIsTaggable &&
124
            (is_string($permission) || is_int($permission) || $permission instanceof $config['models']['permission'])
125
        ) {
126
            return cache()
127
                ->tags($this->getCacheTags($config, $permission))
128
                ->remember($this->getCacheKey($config, $permission), $config['cache']['expiration_time'],
129
                    function () use ($permission, $guardName) {
130
                        return $this->checkHasPermissionTo($permission, $guardName);
0 ignored issues
show
Bug introduced by
It seems like $guardName defined by parameter $guardName on line 119 can also be of type string; however, Spatie\Permission\Traits...:checkHasPermissionTo() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
131
                    });
132
        }
133
134
        return $this->checkHasPermissionTo($permission, $guardName);
0 ignored issues
show
Bug introduced by
It seems like $guardName defined by parameter $guardName on line 119 can also be of type string; however, Spatie\Permission\Traits...:checkHasPermissionTo() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
135
    }
136
137
    /**
138
     * Check the uncached permissions for the model.
139
     *
140
     * @param      $permission
141
     * @param null $guardName
142
     *
143
     * @return bool
144
     */
145
    public function checkHasPermissionTo($permission, $guardName = null)
146
    {
147
        $permissionClass = $this->getPermissionClass();
148
149
        if (is_string($permission)) {
150
            $permission = $permissionClass->findByName(
151
                $permission,
152
                $guardName ?? $this->getDefaultGuardName()
153
            );
154
        }
155
156
        if (is_int($permission)) {
157
            $permission = $permissionClass->findById(
158
                $permission,
159
                $guardName ?? $this->getDefaultGuardName()
160
            );
161
        }
162
163
        if (!$permission instanceof Permission) {
164
            throw new PermissionDoesNotExist;
165
        }
166
167
        return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
168
    }
169
170
    /**
171
     * An alias to hasPermissionTo(), but avoids throwing an exception.
172
     *
173
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
174
     * @param string|null                                        $guardName
175
     *
176
     * @return bool
177
     *
178
     * @throws \Exception
179
     */
180
    public function checkPermissionTo($permission, $guardName = null): bool
181
    {
182
        try {
183
            return $this->hasPermissionTo($permission, $guardName);
184
        } catch (PermissionDoesNotExist $e) {
185
            return false;
186
        }
187
    }
188
189
    /**
190
     * Construct the key for the cache entry.
191
     *
192
     * @param array                                                   $config
193
     * @param null|string|int|\Spatie\Permission\Contracts\Permission $permission
194
     *
195
     * @return string
196
     */
197
    protected function getCacheKey(array $config, $permission = null)
198
    {
199
        $key = $config['cache']['key'] . '.' . $this->getClassCacheString();
200
201
        if ($permission !== null) {
202
            $key .= $this->getPermissionCacheString($config, $permission);
203
        }
204
205
        return $key;
206
    }
207
208
    /**
209
     * Construct the tags for the cache entry.
210
     *
211
     * @param array                                                   $config
212
     * @param null|string|int|\Spatie\Permission\Contracts\Permission $permission
213
     *
214
     * @return array
215
     */
216
    protected function getCacheTags(array $config, $permission = null)
217
    {
218
        $tags = [
219
            $config['cache']['key'],
220
            $this->getClassCacheString(),
221
        ];
222
223
        if ($permission !== null) {
224
            $tags[] = $this->getPermissionCacheString($config, $permission);
225
        }
226
227
        return $tags;
228
    }
229
230
    /**
231
     * Get the configured key to cache the model by.
232
     *
233
     * @return string
234
     */
235
    protected function getClassCacheString()
236
    {
237
        return str_replace('\\', '.', get_class($this)) . '.' . $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...
238
    }
239
240
    /**
241
     * Get the configured key to cache the permission by.
242
     *
243
     * @param array                                              $config
244
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
245
     *
246
     * @return mixed
247
     */
248
    protected function getPermissionCacheString(array $config, $permission)
249
    {
250
        if ($permission instanceof $config['models']['permission']) {
251
            $permission = $permission[$config['cache']['default_model_attribute']];
252
        }
253
254
        return str_replace('\\', '.', $config['models']['permission']) . '.' . $permission;
255
    }
256
257
    /**
258
     * Determine if the model has any of the given permissions.
259
     *
260
     * @param array ...$permissions
261
     *
262
     * @return bool
263
     * @throws \Exception
264
     */
265 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...
266
    {
267
        if (is_array($permissions[0])) {
268
            $permissions = $permissions[0];
269
        }
270
271
        foreach ($permissions as $permission) {
272
            if ($this->checkPermissionTo($permission)) {
273
                return true;
274
            }
275
        }
276
277
        return false;
278
    }
279
280
    /**
281
     * Determine if the model has all of the given permissions.
282
     *
283
     * @param array ...$permissions
284
     *
285
     * @return bool
286
     * @throws \Exception
287
     */
288 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...
289
    {
290
        if (is_array($permissions[0])) {
291
            $permissions = $permissions[0];
292
        }
293
294
        foreach ($permissions as $permission) {
295
            if (!$this->hasPermissionTo($permission)) {
296
                return false;
297
            }
298
        }
299
300
        return true;
301
    }
302
303
    /**
304
     * Determine if the model has, via roles, the given permission.
305
     *
306
     * @param \Spatie\Permission\Contracts\Permission $permission
307
     *
308
     * @return bool
309
     */
310
    protected function hasPermissionViaRole(Permission $permission): bool
311
    {
312
        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...
313
    }
314
315
    /**
316
     * Determine if the model has the given permission.
317
     *
318
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
319
     *
320
     * @return bool
321
     */
322
    public function hasDirectPermission($permission): bool
323
    {
324
        $permissionClass = $this->getPermissionClass();
325
326
        if (is_string($permission)) {
327
            $permission = $permissionClass->findByName($permission, $this->getDefaultGuardName());
328
            if (!$permission) {
329
                return false;
330
            }
331
        }
332
333
        if (is_int($permission)) {
334
            $permission = $permissionClass->findById($permission, $this->getDefaultGuardName());
335
            if (!$permission) {
336
                return false;
337
            }
338
        }
339
340
        if (!$permission instanceof Permission) {
341
            return false;
342
        }
343
344
        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...
345
    }
346
347
    /**
348
     * Return all the permissions the model has via roles.
349
     */
350
    public function getPermissionsViaRoles(): Collection
351
    {
352
        return $this->load('roles', 'roles.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...
353
            ->roles->flatMap(function ($role) {
354
                return $role->permissions;
355
            })->sort()->values();
356
    }
357
358
    /**
359
     * Return all the permissions the model has, both directly and via roles.
360
     */
361
    public function getAllPermissions(): Collection
362
    {
363
        if (PermissionRegistrar::$cacheIsTaggable) {
364
            $config = config('permission');
365
366
            return cache()->tags($this->getCacheTags($config))
367
                ->remember($this->getCacheKey($config), $config['cache']['expiration_time'], function () {
368
                    $permissions = $this->permissions;
369
370
                    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...
371
                        $permissions = $permissions->merge($this->getPermissionsViaRoles());
372
                    }
373
374
                    return $permissions->sort()->values();
375
                });
376
        }
377
378
        $permissions = $this->permissions;
379
380
        if ($this->roles) {
381
            $permissions = $permissions->merge($this->getPermissionsViaRoles());
382
        }
383
384
        return $permissions->sort()->values();
385
    }
386
387
    /**
388
     * Grant the given permission(s) to a role.
389
     *
390
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
391
     *
392
     * @return $this
393
     */
394 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...
395
    {
396
        $permissions = collect($permissions)
397
            ->flatten()
398
            ->map(function ($permission) {
399
                return $this->getStoredPermission($permission);
400
            })
401
            ->filter(function ($permission) {
402
                return $permission instanceof Permission;
403
            })
404
            ->each(function ($permission) {
405
                $this->ensureModelSharesGuard($permission);
406
            })
407
            ->map->id
408
            ->all();
409
410
        $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...
411
412
        if ($model->exists) {
413
            $this->permissions()->sync($permissions, false);
414
            $model->load('permissions');
415
        } else {
416
            $class = \get_class($model);
417
418
            $class::saved(
419
                function ($model) use ($permissions) {
420
                    $model->permissions()->sync($permissions, false);
421
                    $model->load('permissions');
422
                });
423
        }
424
425
        $this->forgetCachedPermissions();
426
427
        return $this;
428
    }
429
430
    /**
431
     * Remove all current permissions and set the given ones.
432
     *
433
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
434
     *
435
     * @return $this
436
     */
437
    public function syncPermissions(...$permissions)
438
    {
439
        $this->permissions()->detach();
440
441
        return $this->givePermissionTo($permissions);
442
    }
443
444
    /**
445
     * Revoke the given permission.
446
     *
447
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|string|string[] $permission
448
     *
449
     * @return $this
450
     */
451
    public function revokePermissionTo($permission)
452
    {
453
        $this->permissions()->detach($this->getStoredPermission($permission));
454
455
        $this->forgetCachedPermissions();
456
457
        $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...
458
459
        return $this;
460
    }
461
462
    /**
463
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
464
     *
465
     * @return \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|\Illuminate\Support\Collection
466
     */
467
    protected function getStoredPermission($permissions)
468
    {
469
        $permissionClass = $this->getPermissionClass();
470
471
        if (is_numeric($permissions)) {
472
            return $permissionClass->findById($permissions, $this->getDefaultGuardName());
473
        }
474
475
        if (is_string($permissions)) {
476
            return $permissionClass->findByName($permissions, $this->getDefaultGuardName());
477
        }
478
479
        if (is_array($permissions)) {
480
            return $permissionClass
481
                ->whereIn('name', $permissions)
482
                ->whereIn('guard_name', $this->getGuardNames())
483
                ->get();
484
        }
485
486
        return $permissions;
487
    }
488
489
    /**
490
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Role $roleOrPermission
491
     *
492
     * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
493
     */
494
    protected function ensureModelSharesGuard($roleOrPermission)
495
    {
496
        if (!$this->getGuardNames()->contains($roleOrPermission->guard_name)) {
497
            throw GuardDoesNotMatch::create($roleOrPermission->guard_name, $this->getGuardNames());
498
        }
499
    }
500
501
    protected function getGuardNames(): Collection
502
    {
503
        return Guard::getNames($this);
504
    }
505
506
    protected function getDefaultGuardName(): string
507
    {
508
        return Guard::getDefaultName($this);
509
    }
510
511
    /**
512
     * Forget the cached permissions.
513
     */
514
    public function forgetCachedPermissions()
515
    {
516
        app(PermissionRegistrar::class)->forgetCachedPermissions();
517
    }
518
}
519