Completed
Pull Request — master (#820)
by
unknown
01:29
created

HasPermissions::ensureModelSharesGuard()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Permission\Traits;
4
5
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
6
use Spatie\Permission\Guard;
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Builder;
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
14
trait HasPermissions
15
{
16
    public static function bootHasPermissions()
17
    {
18
        static::deleting(function ($model) {
19
            if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
20
                return;
21
            }
22
23
            $model->permissions()->detach();
24
        });
25
    }
26
27
    /**
28
     * A model may have multiple direct permissions.
29
     */
30
    public function permissions(): MorphToMany
31
    {
32
        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...
33
            config('permission.models.permission'),
34
            'model',
35
            config('permission.table_names.model_has_permissions'),
36
            'model_id',
37
            'permission_id'
38
        );
39
    }
40
41
    /**
42
     * Scope the model query to certain permissions only.
43
     *
44
     * @param \Illuminate\Database\Eloquent\Builder $query
45
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
46
     *
47
     * @return \Illuminate\Database\Eloquent\Builder
48
     */
49
    public function scopePermission(Builder $query, $permissions): Builder
50
    {
51
        $permissions = $this->convertToPermissionModels($permissions);
52
53
        $rolesWithPermissions = array_unique(array_reduce($permissions, function ($result, $permission) {
54
            return array_merge($result, $permission->roles->all());
55
        }, []));
56
57
        return $query->where(function ($query) use ($permissions, $rolesWithPermissions) {
58
            $query->whereHas('permissions', function ($query) use ($permissions) {
59
                $query->where(function ($query) use ($permissions) {
60
                    foreach ($permissions as $permission) {
61
                        $query->orWhere(config('permission.table_names.permissions').'.id', $permission->id);
62
                    }
63
                });
64
            });
65
            if (count($rolesWithPermissions) > 0) {
66
                $query->orWhereHas('roles', function ($query) use ($rolesWithPermissions) {
67
                    $query->where(function ($query) use ($rolesWithPermissions) {
68
                        foreach ($rolesWithPermissions as $role) {
69
                            $query->orWhere(config('permission.table_names.roles').'.id', $role->id);
70
                        }
71
                    });
72
                });
73
            }
74
        });
75
    }
76
77
    /**
78
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
79
     *
80
     * @return array
81
     */
82
    protected function convertToPermissionModels($permissions): array
83
    {
84
        if ($permissions instanceof Collection) {
85
            $permissions = $permissions->all();
86
        }
87
88
        $permissions = array_wrap($permissions);
89
90
        return array_map(function ($permission) {
91
            if ($permission instanceof Permission) {
92
                return $permission;
93
            }
94
95
            return app(Permission::class)->findByName($permission, $this->getDefaultGuardName());
96
        }, $permissions);
97
    }
98
99
    /**
100
     * Determine if the model may perform the given permission.
101
     *
102
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
103
     * @param string|null $guardName
104
     *
105
     * @return bool
106
     */
107
    public function hasPermissionTo($permission, $guardName = null): bool
108
    {
109 View Code Duplication
        if (is_string($permission)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
110
            $permission = app(Permission::class)->findByName(
111
                $permission,
112
                $guardName ?? $this->getDefaultGuardName()
113
            );
114
        }
115
116 View Code Duplication
        if (is_int($permission)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
117
            $permission = app(Permission::class)->findById(
118
                $permission,
119
                $guardName ?? $this->getDefaultGuardName()
120
            );
121
        }
122
123
        if (!$permission instanceof Permission)
124
        {
125
            throw new PermissionDoesNotExist;
126
        }
127
128
        return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
129
    }
130
131
    /**
132
     * Determine if the model has any of the given permissions.
133
     *
134
     * @param array ...$permissions
135
     *
136
     * @return bool
137
     */
138 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...
139
    {
140
        if (is_array($permissions[0])) {
141
            $permissions = $permissions[0];
142
        }
143
144
        foreach ($permissions as $permission) {
145
            if ($this->hasPermissionTo($permission)) {
146
                return true;
147
            }
148
        }
149
150
        return false;
151
    }
152
153
    /**
154
     * Determine if the model has all of the given permissions.
155
     *
156
     * @param array ...$permissions
157
     *
158
     * @return bool
159
     */
160 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...
161
    {
162
        if (is_array($permissions[0])) {
163
            $permissions = $permissions[0];
164
        }
165
166
        foreach ($permissions as $permission) {
167
            if (! $this->hasPermissionTo($permission)) {
168
                return false;
169
            }
170
        }
171
172
        return true;
173
    }
