Completed
Push — master ( f9e78a...edb43e )
by Abdelrahman
09:22
created

HasRoles::hydrateIfString()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 3
nc 6
nop 1
dl 0
loc 5
rs 9.2
c 1
b 0
f 0
1
<?php
2
3
/*
4
 * NOTICE OF LICENSE
5
 *
6
 * Part of the Rinvex Fort Package.
7
 *
8
 * This source file is subject to The MIT License (MIT)
9
 * that is bundled with this package in the LICENSE file.
10
 *
11
 * Package: Rinvex Fort Package
12
 * License: The MIT License (MIT)
13
 * Link:    https://rinvex.com
14
 */
15
16
namespace Rinvex\Fort\Traits;
17
18
use Rinvex\Fort\Models\Role;
19
use Illuminate\Support\Collection;
20
21
trait HasRoles
22
{
23
    use HasAbilities;
24
25
    /**
26
     * Attach the given roles to the model.
27
     *
28
     * @param int|string|array|\ArrayAccess|\Rinvex\Fort\Models\Role $roles
29
     *
30
     * @return $this
31
     */
32
    public function assignRoles($roles)
33
    {
34
        $this->setRoles($roles, 'syncWithoutDetaching');
35
36
        return $this;
37
    }
38
39
    /**
40
     * Sync the given roles to the model.
41
     *
42
     * @param int|string|array|\ArrayAccess|\Rinvex\Fort\Models\Role $roles
43
     *
44
     * @return $this
45
     */
46
    public function syncRoles($roles)
47
    {
48
        $this->setRoles($roles, 'sync');
49
50
        return $this;
51
    }
52
53
    /**
54
     * Detach the given roles from the model.
55
     *
56
     * @param int|string|array|\ArrayAccess|\Rinvex\Fort\Models\Role $roles
57
     *
58
     * @return $this
59
     */
60
    public function removeRoles($roles)
61
    {
62
        $this->setRoles($roles, 'detach');
63
64
        return $this;
65
    }
66
67
    /**
68
     * Set the given role(s) to the model.
69
     *
70
     * @param int|string|array|\ArrayAccess|\Rinvex\Fort\Models\Role $roles
71
     * @param string                                                 $process
72
     *
73
     * @return bool
74
     */
75
    protected function setRoles($roles, string $process)
76
    {
77
        // Guess event name
78
        $event = $process == 'syncWithoutDetaching' ? 'attach' : $process;
79
80
        // If the "attaching/syncing/detaching" event returns false we'll cancel this operation and
81
        // return false, indicating that the attaching/syncing/detaching failed. This provides a
82
        // chance for any listeners to cancel save operations if validations fail or whatever.
83
        if ($this->fireModelEvent($event.'ing') === false) {
0 ignored issues
show
Bug introduced by
It seems like fireModelEvent() 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...
84
            return false;
85
        }
86
87
        // Hydrate Roles
88
        $roles = $this->hydrateRoles($roles)->pluck('id')->toArray();
89
90
        // Set roles
91
        $this->roles()->$process($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...
92
93
        // Fire the roles attached/synced/detached event
94
        $this->fireModelEvent($event.'ed', false);
0 ignored issues
show
Bug introduced by
It seems like fireModelEvent() 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...
95
96
        return true;
97
    }
98
99
    /**
100
     * Determine if the entity has (one of) the given roles.
101
     *
102
     * @param mixed $roles
103
     *
104
     * @return bool
105
     */
106
    public function hasRole($roles)
107
    {
108
        // Single role slug
109
        if (is_string($roles)) {
110
            return $this->roles->contains('slug', $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...
111
        }
112
113
        // Single role id
114
        if (is_string($roles)) {
115
            return $this->roles->contains('id', $roles);
116
        }
117
118
        // Single role model
119
        if ($roles instanceof Role) {
120
            return $this->roles->contains('slug', $roles->slug);
121
        }
122
123
        // Array of role slugs
124
        if (is_array($roles) && isset($roles[0]) && is_string($roles[0])) {
125
            return ! $this->roles->pluck('slug')->intersect($roles)->isEmpty();
126
        }
127
128
        // Array of role Ids
129
        if (is_array($roles) && isset($roles[0]) && is_int($roles[0])) {
130
            return ! $this->roles->pluck('id')->intersect($roles)->isEmpty();
131
        }
132
133
        // Collection of role models
134
        if ($roles instanceof Collection) {
135
            return ! $roles->intersect($this->roles->pluck('slug'))->isEmpty();
136
        }
137
138
        return false;
139
    }
140
141
    /**
142
     * Alias for `hasRole` method.
143
     *
144
     * @param mixed $roles
145
     *
146
     * @return bool
147
     */
148
    public function hasAnyRole($roles)
149
    {
150
        return $this->hasRole($roles);
151
    }
152
153
    /**
154
     * Determine if the given entity has all of the given roles.
155
     *
156
     * @param mixed $roles
157
     *
158
     * @return bool
159
     */
160
    public function hasAllRoles($roles)
161
    {
162
        // Single role slug
163
        if (is_string($roles)) {
164
            return $this->roles->contains('slug', $roles);
165
        }
166
167
        // Single role id
168
        if (is_int($roles)) {
169
            return $this->roles->contains('id', $roles);
170
        }
171
172
        // Single role model
173
        if ($roles instanceof Role) {
174
            return $this->roles->contains('slug', $roles->slug);
175
        }
176
177
        // Array of role slugs
178
        if (is_array($roles) && isset($roles[0]) && is_string($roles[0])) {
179
            return $this->roles->pluck('slug')->count() == count($roles)
180
                   && $this->roles->pluck('slug')->diff($roles)->isEmpty();
181
        }
182
183
        // Array of role ids
184
        if (is_array($roles) && isset($roles[0]) && is_int($roles[0])) {
185
            return $this->roles->pluck('id')->count() == count($roles)
186
                   && $this->roles->pluck('id')->diff($roles)->isEmpty();
187
        }
188
189
        // Collection of role models
190
        if ($roles instanceof Collection) {
191
            return $this->roles->count() == $roles->count() && $this->roles->diff($roles)->isEmpty();
192
        }
193
194
        return false;
195
    }
196
197
    /**
198
     * Hydrate roles.
199
     *
200
     * @param int|string|array|\ArrayAccess|\Rinvex\Fort\Models\Role $roles
201
     *
202
     * @return \Illuminate\Support\Collection
203
     */
204
    protected function hydrateRoles($roles)
205
    {
206
        $isRolesStringBased = $this->isRolesStringBased($roles);
207
        $isRolesIntBased = $this->isRolesIntBased($roles);
208
        $field = $isRolesStringBased ? 'slug' : 'id';
209
210
        return $isRolesStringBased || $isRolesIntBased ? Role::whereIn($field, (array) $roles)->get() : collect($roles);
211
    }
212
213
    /**
214
     * Determine if the given role(ies) are string based.
215
     *
216
     * @param int|string|array|\ArrayAccess|\Rinvex\Fort\Models\Role $roles
217
     *
218
     * @return bool
219
     */
220
    protected function isRolesStringBased($roles)
221
    {
222
        return is_string($roles) || (is_array($roles) && isset($roles[0]) && is_string($roles[0]));
223
    }
224
225
    /**
226
     * Determine if the given role(ies) are integer based.
227
     *
228
     * @param int|string|array|\ArrayAccess|\Rinvex\Fort\Models\Role $roles
229
     *
230
     * @return bool
231
     */
232
    protected function isRolesIntBased($roles)
233
    {
234
        return is_int($roles) || (is_array($roles) && isset($roles[0]) && is_int($roles[0]));
235
    }
236
}
237