Completed
Push — master ( f92c85...42c484 )
by Chris
01:36
created

HasPermissions::getClassCacheString()   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 0
dl 0
loc 4
rs 10
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\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
        if (! is_string($permission) && ! is_int($permission) && ! $permission instanceof Permission) {
122
            throw new PermissionDoesNotExist;
123
        }
124
125
        return $this->hasUncachedPermissionTo($permission, $guardName);
126
    }
127
128
    /**
129
     * Check the uncached permissions for the model.
130
     *
131
     * @param string|int|Permission $permission
132
     * @param string|null $guardName
133
     *
134
     * @return bool
135
     *
136
     * @throws PermissionDoesNotExist
137
     */
138
    public function hasUncachedPermissionTo($permission, $guardName = null): bool
139
    {
140
        $permissionClass = $this->getPermissionClass();
141
142
        if (is_string($permission)) {
143
            $permission = $permissionClass->findByName(
144
                $permission,
145
                $guardName ?? $this->getDefaultGuardName()
146
            );
147
        }
148
149
        if (is_int($permission)) {
150
            $permission = $permissionClass->findById(
151
                $permission,
152
                $guardName ?? $this->getDefaultGuardName()
153
            );
154
        }
155
156
        if (! $permission instanceof Permission) {
157
            throw new PermissionDoesNotExist;
158
        }
159
160
        return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
161
    }
162
163
    /**
164
     * An alias to hasPermissionTo(), but avoids throwing an exception.
165
     *
166
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
167
     * @param string|null $guardName
168
     *
169
     * @return bool
170
     */
171
    public function checkPermissionTo($permission, $guardName = null): bool
172
    {
173
        try {
174
            return $this->hasPermissionTo($permission, $guardName);
175
        } catch (PermissionDoesNotExist $e) {
176
            return false;
177
        }
178
    }
179
180
    /**
181
     * Determine if the model has any of the given permissions.
182
     *
183
     * @param array ...$permissions
184
     *
185
     * @return bool
186
     * @throws \Exception
187
     */
188 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...
189
    {
190
        if (is_array($permissions[0])) {
191
            $permissions = $permissions[0];
192
        }
193
194
        foreach ($permissions as $permission) {
195
            if ($this->checkPermissionTo($permission)) {
196
                return true;
197
            }
198
        }
199
200
        return false;
201
    }
202
203
    /**
204
     * Determine if the model has all of the given permissions.
205
     *
206
     * @param array ...$permissions
207
     *
208
     * @return bool
209
     * @throws \Exception
210
     */
211 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...
212
    {
213
        if (is_array($permissions[0])) {
214
            $permissions = $permissions[0];
215
        }
216
217
        foreach ($permissions as $permission) {
218
            if (! $this->hasPermissionTo($permission)) {
219
                return false;
220
            }
221
        }
222
223
        return true;
224
    }
225
226
    /**
227
     * Determine if the model has, via roles, the given permission.
228
     *
229
     * @param \Spatie\Permission\Contracts\Permission $permission
230
     *
231
     * @return bool
232
     */
233
    protected function hasPermissionViaRole(Permission $permission): bool
234
    {
235
        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...
236
    }
237
238
    /**
239
     * Determine if the model has the given permission.
240
     *
241
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
242
     *
243
     * @return bool
244
     */
245
    public function hasDirectPermission($permission): bool
246
    {
247
        $permissionClass = $this->getPermissionClass();
248
249
        if (is_string($permission)) {
250
            $permission = $permissionClass->findByName($permission, $this->getDefaultGuardName());
251
            if (! $permission) {
252
                return false;
253
            }
254
        }
255
256
        if (is_int($permission)) {
257
            $permission = $permissionClass->findById($permission, $this->getDefaultGuardName());
258
            if (! $permission) {
259
                return false;
260
            }
261
        }
262
263
        if (! $permission instanceof Permission) {
264
            return false;
265
        }
266
267
        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...
268
    }
269
270
    /**
271
     * Return all the permissions the model has via roles.
272
     */
273
    public function getPermissionsViaRoles(): Collection
274
    {
275
        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...
276
            ->roles->flatMap(function ($role) {
277
                return $role->permissions;
278
            })->sort()->values();
279
    }
