Completed
Push — develop ( 4264eb...5ad3b4 )
by Abdelrahman
9s
created

HasRoles::hasAnyRoles()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rinvex\Fort\Traits;
6
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Builder;
9
use Illuminate\Database\Eloquent\Collection;
10
use Illuminate\Support\Collection as BaseCollection;
11
12
trait HasRoles
13
{
14
    use HasAbilities;
15
16
    /**
17
     * Register a saved model event with the dispatcher.
18
     *
19
     * @param \Closure|string $callback
20
     *
21
     * @return void
22
     */
23
    abstract public static function saved($callback);
24
25
    /**
26
     * Register a deleted model event with the dispatcher.
27
     *
28
     * @param \Closure|string $callback
29
     *
30
     * @return void
31
     */
32
    abstract public static function deleted($callback);
33
34
    /**
35
     * Boot the HasRoles trait for the model.
36
     *
37
     * @return void
38
     */
39
    public static function bootHasRoles()
40
    {
41
        static::deleted(function (self $model) {
42
            $model->roles()->detach();
43
        });
44
    }
45
46
    /**
47
     * Attach the given roles to the model.
48
     *
49
     * @param mixed $roles
50
     *
51
     * @return void
52
     */
53
    public function setRolesAttribute($roles)
54
    {
55
        static::saved(function (self $model) use ($roles) {
56
            $model->syncRoles($roles);
57
        });
58
    }
59
60
    /**
61
     * Attach model roles.
62
     *
63
     * @param mixed $roles
64
     *
65
     * @return $this
66
     */
67
    public function assignRoles($roles)
68
    {
69
        // Use 'sync' not 'attach' to avoid Integrity constraint violation
70
        $this->roles()->sync($this->parseRoles($roles), false);
0 ignored issues
show
Bug introduced by
It seems like roles() 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...
71
72
        return $this;
73
    }
74
75
    /**
76
     * Sync model roles.
77
     *
78
     * @param mixed $roles
79
     * @param bool  $detaching
80
     *
81
     * @return $this
82
     */
83
    public function syncRoles($roles, bool $detaching = true)
84
    {
85
        $this->roles()->sync($this->parseRoles($roles), $detaching);
0 ignored issues
show
Bug introduced by
It seems like roles() 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...
86
87
        return $this;
88
    }
89
90
    /**
91
     * Detach model roles.
92
     *
93
     * @param mixed $roles
94
     *
95
     * @return $this
96
     */
97
    public function retractRoles($roles = null)
98
    {
99
        ! $roles || $roles = $this->parseRoles($roles);
100
101
        $this->roles()->detach($roles);
0 ignored issues
show
Bug introduced by
It seems like roles() 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...
102
103
        return $this;
104
    }
105
106
    /**
107
     * Determine if the model has any of the given roles.
108
     *
109
     * @param mixed $roles
110
     *
111
     * @return bool
112
     */
113
    public function hasAnyRoles($roles): bool
114
    {
115
        $roles = $this->parseRoles($roles);
116
117
        return ! $this->roles->pluck('id')->intersect($roles)->isEmpty();
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...
118
    }
119
120
    /**
121
     * Determine if the given entity has all of the given roles.
122
     *
123
     * @param mixed $roles
124
     *
125
     * @return bool
126
     */
127
    public function hasAllRoles($roles): bool
128
    {
129
        $roles = $this->parseRoles($roles);
130
131
        return collect($roles)->diff($this->roles->pluck('id'))->isEmpty();
132
    }
133
134
    /**
135
     * Scope query with all the given roles.
136
     *
137
     * @param \Illuminate\Database\Eloquent\Builder $builder
138
     * @param mixed                                 $roles
139
     *
140
     * @return \Illuminate\Database\Eloquent\Builder
141
     */
142
    public function scopeWithAllRoles(Builder $builder, $roles): Builder
143
    {
144
        $roles = $this->parseRoles($roles);
145
146
        collect($roles)->each(function ($role) use ($builder) {
147
            $builder->whereHas('roles', function (Builder $builder) use ($role) {
148
                return $builder->where('id', $role);
149
            });
150
        });
151
152
        return $builder;
153
    }
154
155
    /**
156
     * Scope query with any of the given roles.
157
     *
158
     * @param \Illuminate\Database\Eloquent\Builder $builder
159
     * @param mixed                                 $roles
160
     *
161
     * @return \Illuminate\Database\Eloquent\Builder
162
     */
163
    public function scopeWithAnyRoles(Builder $builder, $roles): Builder
164
    {
165
        $roles = $this->parseRoles($roles);
166
167
        return $builder->whereHas('roles', function (Builder $builder) use ($roles) {
168
            $builder->whereIn('id', $roles);
169
        });
170
    }
171
172
    /**
173
     * Scope query without any of the given roles.
174
     *
175
     * @param \Illuminate\Database\Eloquent\Builder $builder
176
     * @param mixed                                 $roles
177
     *
178
     * @return \Illuminate\Database\Eloquent\Builder
179
     */
180
    public function scopeWithoutRoles(Builder $builder, $roles): Builder
181
    {
182
        $roles = $this->parseRoles($roles);
183
184
        return $builder->whereDoesntHave('roles', function (Builder $builder) use ($roles) {
185
            $builder->whereIn('id', $roles);
186
        });
187
    }
188
189
    /**
190
     * Scope query without any roles.
191
     *
192
     * @param \Illuminate\Database\Eloquent\Builder $builder
193
     *
194
     * @return \Illuminate\Database\Eloquent\Builder
195
     */
196
    public function scopeWithoutAnyRoles(Builder $builder): Builder
197
    {
198
        return $builder->doesntHave('roles');
199
    }
200
201
    /**
202
     * Parse role IDs.
203
     *
204
     * @param mixed $roles
205
     *
206
     * @return array
207
     */
208
    protected function parseRoles($roles): array
209
    {
210
        ! $roles instanceof Model || $roles = [$roles->getKey()];
211
        ! $roles instanceof Collection || $roles = $roles->modelKeys();
212
        ! $roles instanceof BaseCollection || $roles = $roles->toArray();
213
214
        // Find roles by slug, and get their IDs
215
        if (is_string($roles) || (is_array($roles) && is_string(array_first($roles)))) {
216
            $roles = app('rinvex.fort.role')->whereIn('slug', (array) $roles)->get()->pluck('id')->toArray();
217
        }
218
219
        return (array) $roles;
220
    }
221
}
222