Completed
Pull Request — master (#664)
by Chris
01:43
created

HasRoles::getStoredRole()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 12
rs 9.4285
c 0
b 0
f 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
            if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
19
                return;
20
            }
21
22
            $model->roles()->detach();
23
            $model->permissions()->detach();
24
        });
25
    }
26
27
    /**
28
     * A model may have multiple roles.
29
     */
30
    public function roles(): 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.role'),
34
            'model',
35
            config('permission.table_names.model_has_roles'),
36
            'model_id',
37
            'role_id'
38
        );
39
    }
40
41
    /**
42
     * A model may have multiple direct permissions.
43
     */
44
    public function permissions(): MorphToMany
45
    {
46
        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...
47
            config('permission.models.permission'),
48
            'model',
49
            config('permission.table_names.model_has_permissions'),
50
            'model_id',
51
            'permission_id'
52
        );
53
    }
54
55
    /**
56
     * Scope the model query to certain roles only.
57
     *
58
     * @param \Illuminate\Database\Eloquent\Builder $query
59
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
60
     *
61
     * @return \Illuminate\Database\Eloquent\Builder
62
     */
63
    public function scopeRole(Builder $query, $roles): Builder
64
    {
65
        if ($roles instanceof Collection) {
66
            $roles = $roles->all();
67
        }
68
69
        if (! is_array($roles)) {
70
            $roles = [$roles];
71
        }
72
73
        $roles = array_map(function ($role) {
74
            if ($role instanceof Role) {
75
                return $role;
76
            }
77
78
            return app(Role::class)->findByName($role, $this->getDefaultGuardName());
79
        }, $roles);
80
81
        return $query->whereHas('roles', function ($query) use ($roles) {
82
            $query->where(function ($query) use ($roles) {
83
                foreach ($roles as $role) {
84
                    $query->orWhere(config('permission.table_names.roles').'.id', $role->id);
85
                }
86
            });
87
        });
88
    }
89
90
    /**
91
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
92
     *
93
     * @return array
94
     */
95
    protected function convertToPermissionModels($permissions): array
96
    {
97
        if ($permissions instanceof Collection) {
98
            $permissions = $permissions->all();
99
        }
100
101
        $permissions = array_wrap($permissions);
102
103
        return array_map(function ($permission) {
104
            if ($permission instanceof Permission) {
105
                return $permission;
106
            }
107
108
            return app(Permission::class)->findByName($permission, $this->getDefaultGuardName());
109
        }, $permissions);
110
    }
111
112
    /**
113
     * Scope the model query to certain permissions only.
114
     *
115
     * @param \Illuminate\Database\Eloquent\Builder $query
116
     * @param string|array|\Spatie\Permission\Contracts\Permission|\Illuminate\Support\Collection $permissions
117
     *
118
     * @return \Illuminate\Database\Eloquent\Builder
119
     */
120
    public function scopePermission(Builder $query, $permissions): Builder
121
    {
122
        $permissions = $this->convertToPermissionModels($permissions);
123
124
        $rolesWithPermissions = array_unique(array_reduce($permissions, function ($result, $permission) {
125
            return array_merge($result, $permission->roles->all());
126
        }, []));
127
128
        return $query->
129
            where(function ($query) use ($permissions, $rolesWithPermissions) {
130
                $query->whereHas('permissions', function ($query) use ($permissions) {
131
                    $query->where(function ($query) use ($permissions) {
132
                        foreach ($permissions as $permission) {
133
                            $query->orWhere(config('permission.table_names.permissions').'.id', $permission->id);
134
                        }
135
                    });
136
                });
137
                if (count($rolesWithPermissions) > 0) {
138
                    $query->orWhereHas('roles', function ($query) use ($rolesWithPermissions) {
139
                        $query->where(function ($query) use ($rolesWithPermissions) {
140
                            foreach ($rolesWithPermissions as $role) {
141
                                $query->orWhere(config('permission.table_names.roles').'.id', $role->id);
142
                            }
143
                        });
144
                    });
145
                }
146
            });
147
    }
148
149
    /**
150
     * Assign the given role to the model.
151
     *
152
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
153
     *
154
     * @return $this
155
     */
156 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...
157
    {
158
        $roles = collect($roles)
159
            ->flatten()
160
            ->map(function ($role) {
161
                return $this->getStoredRole($role);
162
            })
163
            ->each(function ($role) {
164
                $this->ensureModelSharesGuard($role);
165
            })
166
            ->all();
167
168
        $this->roles()->saveMany($roles);
169
170
        $this->forgetCachedPermissions();
171
172
        return $this;
173
    }
174
175
    /**
176
     * Revoke the given role from the model.
177
     *
178
     * @param string|\Spatie\Permission\Contracts\Role $role
179
     */
180
    public function removeRole($role)
181
    {
182
        $this->roles()->detach($this->getStoredRole($role));
183
    }
184
185
    /**
186
     * Remove all current roles and set the given ones.
187
     *
188
     * @param array|\Spatie\Permission\Contracts\Role|string ...$roles
189
     *
190
     * @return $this
191
     */
192
    public function syncRoles(...$roles)
193
    {
194
        $this->roles()->detach();
195
196
        return $this->assignRole($roles);
197
    }
198
199
    /**
200
     * Determine if the model has (one of) the given role(s).
201
     *
202
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
203
     *
204
     * @return bool
205
     */
206
    public function hasRole($roles): bool
207
    {
208 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...
209
            $roles = $this->convertPipeToArray($roles);
210
        }