280
281
    /**
282
     * Return all the permissions the model has, both directly and via roles.
283
     *
284
     * @throws \Exception
285
     */
286
    public function getAllPermissions(): Collection
287
    {
288
        $permissions = $this->permissions;
289
290
        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...
291
            $permissions = $permissions->merge($this->getPermissionsViaRoles());
292
        }
293
294
        return $permissions->sort()->values();
295
    }
296
297
    /**
298
     * Grant the given permission(s) to a role.
299
     *
300
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
301
     *
302
     * @return $this
303
     */
304 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...
305
    {
306
        $permissions = collect($permissions)
307
            ->flatten()
308
            ->map(function ($permission) {
309
                if (empty($permission)) {
310
                    return false;
311
                }
312
313
                return $this->getStoredPermission($permission);
314
            })
315
            ->filter(function ($permission) {
316
                return $permission instanceof Permission;
317
            })
318
            ->each(function ($permission) {
319
                $this->ensureModelSharesGuard($permission);
320
            })
321
            ->map->id
322
            ->all();
323
324
        $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...
325
326
        if ($model->exists) {
327
            $this->permissions()->sync($permissions, false);
328
            $model->load('permissions');
329
        } else {
330
            $class = \get_class($model);
331
332
            $class::saved(
333
                function ($object) use ($permissions, $model) {
334
                    static $modelLastFiredOn;
335
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
336
                        return;
337
                    }
338
                    $object->permissions()->sync($permissions, false);
339
                    $object->load('permissions');
340
                    $modelLastFiredOn = $object;
341
                }
342
            );
343
        }
344
345
        $this->forgetCachedPermissions();
346
347
        return $this;
348
    }
349
350
    /**
351
     * Remove all current permissions and set the given ones.
352
     *
353
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
354
     *
355
     * @return $this
356
     */
357
    public function syncPermissions(...$permissions)
358
    {
359
        $this->permissions()->detach();
360
361
        return $this->givePermissionTo($permissions);
362
    }
363
364
    /**
365
     * Revoke the given permission.
366
     *
367
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|string|string[] $permission
368
     *
369
     * @return $this
370
     */
371
    public function revokePermissionTo($permission)
372
    {
373
        $this->permissions()->detach($this->getStoredPermission($permission));
374
375
        $this->forgetCachedPermissions();
376
377
        $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...
378
379
        return $this;
380
    }
381
382
    public function getPermissionNames(): Collection
383
    {
384
        return $this->permissions->pluck('name');
385
    }
386
387
    /**
388
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
389
     *
390
     * @return \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|\Illuminate\Support\Collection
391
     */
392
    protected function getStoredPermission($permissions)
393
    {
394
        $permissionClass = $this->getPermissionClass();
395
396
        if (is_numeric($permissions)) {
397
            return $permissionClass->findById($permissions, $this->getDefaultGuardName());
398
        }
399
400
        if (is_string($permissions)) {
401
            return $permissionClass->findByName($permissions, $this->getDefaultGuardName());
402
        }
403
404
        if (is_array($permissions)) {
405
            return $permissionClass
406
                ->whereIn('name', $permissions)
407
                ->whereIn('guard_name', $this->getGuardNames())
408
                ->get();
409
        }
410
411
        return $permissions;
412
    }
413
414
    /**
415
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Role $roleOrPermission
416
     *
417
     * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
418
     */
419
    protected function ensureModelSharesGuard($roleOrPermission)
420
    {
421
        if (! $this->getGuardNames()->contains($roleOrPermission->guard_name)) {
422
            throw GuardDoesNotMatch::create($roleOrPermission->guard_name, $this->getGuardNames());
423
        }
424
    }
425
426
    protected function getGuardNames(): Collection
427
    {
428
        return Guard::getNames($this);
429
    }
430
431
    protected function getDefaultGuardName(): string
432
    {
433
        return Guard::getDefaultName($this);
434
    }
435
436
    /**
437
     * Forget the cached permissions.
438
     */
439
    public function forgetCachedPermissions()
440
    {
441
        app(PermissionRegistrar::class)->forgetCachedPermissions();
442
    }
443
}
444