Completed
Push — master ( 8f5508...0e0fba )
by Chris
01:32
created

HasRoles::hasDirectPermission()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 18
Code Lines 10

Duplication

Lines 7
Ratio 38.89 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 7
nop 1
dl 7
loc 18
rs 8.8571
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 Illuminate\Database\Eloquent\Relations\MorphToMany;
9
10
trait HasRoles
11
{
12
    use HasPermissions;
13
14
    public static function bootHasRoles()
15
    {
16
        static::deleting(function ($model) {
17
            if (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) {
18
                return;
19
            }
20
21
            $model->roles()->detach();
22
        });
23
    }
24
25
    /**
26
     * A model may have multiple roles.
27
     */
28
    public function roles(): MorphToMany
29
    {
30
        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...
31
            config('permission.models.role'),
32
            'model',
33
            config('permission.table_names.model_has_roles'),
34
            'model_id',
35
            'role_id'
36
        );
37
    }
38
39
    /**
40
     * Scope the model query to certain roles only.
41
     *
42
     * @param \Illuminate\Database\Eloquent\Builder $query
43
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
44
     *
45
     * @return \Illuminate\Database\Eloquent\Builder
46
     */
47
    public function scopeRole(Builder $query, $roles): Builder
48
    {
49
        if ($roles instanceof Collection) {
50
            $roles = $roles->all();
51
        }
52
53
        if (! is_array($roles)) {
54
            $roles = [$roles];
55
        }
56
57
        $roles = array_map(function ($role) {
58
            if ($role instanceof Role) {
59
                return $role;
60
            }
61
62
            return app(Role::class)->findByName($role, $this->getDefaultGuardName());
63
        }, $roles);
64
65
        return $query->whereHas('roles', function ($query) use ($roles) {
66
            $query->where(function ($query) use ($roles) {
67
                foreach ($roles as $role) {
68
                    $query->orWhere(config('permission.table_names.roles').'.id', $role->id);
69
                }
70
            });
71
        });
72
    }
73
74
    /**
75
     * Assign the given role to the model.
76
     *
77
     * @param array|string|\Spatie\Permission\Contracts\Role ...$roles
78
     *
79
     * @return $this
80
     */
81 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...
82
    {
83
        $roles = collect($roles)
84
            ->flatten()
85
            ->map(function ($role) {
86
                return $this->getStoredRole($role);
87
            })
88
            ->each(function ($role) {
89
                $this->ensureModelSharesGuard($role);
90
            })
91
            ->all();
92
93
        $this->roles()->saveMany($roles);
94
95
        $this->forgetCachedPermissions();
96
97
        return $this;
98
    }
99
100
    /**
101
     * Revoke the given role from the model.
102
     *
103
     * @param string|\Spatie\Permission\Contracts\Role $role
104
     */
105
    public function removeRole($role)
106
    {
107
        $this->roles()->detach($this->getStoredRole($role));
108
    }
109
110
    /**
111
     * Remove all current roles and set the given ones.
112
     *
113
     * @param array|\Spatie\Permission\Contracts\Role|string ...$roles
114
     *
115
     * @return $this
116
     */
117
    public function syncRoles(...$roles)
118
    {
119
        $this->roles()->detach();
120
121
        return $this->assignRole($roles);
122
    }
123
124
    /**
125
     * Determine if the model has (one of) the given role(s).
126
     *
127
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
128
     *
129
     * @return bool
130
     */
131
    public function hasRole($roles): bool
132
    {
133 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...
134
            $roles = $this->convertPipeToArray($roles);
135
        }
136
137
        if (is_string($roles)) {
138
            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...
139
        }
140
141
        if ($roles instanceof Role) {
142
            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...
143
        }
144
145
        if (is_array($roles)) {
146
            foreach ($roles as $role) {
147
                if ($this->hasRole($role)) {
148
                    return true;
149
                }
150
            }
151
152
            return false;
153
        }
154
155
        return $roles->intersect($this->roles)->isNotEmpty();
156
    }
157
158
    /**
159
     * Determine if the model has any of the given role(s).
160
     *
161
     * @param string|array|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
162
     *
163
     * @return bool
164
     */
165
    public function hasAnyRole($roles): bool
166
    {
167
        return $this->hasRole($roles);
168
    }
169
170
    /**
171
     * Determine if the model has all of the given role(s).
172
     *
173
     * @param string|\Spatie\Permission\Contracts\Role|\Illuminate\Support\Collection $roles
174
     *
175
     * @return bool
176
     */
177
    public function hasAllRoles($roles): bool
178
    {
179 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...
180
            $roles = $this->convertPipeToArray($roles);
181
        }
182
183
        if (is_string($roles)) {
184
            return $this->roles->contains('name', $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
        $roles = collect()->make($roles)->map(function ($role) {
192
            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...
193
        });
194
195
        return $roles->intersect($this->roles->pluck('name')) == $roles;
196
    }
197
198
    /**
199
     * Return all permissions directly coupled to the model.
200
     */
201
    public function getDirectPermissions(): Collection
202
    {
203
        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...
204
    }
205
206
    public function getRoleNames(): Collection
207
    {
208
        return $this->roles->pluck('name');
209
    }
210
211
    protected function getStoredRole($role): Role
212
    {
213
        if (is_numeric($role)) {
214
            return app(Role::class)->findById($role, $this->getDefaultGuardName());
215
        }
216
217
        if (is_string($role)) {
218
            return app(Role::class)->findByName($role, $this->getDefaultGuardName());
219
        }
220
221
        return $role;
222
    }
223
224
    protected function convertPipeToArray(string $pipeString)
225
    {
226
        $pipeString = trim($pipeString);
227
228
        if (strlen($pipeString) <= 2) {
229
            return $pipeString;
230
        }
231
232
        $quoteCharacter = substr($pipeString, 0, 1);
233
        $endCharacter = substr($quoteCharacter, -1, 1);
234
235
        if ($quoteCharacter !== $endCharacter) {
236
            return explode('|', $pipeString);
237
        }
238
239
        if (! in_array($quoteCharacter, ["'", '"'])) {
240
            return explode('|', $pipeString);
241
        }
242
243
        return explode('|', trim($pipeString, $quoteCharacter));
244
    }
245
}
246