Completed
Pull Request — master (#867)
by
unknown
01:36
created

HasRoles::scopeRole()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 2
dl 0
loc 30
rs 8.8177
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 View Code Duplication
    public static function bootHasRoles()
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...
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
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
     * Assign the given role to the model.
92
     *
93
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
94
     *
95
     * @return $this
96
     */
97 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...
98
    {
99
        $roles = collect($roles)
100
            ->flatten()
101
            ->map(function ($role) {
102
                if (empty($role)) {
103
                    return false;
104
                }
105
106
                return $this->getStoredRole($role);
107
            })
108
            ->filter(function ($role) {
109
                return $role instanceof Role;
110
            })
111
            ->each(function ($role) {
112
                $this->ensureModelSharesGuard($role);
113
            })
114
            ->map->id
115
            ->all();
116
117
        $this->roles()->sync($roles, false);
118
119
        $this->forgetCachedPermissions();
120
121
        return $this;
122
    }
123
124
    /**
125
     * Revoke the given role from the model.
126
     *
127
     * @param string|\Spatie\Permission\Contracts\Role $role
128
     */
129
    public function removeRole($role)
130
    {
131
        $this->roles()->detach($this->getStoredRole($role));
132
    }
133
134
    /**
135
     * Remove all current roles and set the given ones.
136
     *
137
     * @param array|\Spatie\Permission\Contracts\Role|string ...$roles
138
     *
139
     * @return $this
140
     */
141
    public function syncRoles(...$roles)
142
    {
143
        $this->roles()->detach();
144
145
        return $this->assignRole($roles);
146
    }
147
148
    /**
149
     * Determine if the model has (one of) the given role(s).
150
     *
151
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
152
     *
153
     * @return bool
154
     */
155
    public function hasRole($roles): bool
156
    {
157 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...
158
            $roles = $this->convertPipeToArray($roles);
159
        }
160
161
        if (is_string($roles)) {
162
            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...
163
        }
164
165
        if ($roles instanceof Role) {
166
            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...
167
        }
168
169
        if (is_array($roles)) {
170
            foreach ($roles as $role) {
171
                if ($this->hasRole($role)) {
172
                    return true;
173
                }
174
            }
175
176
            return false;
177
        }
178
179
        return $roles->intersect($this->roles)->isNotEmpty();
180
    }
181
182
    /**
183
     * Determine if the model has any of the given role(s).
184
     *
185
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
186
     *
187
     * @return bool
188
     */
189
    public function hasAnyRole($roles): bool
190
    {
191
        return $this->hasRole($roles);
192
    }
193
194
    /**
195
     * Determine if the model has all of the given role(s).
196
     *
197
     * @param string|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
198
     *
199
     * @return bool
200
     */
201
    public function hasAllRoles($roles): bool
202
    {
203 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...
204
            $roles = $this->convertPipeToArray($roles);
205
        }
206
207
        if (is_string($roles)) {
208
            return $this->roles->contains('name', $roles);
209
        }
210
211
        if ($roles instanceof Role) {
212
            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...
213
        }
214
215
        $roles = collect()->make($roles)->map(function ($role) {
216
            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...
217
        });
218
219
        return $roles->intersect($this->roles->pluck('name')) == $roles;
220
    }
221
222
    /**
223
     * Return all permissions directly coupled to the model.
224
     */
225
    public function getDirectPermissions(): Collection
226
    {
227
        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...
228
    }
229
230
    public function getRoleNames(): Collection
231
    {
232
        return $this->roles->pluck('name');
233
    }
234
235
    protected function getStoredRole($role): Role
236
    {
237
        $roleClass = $this->getRoleClass();
238
239
        if (is_numeric($role)) {
240
            return $roleClass->findById($role, $this->getDefaultGuardName());
241
        }
242
243
        if (is_string($role)) {
244
            return $roleClass->findByName($role, $this->getDefaultGuardName());
245
        }
246
247
        return $role;
248
    }
249
250
    protected function convertPipeToArray(string $pipeString)
251
    {
252
        $pipeString = trim($pipeString);
253
254
        if (strlen($pipeString) <= 2) {
255
            return $pipeString;
256
        }
257
258
        $quoteCharacter = substr($pipeString, 0, 1);
259
        $endCharacter = substr($quoteCharacter, -1, 1);
260
261
        if ($quoteCharacter !== $endCharacter) {
262
            return explode('|', $pipeString);
263
        }
264
265
        if (! in_array($quoteCharacter, ["'", '"'])) {
266
            return explode('|', $pipeString);
267
        }
268
269
        return explode('|', trim($pipeString, $quoteCharacter));
270
    }
271
}
272