Completed
Pull Request — master (#1449)
by Chris
01:16
created

HasRoles::getArgumentRoles()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 1
nop 2
dl 0
loc 13
rs 9.8333
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 Illuminate\Database\Eloquent\Relations\BelongsToMany;
9
10
trait HasRoles
11
{
12
    use HasPermissions;
13
14
    public static function bootHasRoles()
15
    {
16
        static::deleting(function ($model) {
17
            if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
18
                return;
19
            }
20
21
            $model->roles()->detach();
22
        });
23
    }
24
25
    /**
26
     * A model may have multiple roles.
27
     */
28
    public function roles(): BelongsToMany
29
    {
30
        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...
31
            config('permission.models.role'),
32
            'model',
33
            config('permission.table_names.model_has_roles'),
34
            config('permission.column_names.model_morph_key'),
35
            'role_id'
36
        );
37
    }
38
39
    /**
40
     * Scope the model query to certain roles only.
41
     *
42
     * @param \Illuminate\Database\Eloquent\Builder $query
43
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
44
     * @param string $guard
45
     *
46
     * @return \Illuminate\Database\Eloquent\Builder
47
     */
48 View Code Duplication
    public function scopeRole(Builder $query, $roles, $guard = null): Builder
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...
49
    {
50
        if ($roles instanceof Collection) {
51
            $roles = $roles->all();
52
        }
53
54
        if (! is_array($roles)) {
55
            $roles = [$roles];
56
        }
57
58
        $roles = $this->getArgumentRoles($roles, $guard);
59
60
        return $query->whereHas('roles', function (Builder $subQuery) use ($roles) {
61
            $subQuery->whereIn(config('permission.table_names.roles').'.id', \array_column($roles, 'id'));
62
        });
63
    }
64
65
    /**
66
     * Scope the model query without certain roles.
67
     *
68
     * @param \Illuminate\Database\Eloquent\Builder $query
69
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
70
     * @param string $guard
71
     *
72
     * @return \Illuminate\Database\Eloquent\Builder
73
     */
74 View Code Duplication
    public function scopeWithoutRole(Builder $query, $roles, $guard = null): Builder
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...
75
    {
76
        if ($roles instanceof Collection) {
77
            $roles = $roles->all();
78
        }
79
80
        if (! is_array($roles)) {
81
            $roles = [$roles];
82
        }
83
84
        $roles = $this->getArgumentRoles($roles, $guard);
85
86
        return $query->whereDoesntHave('roles', function (Builder $subQuery) use ($roles) {
87
            $subQuery->whereIn(config('permission.table_names.roles').'.id', \array_column($roles, 'id'));
88
        });
89
    }
90
91
    /**
92
     * Assign the given role to the model.
93
     *
94
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
95
     *
96
     * @return $this
97
     */
98 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...
99
    {
100
        $roles = collect($roles)
101
            ->flatten()
102
            ->map(function ($role) {
103
                if (empty($role)) {
104
                    return false;
105
                }
106
107
                return $this->getStoredRole($role);
108
            })
109
            ->filter(function ($role) {
110
                return $role instanceof Role;
111
            })
112
            ->each(function ($role) {
113
                $this->ensureModelSharesGuard($role);
114
            })
115
            ->map->id
116
            ->all();
117
118
        $model = $this->getModel();
0 ignored issues
show
Bug introduced by
It seems like getModel() 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...
119
120
        if ($model->exists) {
121
            $this->roles()->sync($roles, false);
122
            $model->load('roles');
123
        } else {
124
            $class = \get_class($model);
125
126
            $class::saved(
127
                function ($object) use ($roles, $model) {
128
                    static $modelLastFiredOn;
129
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
130
                        return;
131
                    }
132
                    $object->roles()->sync($roles, false);
133
                    $object->load('roles');
134
                    $modelLastFiredOn = $object;
135
                });
136
        }
137
138
        $this->forgetCachedPermissions();
139
140
        return $this;
141
    }
142
143
    /**
144
     * Revoke the given role from the model.
145
     *
146
     * @param string|\Spatie\Permission\Contracts\Role $role
147
     */
148
    public function removeRole($role)
149
    {
150
        $this->roles()->detach($this->getStoredRole($role));
151
152
        $this->load('roles');
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...
153
154
        $this->forgetCachedPermissions();
155
156
        return $this;
157
    }
158
159
    /**
160
     * Remove all current roles and set the given ones.
161
     *
162
     * @param  array|\Spatie\Permission\Contracts\Role|string  ...$roles
163
     *
164
     * @return $this
165
     */
