Completed
Pull Request — master (#1328)
by
unknown
01:16
created

HasRoles::assignRole()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 45

Duplication

Lines 44
Ratio 97.78 %

Importance

Changes 0
Metric Value
cc 5
nc 2
nop 1
dl 44
loc 45
rs 8.8888
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
0 ignored issues
show
Bug introduced by
There is no parameter named $roles. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
56
     * @param string $guard
57
     *
58
     * @return \Illuminate\Database\Eloquent\Builder
59
     */
60
    public function scopeRole(Builder $query, $listOfRoles, $guard = null): Builder
61
    {
62
        if ($listOfRoles instanceof Collection) {
63
            $listOfRoles = $listOfRoles->all();
64
        }
65
66
        if (!is_array($listOfRoles)) {
67
            $listOfRoles = [$listOfRoles];
68
        }
69
70
        $guard = $guard ?: $this->getDefaultGuardName();
71
72
        $listOfRoleNames = [];
73
        $roles = [];
74
75 View Code Duplication
        foreach ($listOfRoles as $role) {
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...
76
            if ($role instanceof Role) {
77
                $roles[$role->id] = $role;
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...
78
            } else {
79
                $method = is_numeric($role) ? 'findById' : 'findByName';
80
81
                if (!is_numeric($role) && !isset($listOfRoleNames[$role])) {
82
                    $thisRole = $this->getRoleClass()->{$method}($role, $guard);
83
                    $roles[$thisRole->id] = $thisRole;
84
                    $listOfRoleNames[$thisRole->name] = null;
85
                } elseif (is_numeric($role) && !isset($roles[$role])) {
86
                    $thisRole = $this->getRoleClass()->{$method}($role, $guard);
87
                    $roles[$thisRole->id] = $thisRole;
88
                }
89
            }
90
        }
91
92
        return $query->whereHas('roles', function ($query) use ($roles) {
93
            $query->where(function ($query) use ($roles) {
94
                foreach ($roles as $role) {
95
                    $query->orWhere(config('permission.table_names.roles') . '.id', $role->id);
96
                }
97
            });
98
        });
99
    }
100
101
    /**
102
     * Assign the given role to the model.
103
     *
104
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
105
     *
106
     * @return $this
107
     */
108 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...
109
    {
110
        $roles = collect($roles)
111
            ->flatten()
112
            ->map(function ($role) {
113
                if (empty($role)) {
114
                    return false;
115
                }
116
117
                return $this->getStoredRole($role);
118
            })
119
            ->filter(function ($role) {
120
                return $role instanceof Role;
121
            })
122
            ->each(function ($role) {
123
                $this->ensureModelSharesGuard($role);
124
            })
125
            ->map->id
126
            ->all();
127
128
        $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...
129
130
        if ($model->exists) {
131
            $this->roles()->sync($roles, false);
132
            $model->load('roles');
133
        } else {
134
            $class = \get_class($model);
135
136
            $class::saved(
137
                function ($object) use ($roles, $model) {
138
                    static $modelLastFiredOn;
139
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
140
                        return;
141
                    }
142
                    $object->roles()->sync($roles, false);
143
                    $object->load('roles');
144
                    $modelLastFiredOn = $object;
145
                }
146
            );
147
        }
148
149
        $this->forgetCachedPermissions();
150
151
        return $this;
152
    }
153
154
    /**
155
     * Revoke the given role from the model.
156
     *
157
     * @param string|\Spatie\Permission\Contracts\Role $role
158
     */
159
    public function removeRole($role)
160
    {
161
        $this->roles()->detach($this->getStoredRole($role));
162
163
        $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...
164
165
        $this->forgetCachedPermissions();
166
167
        return $this;
168
    }
169
170
    /**
171
     * Remove all current roles and set the given ones.
172
     *
173
     * @param  array|\Spatie\Permission\Contracts\Role|string  ...$roles
174
     *
175
     * @return $this
176
     */
