PermissionsGroup::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php namespace Arcanedev\LaravelAuth\Models;
2
3
use Arcanedev\LaravelAuth\Events\PermissionsGroups\{
4
    AttachedPermissionsToGroup, AttachedPermissionToGroup, AttachingPermissionsToGroup, AttachingPermissionToGroup,
5
    CreatedPermissionsGroup, CreatingPermissionsGroup, DeletedPermissionsGroup, DeletingPermissionsGroup,
6
    DetachedAllPermissions, DetachedPermissionFromGroup, DetachedPermissionsFromGroup, DetachingAllPermissions,
7
    DetachingPermissionFromGroup, DetachingPermissionsFromGroup, SavedPermissionsGroup, SavingPermissionsGroup,
8
    UpdatedPermissionsGroup, UpdatingPermissionsGroup
9
};
10
use Arcanesoft\Contracts\Auth\Models\Permission as PermissionContract;
11
use Arcanesoft\Contracts\Auth\Models\PermissionsGroup as PermissionsGroupContract;
12
use Illuminate\Database\Eloquent\Model as Eloquent;
13
use Illuminate\Support\Str;
14
15
/**
16
 * Class     PermissionsGroup
17
 *
18
 * @package  Arcanedev\LaravelAuth\Models
19
 * @author   ARCANEDEV <[email protected]>
20
 *
21
 * @property  int                                       id
22
 * @property  string                                    name
23
 * @property  string                                    slug
24
 * @property  string                                    description
25
 * @property  \Carbon\Carbon                            created_at
26
 * @property  \Carbon\Carbon                            updated_at
27
 * @property  \Illuminate\Database\Eloquent\Collection  permissions
28
 */
