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