177
    public function syncRoles(...$roles)
178
    {
179
        $this->roles()->detach();
180
181
        return $this->assignRole($roles);
182
    }
183
184
    /**
185
     * Determine if the model has (one of) the given role(s).
186
     *
187
     * @param string|int|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
188
     * @param string|null $guard
189
     * @return bool
190
     */
191
    public function hasRole($roles, string $guard = null): bool
192
    {
193 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...
194
            $roles = $this->convertPipeToArray($roles);
195
        }
196
197 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...
198
            return $guard
199
                ? $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...
200
                : $this->roles->contains('name', $roles);
201
        }
202
203 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...
204
            return $guard
205
                ? $this->roles->where('guard_name', $guard)->contains('id', $roles)
206
                : $this->roles->contains('id', $roles);
207
        }
208
209
        if ($roles instanceof Role) {
210
            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...
211
        }
212
213
        if (is_array($roles)) {
214
            foreach ($roles as $role) {
215
                if ($this->hasRole($role, $guard)) {
216
                    return true;
217
                }
218
            }
219
220
            return false;
221
        }
222
223
        return $roles->intersect($guard ? $this->roles->where('guard_name', $guard) : $this->roles)->isNotEmpty();
224
    }
225
226
    /**
227
     * Determine if the model has any of the given role(s).
228
     *
229
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
230
     *
231
     * @return bool
232
     */
233
    public function hasAnyRole($roles): bool
234
    {
235
        return $this->hasRole($roles);
236
    }
237
238
    /**
239
     * Determine if the model has all of the given role(s).
240
     *
241
     * @param  string|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection  $roles
242
     * @param  string|null  $guard
243
     * @return bool
244
     */
245
    public function hasAllRoles($roles, string $guard = null): bool
246
    {
247 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...
248
            $roles = $this->convertPipeToArray($roles);
249
        }
250
251 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...
252
            return $guard
253
                ? $this->roles->where('guard_name', $guard)->contains('name', $roles)
254
                : $this->roles->contains('name', $roles);
255
        }
256
257
        if ($roles instanceof Role) {
258
            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...
259
        }
260
261
        $roles = collect()->make($roles)->map(function ($role) {
262
            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...
263
        });
264
265
        return $roles->intersect(
266
            $guard
267
                ? $this->roles->where('guard_name', $guard)->pluck('name')
268
                : $this->getRoleNames()
269
        ) == $roles;
270
    }
271
272
    /**
273
     * Return all permissions directly coupled to the model.
274
     */
275
    public function getDirectPermissions(): Collection
276
    {
277
        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...
278
    }
279
280
    public function getRoleNames(): Collection
281
    {
282
        return $this->roles->pluck('name');
283
    }
284
285
    protected function getStoredRole($role): Role
286
    {
287
        $roleClass = $this->getRoleClass();
288
289
        if (is_numeric($role)) {
290
            return $roleClass->findById($role, $this->getDefaultGuardName());
291
        }
292
293
        if (is_string($role)) {
294
            return $roleClass->findByName($role, $this->getDefaultGuardName());
295
        }
296
297
        return $role;
298
    }
299
300
    protected function convertPipeToArray(string $pipeString)
301
    {
302
        $pipeString = trim($pipeString);
303
304
        if (strlen($pipeString) <= 2) {
305
            return $pipeString;
306
        }
307
308
        $quoteCharacter = substr($pipeString, 0, 1);
309
        $endCharacter = substr($quoteCharacter, -1, 1);
310
311
        if ($quoteCharacter !== $endCharacter) {
312
            return explode('|', $pipeString);
313
        }
314
315
        if (!in_array($quoteCharacter, ["'", '"'])) {
316
            return explode('|', $pipeString);
317
        }
318
319
        return explode('|', trim($pipeString, $quoteCharacter));
320
    }
321
}
322