Completed
Pull Request — master (#245)
by Sebastian
05:44 queued 03:45
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
    use RefreshesPermissionCache;
15
16
    /**
17
     * A model may have multiple roles.
18
     */
19
    public function roles(): MorphToMany
20
    {
21
        return $this->morphedByMany(
0 ignored issues
show
Bug introduced by
It seems like morphedByMany() 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...
22
            config('laravel-permission.models.role'),
23
            'model',
24
            config('laravel-permission.table_names.model_has_roles'),
25
            'role_id',
26
            'model_id'
27
        );
28
    }
29
30
    /**
31
     * A model may have multiple direct permissions.
32
     */
33
    public function permissions(): MorphToMany
34
    {
35
        return $this->morphedByMany(
0 ignored issues
show
Bug introduced by
It seems like morphedByMany() 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...
36
            config('laravel-permission.models.permission'),
37
            'model',
38
            config('laravel-permission.table_names.model_has_permissions'),
39
            'permission_id',
40
            'model_id'
41
        );
42
    }
43
44
    /**
45
     * Scope the model query to certain roles only.
46
     *
47
     * @param \Illuminate\Database\Eloquent\Builder $query
48
     * @param string|array|Role|\Illuminate\Support\Collection $roles
49
     *
50
     * @return \Illuminate\Database\Eloquent\Builder
51
     */
52
    public function scopeRole(Builder $query, $roles): Builder
53
    {
54
        if ($roles instanceof Collection) {
55
            $roles = $roles->toArray();
56
        }
57
58
        if (! is_array($roles)) {
59
            $roles = [$roles];
60
        }
61
62
        $roles = array_map(function ($role) {
63
            if ($role instanceof Role) {
64
                return $role;
65
            }
66
67
            $guardName = $this->getGuardName();
68
69
            return app(Role::class)->findByName($role, $guardName);
70
        }, $roles);
71
72
        return $query->whereHas('roles', function ($query) use ($roles) {
73
            $query->where(function ($query) use ($roles) {
74
                foreach ($roles as $role) {
75
                    $query->orWhere(config('laravel-permission.table_names.roles').'.id', $role->id);
76
                }
77
            });
78
        });
79
    }
80
81
    /**
82
     * Assign the given role to the model.
83
     *
84
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
85
     *
86
     * @return $this
87
     */
88 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...
89
    {
90
        $roles = collect($roles)
91
            ->flatten()
92
            ->map(function ($role) {
93
                return $this->getStoredRole($role);
94
            })
95
            ->each(function ($role) {
96
                $this->ensureGuardIsEqual($role);
97
            })
98
            ->all();
99
100
        $this->roles()->saveMany($roles);
101
102
        $this->forgetCachedPermissions();
103
104
        return $this;
105
    }
106
107
    /**
108
     * Revoke the given role from the model.
109
     *
110
     * @param string|\Spatie\Permission\Contracts\Role $role
111
     */
112
    public function removeRole($role)
113
    {
114
        $this->roles()->detach($this->getStoredRole($role));
115
    }
116
117
    /**
118
     * Remove all current roles and set the given ones.
119
     *
120
     * @param array ...$roles
121
     *
122
     * @return $this
123
     */
124
    public function syncRoles(...$roles)
125
    {
126
        $this->roles()->detach();
127
128
        return $this->assignRole($roles);
129
    }
130
131
    /**
132
     * Determine if the model has (one of) the given role(s).
133
     *
134
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
135
     *
136
     * @return bool
137
     */
138
    public function hasRole($roles): bool
139
    {
140
        if (is_string($roles)) {
141
            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...
142
        }
143
144
        if ($roles instanceof Role) {
145
            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...
146
        }
147
148
        if (is_array($roles)) {
149
            foreach ($roles as $role) {
150
                if ($this->hasRole($role)) {
151
                    return true;
152
                }
153
            }
154
155
            return false;
156
        }
157
158
        return (bool) $roles->intersect($this->roles)->count();
159
    }
160
161
    /**
162
     * Determine if the model has any of the given role(s).
163
     *
164
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
165
     *
166
     * @return bool
167
     */
168
    public function hasAnyRole($roles): bool
169
    {
170
        return $this->hasRole($roles);
171
    }
172
173
    /**
174
     * Determine if the model has all of the given role(s).
175
     *
176
     * @param string|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
177
     *
178
     * @return bool
179
     */
180
    public function hasAllRoles($roles): bool
181
    {
182
        if (is_string($roles)) {
183
            return $this->roles->contains('name', $roles);
184
        }
185
186
        if ($roles instanceof Role) {
187
            return $this->roles->contains('id', $roles->id);
188
        }
189
190
        $roles = collect()->make($roles)->map(function ($role) {
191
            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...
192
        });
193
194
        return $roles->intersect($this->roles->pluck('name')) == $roles;
195
    }
196
197
    /**
198
     * Determine if the model may perform the given permission.
199
     *
200
     * @param string|\Spatie\Permission\Contracts\Permission $permission
201
     *
202
     * @return bool
203
     */
204
    public function hasPermissionTo($permission): bool
205
    {
206
        if (is_string($permission)) {
207
            $permission = app(Permission::class)->findByName($permission, $this->getGuardName());
208
        }
209
210
        return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
211
    }
212
213
    /**
214
     * Determine if the model has any of the given permissions.
215
     *
216
     * @param array ...$permissions
217
     *
218
     * @return bool
219
     */
220
    public function hasAnyPermission(...$permissions): bool
221
    {
222
        foreach ($permissions as $permission) {
223
            if ($this->hasPermissionTo($permission)) {
0 ignored issues
show
Documentation introduced by
$permission is of type array, but the function expects a string|object<Spatie\Per...n\Contracts\Permission>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
224
                return true;
225
            }
226
        }
227
228
        return false;
229
    }
230
231
    /**
232
     * Determine if the model has, via roles, the given permission.
233
     *
234
     * @param \Spatie\Permission\Contracts\Permission $permission
235
     *
236
     * @return bool
237
     */
238
    protected function hasPermissionViaRole(Permission $permission): bool
239
    {
240
        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...
241
    }
242
243
    /**
244
     * Determine if the model has the given permission.
245
     *
246
     * @param string|\Spatie\Permission\Contracts\Permission $permission
247
     *
248
     * @return bool
249
     */
250
    public function hasDirectPermission($permission): bool
251
    {
252
        if (is_string($permission)) {
253
            $permission = app(Permission::class)->findByName($permission, $this->getGuardName());
254
255
            if (! $permission) {
256
                return false;
257
            }
258
        }
259
260
        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...
261
    }
262
263
    /**
264
     * Return all permissions the directory coupled to the model.
265
     */
266
    public function getDirectPermissions(): Collection
267
    {
268
        return $this->permissions;
269
    }
270
271
    /**
272
     * Return all the permissions the model has via roles.
273
     */
274
    public function getPermissionsViaRoles(): Collection
275
    {
276
        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...
277
            ->roles->flatMap(function ($role) {
278
                return $role->permissions;
279
            })->sort()->values();
280
    }
281
282
    /**
283
     * Return all the permissions the model has, both directly and via roles.
284
     */
285
    public function getAllPermissions(): Collection
286
    {
287
        return $this->permissions
288
            ->merge($this->getPermissionsViaRoles())
289
            ->sort()
290
            ->values();
291
    }
292
293
    protected function getStoredRole($role): Role
294
    {
295
        if (is_string($role)) {
296
            return app(Role::class)->findByName($role, $this->getGuardName());
297
        }
298
299
        return $role;
300
    }
301
}
302