Completed
Pull Request — master (#746)
by Chris
04:01
created

HasPermissions::getAllPermissions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 7
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
            'model_id',
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
            ->each(function ($permission) {
259
                $this->ensureModelSharesGuard($permission);
260
            })
261
            ->all();
262
263
        $this->permissions()->saveMany($permissions);
264
265
        $this->forgetCachedPermissions();
266
267
        return $this;
268
    }
269
270
    /**
271
     * Remove all current permissions and set the given ones.
272
     *
273
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
274
     *
275
     * @return $this
276
     */
277
    public function syncPermissions(...$permissions)
278
    {
279
        $this->permissions()->detach();
280
281
        return $this->givePermissionTo($permissions);
282
    }
283
284
    /**
285
     * Revoke the given permission.
286
     *
287
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|string|string[] $permission
288
     *
289
     * @return $this
290
     */
291
    public function revokePermissionTo($permission)
292
    {
293
        $this->permissions()->detach($this->getStoredPermission($permission));
294
295
        $this->forgetCachedPermissions();
296
297
        return $this;
298
    }
299
300
    /**
301
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
302
     *
303
     * @return \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Permission[]|\Illuminate\Support\Collection
304
     */
305
    protected function getStoredPermission($permissions)
306
    {
307
        $permissionClass = $this->getPermissionClass();
308
309
        if (is_numeric($permissions)) {
310
            return $permissionClass->findById($permissions, $this->getDefaultGuardName());
311
        }
312
313
        if (is_string($permissions)) {
314
            return $permissionClass->findByName($permissions, $this->getDefaultGuardName());
315
        }
316
317
        if (is_array($permissions)) {
318
            return $permissionClass
319
                ->whereIn('name', $permissions)
320
                ->whereIn('guard_name', $this->getGuardNames())
321
                ->get();
322
        }
323
324
        return $permissions;
325
    }
326
327
    /**
328
     * @param \Spatie\Permission\Contracts\Permission|\Spatie\Permission\Contracts\Role $roleOrPermission
329
     *
330
     * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
331
     */
332
    protected function ensureModelSharesGuard($roleOrPermission)
333
    {
334
        if (! $this->getGuardNames()->contains($roleOrPermission->guard_name)) {
335
            throw GuardDoesNotMatch::create($roleOrPermission->guard_name, $this->getGuardNames());
336
        }
337
    }
338
339
    protected function getGuardNames(): Collection
340
    {
341
        return Guard::getNames($this);
342
    }
343
344
    protected function getDefaultGuardName(): string
345
    {
346
        return Guard::getDefaultName($this);
347
    }
348
349
    /**
350
     * Forget the cached permissions.
351
     */
352
    public function forgetCachedPermissions()
353
    {
354
        app(PermissionRegistrar::class)->forgetCachedPermissions();
355
    }
356
}
357