166
    public function syncRoles(...$roles)
167
    {
168
        $this->roles()->detach();
169
170
        return $this->assignRole($roles);
171
    }
172
173
    /**
174
     * Determine if the model has (one of) the given role(s).
175
     *
176
     * @param string|int|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
177
     * @param string|null $guard
178
     * @return bool
179
     */
180
    public function hasRole($roles, string $guard = null): bool
181
    {
182 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...
183
            $roles = $this->convertPipeToArray($roles);
184
        }
185
186 View Code Duplication
        if (is_string($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...
187
            return $guard
188
                ? $this->roles->where('guard_name', $guard)->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...
189
                : $this->roles->contains('name', $roles);
190
        }
191
192 View Code Duplication
        if (is_int($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...
193
            return $guard
194
                ? $this->roles->where('guard_name', $guard)->contains('id', $roles)
195
                : $this->roles->contains('id', $roles);
196
        }
197
198
        if ($roles instanceof Role) {
199
            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...
200
        }
201
202
        if (is_array($roles)) {
203
            foreach ($roles as $role) {
204
                if ($this->hasRole($role, $guard)) {
205
                    return true;
206
                }
207
            }
208
209
            return false;
210
        }
211
212
        return $roles->intersect($guard ? $this->roles->where('guard_name', $guard) : $this->roles)->isNotEmpty();
213
    }
214
215
    /**
216
     * Determine if the model has any of the given role(s).
217
     *
218
     * Alias to hasRole() but without Guard controls
219
     *
220
     * @param string|int|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
221
     *
222
     * @return bool
223
     */
224
    public function hasAnyRole(...$roles): bool
225
    {
226
        return $this->hasRole($roles);
227
    }
228
229
    /**
230
     * Determine if the model has all of the given role(s).
231
     *
232
     * @param  string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection  $roles
233
     * @param  string|null  $guard
234
     * @return bool
235
     */
236
    public function hasAllRoles($roles, string $guard = null): bool
237
    {
238 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...
239
            $roles = $this->convertPipeToArray($roles);
240
        }
241
242 View Code Duplication
        if (is_string($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...
243
            return $guard
244
                ? $this->roles->where('guard_name', $guard)->contains('name', $roles)
245
                : $this->roles->contains('name', $roles);
246
        }
247
248
        if ($roles instanceof Role) {
249
            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...
250
        }
251
252
        $roles = collect()->make($roles)->map(function ($role) {
253
            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...
254
        });
255
256
        return $roles->intersect(
257
            $guard
258
                ? $this->roles->where('guard_name', $guard)->pluck('name')
259
                : $this->getRoleNames()) == $roles;
260
    }
261
262
    /**
263
     * Return all permissions directly coupled to the model.
264
     */
265
    public function getDirectPermissions(): Collection
266
    {
267
        return $this->permissions;
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...
268
    }
269
270
    public function getRoleNames(): Collection
271
    {
272
        return $this->roles->pluck('name');
273
    }
274
275
    protected function getStoredRole($role): Role
276
    {
277
        $roleClass = $this->getRoleClass();
278
279
        if (is_numeric($role)) {
280
            return $roleClass->findById($role, $this->getDefaultGuardName());
281
        }
282
283
        if (is_string($role)) {
284
            return $roleClass->findByName($role, $this->getDefaultGuardName());
285
        }
286
287
        return $role;
288
    }
289
290
    protected function convertPipeToArray(string $pipeString)
291
    {
292
        $pipeString = trim($pipeString);
293
294
        if (strlen($pipeString) <= 2) {
295
            return $pipeString;
296
        }
297
298
        $quoteCharacter = substr($pipeString, 0, 1);
299
        $endCharacter = substr($quoteCharacter, -1, 1);
300
301
        if ($quoteCharacter !== $endCharacter) {
302
            return explode('|', $pipeString);
303
        }
304
305
        if (! in_array($quoteCharacter, ["'", '"'])) {
306
            return explode('|', $pipeString);
307
        }
308
309
        return explode('|', trim($pipeString, $quoteCharacter));
310
    }
311
312
    protected function getArgumentRoles($roles, $guard = null)
313
    {
314
        return array_map(function ($role) use ($guard) {
315
            if ($role instanceof Role) {
316
                return $role;
317
            }
318
319
            $method = is_numeric($role) ? 'findById' : 'findByName';
320
            $guard = $guard ?: $this->getDefaultGuardName();
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $guard, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
321
322
            return $this->getRoleClass()->{$method}($role, $guard);
323
        }, $roles);
324
    }
325
}
326