Completed
Pull Request — master (#1336)
by
unknown
01:23
created

HasRoles::getStoredRole()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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