211
212
        if (is_string($roles)) {
213
            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...
214
        }
215
216
        if ($roles instanceof Role) {
217
            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...
218
        }
219
220
        if (is_array($roles)) {
221
            foreach ($roles as $role) {
222
                if ($this->hasRole($role)) {
223
                    return true;
224
                }
225
            }
226
227
            return false;
228
        }
229
230
        return $roles->intersect($this->roles)->isNotEmpty();
231
    }
232
233
    /**
234
     * Determine if the model has any of the given role(s).
235
     *
236
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
237
     *
238
     * @return bool
239
     */
240
    public function hasAnyRole($roles): bool
241
    {
242
        return $this->hasRole($roles);
243
    }
244
245
    /**
246
     * Determine if the model has all of the given role(s).
247
     *
248
     * @param string|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
249
     *
250
     * @return bool
251
     */
252
    public function hasAllRoles($roles): bool
253
    {
254 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...
255
            $roles = $this->convertPipeToArray($roles);
256
        }
257
258
        if (is_string($roles)) {
259
            return $this->roles->contains('name', $roles);
260
        }
261
262
        if ($roles instanceof Role) {
263
            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...
264
        }
265
266
        $roles = collect()->make($roles)->map(function ($role) {
267
            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...
268
        });
269
270
        return $roles->intersect($this->roles->pluck('name')) == $roles;
271
    }
272
273
    /**
274
     * Determine if the model may perform the given permission.
275
     *
276
     * @param string|\Spatie\Permission\Contracts\Permission $permission
277
     * @param string|null $guardName
278
     *
279
     * @return bool
280
     */
281
    public function hasPermissionTo($permission, $guardName = null): bool
282
    {
283 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...
284
            $permission = app(Permission::class)->findByName(
285
                $permission,
286
                $guardName ?? $this->getDefaultGuardName()
287
            );
288
        }
289
      
290
        if (is_integer($permission)) {
291
          $permission = app(Permission::class)->findById($permission, $this->getDefaultGuardName());
292
        }
293
294
        return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
295
    }
296
297
    /**
298
     * Determine if the model has any of the given permissions.
299
     *
300
     * @param array ...$permissions
301
     *
302
     * @return bool
303
     */
304
    public function hasAnyPermission(...$permissions): bool
305
    {
306
        if (is_array($permissions[0])) {
307
            $permissions = $permissions[0];
308
        }
309
310
        foreach ($permissions as $permission) {
311
            if ($this->hasPermissionTo($permission)) {
312
                return true;
313
            }
314
        }
315
316
        return false;
317
    }
318
319
    /**
320
     * Determine if the model has, via roles, the given permission.
321
     *
322
     * @param \Spatie\Permission\Contracts\Permission $permission
323
     *
324
     * @return bool
325
     */
326
    protected function hasPermissionViaRole(Permission $permission): bool
327
    {
328
        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...
329
    }
330
331
    /**
332
     * Determine if the model has the given permission.
333
     *
334
     * @param string|\Spatie\Permission\Contracts\Permission $permission
335
     *
336
     * @return bool
337
     */
338
    public function hasDirectPermission($permission): bool
339
    {
340 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...
341
            $permission = app(Permission::class)->findByName($permission, $this->getDefaultGuardName());
342
            if (! $permission) {
343
                return false;
344
            }
345
        }
346
      
347
      if (is_integer($permission)) {
348
            $permission = app(Permission::class)->findById($permission, $this->getDefaultGuardName());
349
            if (! $permission ) {
350
                return false;
351
            }
352
        }
353
       
354
      
355
        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...
356
    }
357
358
    /**
359
     * Return all permissions the directory coupled to the model.
360
     */
361
    public function getDirectPermissions(): Collection
362
    {
363
        return $this->permissions;
364
    }
365
366
    /**
367
     * Return all the permissions the model has via roles.
368
     */
369
    public function getPermissionsViaRoles(): Collection
370
    {
371
        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...
372
            ->roles->flatMap(function ($role) {
373
                return $role->permissions;
374
            })->sort()->values();
375
    }
376
377
    /**
378
     * Return all the permissions the model has, both directly and via roles.
379
     */
380
    public function getAllPermissions(): Collection
381
    {
382
        return $this->permissions
383
            ->merge($this->getPermissionsViaRoles())
384
            ->sort()
385
            ->values();
386
    }
387
388
    public function getRoleNames(): Collection
389
    {
390
        return $this->roles->pluck('name');
391
    }
392
393
    protected function getStoredRole($role): Role
394
    {
395
        if (is_numeric($role)) {
396
            return app(Role::class)->findById($role, $this->getDefaultGuardName());
397
        }
398
399
        if (is_string($role)) {
400
            return app(Role::class)->findByName($role, $this->getDefaultGuardName());
401
        }
402
403
        return $role;
404
    }
405
406
    protected function convertPipeToArray(string $pipeString)
407
    {
408
        $pipeString = trim($pipeString);
409
410
        if (strlen($pipeString) <= 2) {
411
            return $pipeString;
412
        }
413
414
        $quoteCharacter = substr($pipeString, 0, 1);
415
        $endCharacter = substr($quoteCharacter, -1, 1);
416
417
        if ($quoteCharacter !== $endCharacter) {
418
            return explode('|', $pipeString);
419
        }
420
421
        if (! in_array($quoteCharacter, ["'", '"'])) {
422
            return explode('|', $pipeString);
423
        }
424
425
        return explode('|', trim($pipeString, $quoteCharacter));
426
    }
427
}
428