Completed
Push — master ( 40cd73...37f317 )
by Chris
01:33
created

HasRoles::hasRole()   B

Complexity

Conditions 8
Paths 12

Size

Total Lines 26

Duplication

Lines 3
Ratio 11.54 %

Importance

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