Completed
Pull Request — master (#975)
by Chris
01:50
created

HasRoles::hasAllRoles()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 20

Duplication

Lines 3
Ratio 15 %

Importance

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