Completed
Pull Request — master (#1255)
by
unknown
01:19
created

HasPermissions::givePermissionTo()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 47

Duplication

Lines 47
Ratio 100 %

Importance

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