174
175
    /**
176
     * Determine if the model has, via roles, the given permission.
177
     *
178
     * @param \Spatie\Permission\Contracts\Permission $permission
179
     *
180
     * @return bool
181
     */
182
    protected function hasPermissionViaRole(Permission $permission): bool
183
    {
184
        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...
185
    }
186
187
    /**
188
     * Determine if the model has the given permission.
189
     *
190
     * @param string|int|\Spatie\Permission\Contracts\Permission $permission
191
     *
192
     * @return bool
193
     */
194
    public function hasDirectPermission($permission): bool
195
    {
196 View Code Duplication
        if (is_string($permission)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
197
            $permission = app(Permission::class)->findByName($permission, $this->getDefaultGuardName());
198
            if (! $permission) {
199
                return false;
200
            }
201
        }
202
203 View Code Duplication
        if (is_int($permission)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
204
            $permission = app(Permission::class)->findById($permission, $this->getDefaultGuardName());
205
            if (! $permission) {
206
                return false;
207
            }
208
        }
209
210
        if (!$permission instanceof Permission)
211
        {
212
            return false;
213
        }
214
215
        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...
216
    }
217
218
    /**
219
     * Return all the permissions the model has via roles.
220
     */
221
    public function getPermissionsViaRoles(): Collection
222
    {
223
        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...
224
            ->roles->flatMap(function ($role) {
225
                return $role->permissions;
226
            })->sort()->values();
227
    }
228
229
    /**
230
     * Return all the permissions the model has, both directly and via roles.
231
     */
232
    public function getAllPermissions(): Collection
233
    {
234
        return $this->permissions
235
            ->merge($this->getPermissionsViaRoles())
236
            ->sort()
237
            ->values();
238
    }
239
240
    /**
241
     * Grant the given permission(s) to a role.
242
     *
243
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
244
     *
245
     * @return $this
246
     */
247 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...
248
    {
249
        $permissions = collect($permissions)
250
            ->flatten()
251
            ->map(function ($permission) {
252
                return $this->getStoredPermission($permission);
253
            })
254
            ->filter(function ($permission) {
255
                return $permission instanceof Permission;
256
            })
257
            ->each(function ($permission) {
258
                $this->ensureModelSharesGuard($permission);
259
            })
260
            ->all();
261
262
        $this->permissions()->saveMany($permissions);
263
264
        $this->forgetCachedPermissions();
265
266
        return $this;
267
    }
268
269
    /**
270
     * Remove all current permissions and set the given ones.
271
     *
272
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
273
     *
274
     * @return $this
275
     */
276
    public function syncPermissions(...$permissions)
277
    {
278
        $this->permissions()->detach();
279
280
        return $this->givePermissionTo($permissions);
281
    }
282
283
    /**
284
     * Revoke the given permission.
285
     *
286
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|string|string[] $permission
287
     *
288
     * @return $this
289
     */
290
    public function revokePermissionTo($permission)
291
    {
292
        $this->permissions()->detach($this->getStoredPermission($permission));
293
294
        $this->forgetCachedPermissions();
295
296
        return $this;
297
    }
298
299
    /**
300
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
301
     *
302
     * @return \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|\Illuminate\Support\Collection
303
     */
304
    protected function getStoredPermission($permissions)
305
    {
306
        if (is_numeric($permissions)) {
307
            return app(Permission::class)->findById($permissions, $this->getDefaultGuardName());
308
        }
309
310
        if (is_string($permissions)) {
311
            return app(Permission::class)->findByName($permissions, $this->getDefaultGuardName());
312
        }
313
314
        if (is_array($permissions)) {
315
            return app(Permission::class)
316
                ->whereIn('name', $permissions)
317
                ->whereIn('guard_name', $this->getGuardNames())
318
                ->get();
319
        }
320
321
        return $permissions;
322
    }
323
324
    /**
325
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Role $roleOrPermission
326
     *
327
     * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
328
     */
329
    protected function ensureModelSharesGuard($roleOrPermission)
330
    {
331
        if (! $this->getGuardNames()->contains($roleOrPermission->guard_name)) {
332
            throw GuardDoesNotMatch::create($roleOrPermission->guard_name, $this->getGuardNames());
333
        }
334
    }
335
336
    protected function getGuardNames(): Collection
337
    {
338
        return Guard::getNames($this);
339
    }
340
341
    protected function getDefaultGuardName(): string
342
    {
343
        return Guard::getDefaultName($this);
344
    }
345
346
    /**
347
     * Forget the cached permissions.
348
     */
349
    public function forgetCachedPermissions()
350
    {
351
        app(PermissionRegistrar::class)->forgetCachedPermissions();
352
    }
353
}
354