Completed
Pull Request — master (#442)
by Chris
01:22
created

HasRoles::getAllPermissions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
namespace Spatie\Permission\Traits;
4
5
use Illuminate\Support\Collection;
6
use Spatie\Permission\Contracts\Role;
7
use Illuminate\Database\Eloquent\Builder;
8
use Spatie\Permission\Contracts\Permission;
9
use Illuminate\Database\Eloquent\Relations\MorphToMany;
10
11
trait HasRoles
12
{
13
    use HasPermissions;
14
15
    public static function bootHasRoles()
16
    {
17
        static::deleting(function ($model) {
18
            $model->roles()->detach();
19
            $model->permissions()->detach();
20
        });
21
    }
22
23
    /**
24
     * A model may have multiple roles.
25
     */
26
    public function roles(): MorphToMany
27
    {
28
        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...
29
            config('permission.models.role'),
30
            'model',
31
            config('permission.table_names.model_has_roles'),
32
            'model_id',
33
            'role_id'
34
        );
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 roles only.
53
     *
54
     * @param \Illuminate\Database\Eloquent\Builder $query
55
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
56
     *
57
     * @return \Illuminate\Database\Eloquent\Builder
58
     */
59
    public function scopeRole(Builder $query, $roles): Builder
60
    {
61
        if ($roles instanceof Collection) {
62
            $roles = $roles->toArray();
63
        }
64
65
        if (! is_array($roles)) {
66
            $roles = [$roles];
67
        }
68
69
        $roles = array_map(function ($role) {
70
            if ($role instanceof Role) {
71
                return $role;
72
            }
73
74
            return app(Role::class)->findByName($role, $this->getDefaultGuardName());
75
        }, $roles);
76
77
        return $query->whereHas('roles', function ($query) use ($roles) {
78
            $query->where(function ($query) use ($roles) {
79
                foreach ($roles as $role) {
80
                    $query->orWhere(config('permission.table_names.roles').'.id', $role->id);
81
                }
82
            });
83
        });
84
    }
85
86
    /**
87
     * Assign the given role to the model.
88
     *
89
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
90
     *
91
     * @return $this
92
     */
93 View Code Duplication
    public function assignRole(...$roles)
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...
94
    {
95
        $roles = collect($roles)
96
            ->flatten()
97
            ->map(function ($role) {
98
                return $this->getStoredRole($role);
99
            })
100
            ->each(function ($role) {
101
                $this->ensureModelSharesGuard($role);
102
            })
103
            ->all();
104
105
        $this->roles()->saveMany($roles);
106
107
        $this->forgetCachedPermissions();
108
109
        return $this;
110
    }
111
112
    /**
113
     * Revoke the given role from the model.
114
     *
115
     * @param string|\Spatie\Permission\Contracts\Role $role
116
     */
117
    public function removeRole($role)
118
    {
119
        $this->roles()->detach($this->getStoredRole($role));
120
    }
121
122
    /**
123
     * Remove all current roles and set the given ones.
124
     *
125
     * @param array|\Spatie\Permission\Contracts\Role|string ...$roles
126
     *
127
     * @return $this
128
     */
129
    public function syncRoles(...$roles)
130
    {
131
        $this->roles()->detach();
132
133
        return $this->assignRole($roles);
134
    }
135
136
    /**
137
     * Determine if the model has (one of) the given role(s).
138
     *
139
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
140
     *
141
     * @return bool
142
     */
143
    public function hasRole($roles): bool
144
    {
145 View Code Duplication
        if (is_string($roles) && false !== strpos($roles, '|')) {
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...
146
            $roles = $this->convertPipeToArray($roles);
147
        }
148
149
        if (is_string($roles)) {
150
            return $this->roles->contains('name', $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...
151
        }
152
153
        if ($roles instanceof Role) {
154
            return $this->roles->contains('id', $roles->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Spatie\Permission\Contracts\Role 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...
155
        }
156
157
        if (is_array($roles)) {
158
            foreach ($roles as $role) {
159
                if ($this->hasRole($role)) {
160
                    return true;
161
                }
162
            }
163
164
            return false;
165
        }
166
167
        return $roles->intersect($this->roles)->isNotEmpty();
168
    }
169
170
    /**
171
     * Determine if the model has any of the given role(s).
172
     *
173
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
174
     *
175
     * @return bool
176
     */
177
    public function hasAnyRole($roles): bool
178
    {
179
        return $this->hasRole($roles);
180
    }
181
182
    /**
183
     * Determine if the model has all of the given role(s).
184
     *
185
     * @param string|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
186
     *
187
     * @return bool
188
     */
189
    public function hasAllRoles($roles): bool
190
    {
191 View Code Duplication
        if (is_string($roles) && false !== strpos($roles, '|')) {
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...
192
            $roles = $this->convertPipeToArray($roles);
193
        }
194
195
        if (is_string($roles)) {
196
            return $this->roles->contains('name', $roles);
197
        }
198
199
        if ($roles instanceof Role) {
200
            return $this->roles->contains('id', $roles->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Spatie\Permission\Contracts\Role 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...
201
        }
202
203
        $roles = collect()->make($roles)->map(function ($role) {
204
            return $role instanceof Role ? $role->name : $role;
0 ignored issues
show
Bug introduced by
Accessing name on the interface Spatie\Permission\Contracts\Role 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...
205
        });
206
207
        return $roles->intersect($this->roles->pluck('name')) == $roles;
208
    }
209
210
    /**
211
     * Determine if the model may perform the given permission.
212
     *
213
     * @param string|\Spatie\Permission\Contracts\Permission $permission
214
     * @param string|null $guardName
215
     *
216
     * @return bool
217
     */
218
    public function hasPermissionTo($permission, $guardName = null): bool
219
    {
220 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...
221
            $permission = app(Permission::class)->findByName(
222
                $permission,
223
                $guardName ?? $this->getDefaultGuardName()
224
            );
225
        }
226
227
        return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
228
    }
229
230
    /**
231
     * Determine if the model has any of the given permissions.
232
     *
233
     * @param array ...$permissions
234
     *
235
     * @return bool
236
     */
237
    public function hasAnyPermission(...$permissions): bool
238
    {
239
        if (is_array($permissions[0])) {
240
            $permissions = $permissions[0];
241
        }
242
243
        foreach ($permissions as $permission) {
244
            if ($this->hasPermissionTo($permission)) {
245
                return true;
246
            }
247
        }
248
249
        return false;
250
    }
251
252
    /**
253
     * Determine if the model has, via roles, the given permission.
254
     *
255
     * @param \Spatie\Permission\Contracts\Permission $permission
256
     *
257
     * @return bool
258
     */
259
    protected function hasPermissionViaRole(Permission $permission): bool
260
    {
261
        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...
262
    }
263
264
    /**
265
     * Determine if the model has the given permission.
266
     *
267
     * @param string|\Spatie\Permission\Contracts\Permission $permission
268
     *
269
     * @return bool
270
     */
271
    public function hasDirectPermission($permission): bool
272
    {
273 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...
274
            $permission = app(Permission::class)->findByName($permission, $this->getDefaultGuardName());
275
276
            if (! $permission) {
277
                return false;
278
            }
279
        }
280
281
        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...
282
    }
283
284
    /**
285
     * Return all permissions the directory coupled to the model.
286
     */
287
    public function getDirectPermissions(): Collection
288
    {
289
        return $this->permissions;
290
    }
291
292
    /**
293
     * Return all the permissions the model has via roles.
294
     */
295
    public function getPermissionsViaRoles(): Collection
296
    {
297
        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...
298
            ->roles->flatMap(function ($role) {
299
                return $role->permissions;
300
            })->sort()->values();
301
    }
302
303
    /**
304
     * Return all the permissions the model has, both directly and via roles.
305
     */
306
    public function getAllPermissions(): Collection
307
    {
308
        return $this->permissions
309
            ->merge($this->getPermissionsViaRoles())
310
            ->sort()
311
            ->values();
312
    }
313
314
    public function getRoleNames(): Collection
315
    {
316
        return $this->roles->pluck('name');
317
    }
318
319
    protected function getStoredRole($role): Role
320
    {
321
        if (is_string($role)) {
322
            return app(Role::class)->findByName($role, $this->getDefaultGuardName());
323
        }
324
325
        return $role;
326
    }
327
328
    protected function convertPipeToArray(string $pipeString)
329
    {
330
        $pipeString = trim($pipeString);
331
332
        if (strlen($pipeString) <= 2) {
333
            return $pipeString;
334
        }
335
336
        $quoteCharacter = substr($pipeString, 0, 1);
337
        $endCharacter = substr($quoteCharacter, -1, 1);
338
339
        if ($quoteCharacter !== $endCharacter) {
340
            return explode('|', $pipeString);
341
        }
342
343
        if (! in_array($quoteCharacter, ["'", '"'])) {
344
            return explode('|', $pipeString);
345
        }
346
347
        return explode('|', trim($pipeString, $quoteCharacter));
348
    }
349
}
350