29
class PermissionsGroup extends AbstractModel implements PermissionsGroupContract
30
{
31
    /* -----------------------------------------------------------------
32
     |  Properties
33
     | -----------------------------------------------------------------
34
     */
35
36
    /**
37
     * The attributes that are mass assignable.
38
     *
39
     * @var array
40
     */
41
    protected $fillable = ['name', 'slug', 'description'];
42
43
    /**
44
     * The event map for the model.
45
     *
46
     * @var array
47
     */
48
    protected $dispatchesEvents = [
49
        'creating' => CreatingPermissionsGroup::class,
50
        'created'  => CreatedPermissionsGroup::class,
51
        'updating' => UpdatingPermissionsGroup::class,
52
        'updated'  => UpdatedPermissionsGroup::class,
53
        'saving'   => SavingPermissionsGroup::class,
54
        'saved'    => SavedPermissionsGroup::class,
55
        'deleting' => DeletingPermissionsGroup::class,
56
        'deleted'  => DeletedPermissionsGroup::class,
57
    ];
58
59
    /**
60
     * The attributes that should be cast to native types.
61
     *
62
     * @var array
63
     */
64
    protected $casts = [
65
        'id' => 'integer',
66
    ];
67
68
    /* -----------------------------------------------------------------
69
     |  Constructor
70
     | -----------------------------------------------------------------
71
     */
72
73
    /**
74
     * Create a new Eloquent model instance.
75
     *
76
     * @param  array  $attributes
77
     */
78 48
    public function __construct(array $attributes = [])
79
    {
80 48
        parent::__construct($attributes);
81
82 48
        $this->setTable(
83 48
            config('laravel-auth.permissions-groups.table', 'permissions_groups')
84
        );
85 48
    }
86
87
    /* -----------------------------------------------------------------
88
     |  Relationships
89
     | -----------------------------------------------------------------
90
     */
91
92
    /**
93
     * Permissions Groups has many permissions.
94
     *
95
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
96
     */
97 39
    public function permissions()
98
    {
99 39
        return $this->hasMany(
100 39
            config('laravel-auth.permissions.model', Permission::class),
101 39
            'group_id'
102
        );
103
    }
104
105
    /* -----------------------------------------------------------------
106
     |  Getters & Setters
107
     | -----------------------------------------------------------------
108
     */
109
110
    /**
111
     * Set the name attribute.
112
     *
113
     * @param  string  $name
114
     */
115 39
    public function setNameAttribute($name)
116
    {
117 39
        $this->attributes['name'] = $name;
118 39
        $this->setSlugAttribute($name);
119 39
    }
120
121
    /**
122
     * Set the slug attribute.
123
     *
124
     * @param  string  $slug
125
     */
126 39
    public function setSlugAttribute($slug)
127
    {
128 39
        $this->attributes['slug'] = Str::slug($slug, config('laravel-auth.permissions-groups.slug-separator', '-'));
129 39
    }
130
131
    /* -----------------------------------------------------------------
132
     |  Main Methods
133
     | -----------------------------------------------------------------
134
     */
135
136
    /**
137
     * Create and attach a permission.
138
     *
139
     * @param  array  $attributes
140
     * @param  bool   $reload
141
     */
142 6
    public function createPermission(array $attributes, $reload = true)
143
    {
144 6
        $this->permissions()->create($attributes);
145
146 6
        $this->loadPermissions($reload);
147 6
    }
148
149
    /**
150
     * Attach the permission to a group.
151
     *
152
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission  $permission
153
     * @param  bool                                          $reload
154
     */
155 18
    public function attachPermission(&$permission, $reload = true)
156
    {
157 18
        if ($this->hasPermission($permission)) return;
158
159 18
        event(new AttachingPermissionToGroup($this, $permission));
160 18
        $permission = $this->permissions()->save($permission);
0 ignored issues
show
Documentation introduced by
$permission is of type object<Arcanesoft\Contra...Auth\Models\Permission>, but the function expects a object<Illuminate\Database\Eloquent\Model>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
161 18
        event(new AttachedPermissionToGroup($this, $permission));
0 ignored issues
show
Documentation introduced by
$permission is of type object<Illuminate\Database\Eloquent\Model>|false, but the function expects a object<Arcanesoft\Contra...Auth\Models\Permission>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
162
163 18
        $this->loadPermissions($reload);
164 18
    }
165
166
    /**
167
     * Attach the permission by id to a group.
168
     *
169
     * @param  int   $id
170
     * @param  bool  $reload
171
     *
172
     * @return \Arcanesoft\Contracts\Auth\Models\Permission|null
173
     */
174 3
    public function attachPermissionById($id, $reload = true)
175
    {
176 3
        $permission = $this->getPermissionById($id);
177
178 3
        if ($permission !== null)
179 3
            $this->attachPermission($permission, $reload);
180
181 3
        return $permission;
182
    }
183
184
    /**
185
     * Attach a collection of permissions to the group.
186
     *
187
     * @param  \Illuminate\Database\Eloquent\Collection|array  $permissions
188
     * @param  bool                                            $reload
189
     *
190
     * @return \Illuminate\Database\Eloquent\Collection|array
191
     */
192 9
    public function attachPermissions($permissions, $reload = true)
193
    {
194 9
        event(new AttachingPermissionsToGroup($this, $permissions));
195 9
        $permissions = $this->permissions()->saveMany($permissions);
196 9
        event(new AttachedPermissionsToGroup($this, $permissions));
0 ignored issues
show
Bug introduced by
It seems like $permissions defined by $this->permissions()->saveMany($permissions) on line 195 can also be of type object<Traversable>; however, Arcanedev\LaravelAuth\Ev...sToGroup::__construct() does only seem to accept object<Illuminate\Support\Collection>|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
197
198 9
        $this->loadPermissions($reload);
199
200 9
        return $permissions;
201
    }
202
203
    /**
204
     * Attach the permission from a group.
205
     *
206
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission  $permission
207
     * @param  bool                                          $reload
208
     */
209 9
    public function detachPermission(&$permission, $reload = true)
210
    {
211 9
        if ( ! $this->hasPermission($permission))
212 6
            return;
213
214
        /** @var  \Arcanesoft\Contracts\Auth\Models\Permission  $permission */
215 9
        $permission = $this->getPermissionFromGroup($permission);
216
217 9
        event(new DetachingPermissionFromGroup($this, $permission));
218 9
        $permission->update(['group_id' => 0]);
219 9
        event(new DetachedPermissionFromGroup($this, $permission));
220
221 9
        $this->loadPermissions($reload);
222 9
    }
223
224
    /**
225
     * Attach the permission by id to a group.
226
     *
227
     * @param  int   $id
228
     * @param  bool  $reload
229
     *
230
     * @return \Arcanesoft\Contracts\Auth\Models\Permission
231
     */
232 3
    public function detachPermissionById($id, $reload = true)
233
    {
234 3
        if ( ! is_null($permission = $this->getPermissionById($id)))
235 3
            $this->detachPermission($permission, $reload);
236
237 3
        return $permission;
238
    }
239
240
    /**
241
     * Detach multiple permissions by ids.
242
     *
243
     * @param  array  $ids
244
     * @param  bool   $reload
245
     *
246
     * @return int
247
     */
248 3
    public function detachPermissions(array $ids, $reload = true)
249
    {
250 3
        event(new DetachingPermissionsFromGroup($this, $ids));
251 3
        $detached = $this->permissions()->whereIn('id', $ids)->update(['group_id' => 0]);
252 3
        event(new DetachedPermissionsFromGroup($this, $ids, $detached));
253
254 3
        $this->loadPermissions($reload);
255
256 3
        return $detached;
257
    }
258
259
    /**
260
     * Detach all permissions from the group.
261
     *
262
     * @param  bool  $reload
263
     *
264
     * @return int
265
     */
266 6
    public function detachAllPermissions($reload = true)
267
    {
268 6
        event(new DetachingAllPermissions($this));
269 6
        $detached = $this->permissions()->update(['group_id' => 0]);
270 6
        event(new DetachedAllPermissions($this, $detached));
271
272 6
        $this->loadPermissions($reload);
273
274 6
        return $detached;
275
    }
276
277
    /* -----------------------------------------------------------------
278
     |  Check Methods
279
     | -----------------------------------------------------------------
280
     */
281
282
    /**
283
     * Check if role has the given permission (Permission Model or Id).
284
     *
285
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $id
286
     *
287
     * @return bool
288
     */
289 24
    public function hasPermission($id)
290
    {
291 24
        if ($id instanceof Eloquent) $id = $id->getKey();
292
293 24
        return $this->getPermissionFromGroup($id) !== null;
294
    }
295
296
    /* -----------------------------------------------------------------
297
     |  Other Methods
298
     | -----------------------------------------------------------------
299
     */
300
301
    /**
302
     * Get a permission from the group.
303
     *
304
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $id
305
     *
306
     * @return \Arcanesoft\Contracts\Auth\Models\Permission|null
307
     */
308 24
    private function getPermissionFromGroup($id)
309
    {
310 24
        if ($id instanceof Eloquent) $id = $id->getKey();
311
312 24
        $this->loadPermissions();
313
314 24
        return $this->permissions
315
            ->filter(function (PermissionContract $permission) use ($id) {
316 24
                return $permission->getKey() == $id;
317 24
            })
318 24
            ->first();
319
    }
320
321
    /**
322
     * Get a permission by id.
323
     *
324
     * @param  int  $id
325
     *
326
     * @return \Arcanesoft\Contracts\Auth\Models\Permission|null
327
     */
328 6
    private function getPermissionById($id)
329
    {
330 6
        return $this->permissions()->getRelated()->where('id', $id)->first();
331
    }
332
333
    /**
334
     * Load the permissions.
335
     *
336
     * @param  bool  $load
337
     *
338
     * @return self
339
     */
340 33
    protected function loadPermissions($load = true)
341
    {
342 33
        return $load ? $this->load('permissions') : $this;
343
    }
344
}
345