Completed
Push — master ( 4d8dce...e624ea )
by ARCANEDEV
13s
created

Role::deactivate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php namespace Arcanedev\LaravelAuth\Models;
2
3
use Arcanedev\LaravelAuth\Events\Roles\AttachedPermissionToRole;
4
use Arcanedev\LaravelAuth\Events\Roles\AttachedUserToRole;
5
use Arcanedev\LaravelAuth\Events\Roles\AttachingPermissionToRole;
6
use Arcanedev\LaravelAuth\Events\Roles\AttachingUserToRole;
7
use Arcanedev\LaravelAuth\Events\Roles\CreatedRole;
8
use Arcanedev\LaravelAuth\Events\Roles\CreatingRole;
9
use Arcanedev\LaravelAuth\Events\Roles\DeletedRole;
10
use Arcanedev\LaravelAuth\Events\Roles\DeletingRole;
11
use Arcanedev\LaravelAuth\Events\Roles\DetachedAllPermissionsFromRole;
12
use Arcanedev\LaravelAuth\Events\Roles\DetachedAllUsersFromRole;
13
use Arcanedev\LaravelAuth\Events\Roles\DetachedPermissionFromRole;
14
use Arcanedev\LaravelAuth\Events\Roles\DetachedUserFromRole;
15
use Arcanedev\LaravelAuth\Events\Roles\DetachingAllPermissionsFromRole;
16
use Arcanedev\LaravelAuth\Events\Roles\DetachingAllUsersFromRole;
17
use Arcanedev\LaravelAuth\Events\Roles\DetachingPermissionFromRole;
18
use Arcanedev\LaravelAuth\Events\Roles\DetachingUserFromRole;
19
use Arcanedev\LaravelAuth\Events\Roles\SavedRole;
20
use Arcanedev\LaravelAuth\Events\Roles\SavingRole;
21
use Arcanedev\LaravelAuth\Events\Roles\UpdatedRole;
22
use Arcanedev\LaravelAuth\Events\Roles\UpdatingRole;
23
use Arcanedev\LaravelAuth\Models\Traits\Activatable;
24
use Arcanesoft\Contracts\Auth\Models\Role as RoleContract;
25
use Arcanesoft\Contracts\Auth\Models\Permission as PermissionContract;
26
use Illuminate\Database\Eloquent\Model as Eloquent;
27
use Illuminate\Support\Str;
28
29
/**
30
 * Class     Role
31
 *
32
 * @package  Arcanedev\LaravelAuth\Models
33
 * @author   ARCANEDEV <[email protected]>
34
 *
35
 * @property  int                                       id
36
 * @property  string                                    name
37
 * @property  string                                    slug
38
 * @property  string                                    description
39
 * @property  bool                                      is_active
40
 * @property  bool                                      is_locked
41
 * @property  \Carbon\Carbon                            created_at
42
 * @property  \Carbon\Carbon                            updated_at
43
 *
44
 * @property  \Illuminate\Database\Eloquent\Collection       users
45
 * @property  \Illuminate\Database\Eloquent\Collection       permissions
46
 *
47
 * @property  \Arcanedev\LaravelAuth\Models\Pivots\RoleUser|\Arcanedev\LaravelAuth\Models\Pivots\PermissionRole  pivot
48
 */
49
class Role extends AbstractModel implements RoleContract
50
{
51
    /* -----------------------------------------------------------------
52
     |  Traits
53
     | -----------------------------------------------------------------
54
     */
55
56
    use Activatable;
57
58
    /* -----------------------------------------------------------------
59
     |  Properties
60
     | -----------------------------------------------------------------
61
     */
62
63
    /**
64
     * The attributes that are mass assignable.
65
     *
66
     * @var array
67
     */
68
    protected $fillable = ['name', 'slug', 'description'];
69
70
    /**
71
     * The event map for the model.
72
     *
73
     * @var array
74
     */
75
    protected $dispatchesEvents = [
76
        'creating' => CreatingRole::class,
77
        'created'  => CreatedRole::class,
78
        'updating' => UpdatingRole::class,
79
        'updated'  => UpdatedRole::class,
80
        'saving'   => SavingRole::class,
81
        'saved'    => SavedRole::class,
82
        'deleting' => DeletingRole::class,
83
        'deleted'  => DeletedRole::class,
84
    ];
85
86
    /**
87
     * The attributes that should be casted to native types.
88
     *
89
     * @var array
90
     */
91
    protected $casts = [
92
        'id'        => 'integer',
93
        'is_active' => 'boolean',
94
        'is_locked' => 'boolean',
95
    ];
96
97
    /* -----------------------------------------------------------------
98
     |  Constructor
99
     | -----------------------------------------------------------------
100
     */
101
102
    /**
103
     * Create a new Eloquent model instance.
104
     *
105
     * @param  array  $attributes
106
     */
107 76
    public function __construct(array $attributes = [])
108
    {
109 76
        parent::__construct($attributes);
110
111 76
        $this->setTable(config('laravel-auth.roles.table', 'roles'));
112 76
    }
113
114
    /* -----------------------------------------------------------------
115
     |  Relationships
116
     | -----------------------------------------------------------------
117
     */
118
119
    /**
120
     * Role belongs to many users.
121
     *
122
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
123
     */
124 12
    public function users()
125
    {
126
        return $this
127 12
            ->belongsToMany(
128 12
                config('laravel-auth.users.model', User::class),
129 12
                $this->getPrefix().config('laravel-auth.role-user.table', 'permission_role')
130
            )
131 12
            ->using(Pivots\RoleUser::class)
132 12
            ->withTimestamps();
133
    }
134
135
    /**
136
     * Role belongs to many permissions.
137
     *
138
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
139
     */
140 22
    public function permissions()
141
    {
142
        return $this
143 22
            ->belongsToMany(
144 22
                config('laravel-auth.permissions.model', Permission::class),
145 22
                $this->getPrefix().config('laravel-auth.permission-role.table', 'permission_role')
146
            )
147 22
            ->using(Pivots\PermissionRole::class)
148 22
            ->withTimestamps();
149
    }
150
151
    /* -----------------------------------------------------------------
152
     |  Getters & Setters
153
     | -----------------------------------------------------------------
154
     */
155
156
    /**
157
     * Set the name attribute.
158
     *
159
     * @param  string  $name
160
     */
161 66
    public function setNameAttribute($name)
162
    {
163 66
        $this->attributes['name'] = $name;
164 66
        $this->setSlugAttribute($name);
165 66
    }
166
167
    /**
168
     * Set the slug attribute.
169
     *
170
     * @param  string  $slug
171
     */
172 66
    public function setSlugAttribute($slug)
173
    {
174 66
        $this->attributes['slug'] = $this->slugify($slug);
175 66
    }
176
177
    /* ------------------------------------------------------------------------------------------------
178
     |  CRUD Functions
179
     | ------------------------------------------------------------------------------------------------
180
     */
181
182
    /**
183
     * Activate the model.
184
     *
185
     * @param  bool  $save
186
     *
187
     * @return bool
188
     */
189 2
    public function activate($save = true)
190
    {
191 2
        return $this->switchActive(true, $save);
192
    }
193
194
    /**
195
     * Deactivate the model.
196
     *
197
     * @param  bool  $save
198
     *
199
     * @return bool
200
     */
201 4
    public function deactivate($save = true)
202
    {
203 4
        return $this->switchActive(false, $save);
204
    }
205
206
    /**
207
     * Attach a permission to a role.
208
     *
209
     * @param  \Arcanesoft\Contracts\Auth\Models\User|int  $user
210
     * @param  bool                                        $reload
211
     */
212 6
    public function attachUser($user, $reload = true)
213
    {
214 6
        if ($this->hasUser($user)) return;
215
216 6
        event(new AttachingUserToRole($this, $user));
217 6
        $this->users()->attach($user);
218 6
        event(new AttachedUserToRole($this, $user));
219
220 6
        $this->loadUsers($reload);
221 6
    }
222
223
    // TODO: Adding attach multiple users to a role ?
224
225
    /**
226
     * Detach a user from a role.
227
     *
228
     * @param  \Arcanesoft\Contracts\Auth\Models\User|int  $user
229
     * @param  bool                                        $reload
230
     *
231
     * @return int
232
     */
233 2
    public function detachUser($user, $reload = true)
234
    {
235 2
        event(new DetachingUserFromRole($this, $user));
236 2
        $results = $this->users()->detach($user);
237 2
        event(new DetachedUserFromRole($this, $user, $results));
238
239 2
        $this->loadUsers($reload);
240
241 2
        return $results;
242
    }
243
244
    // TODO: Adding detach multiple users to a role ?
245
246
    /**
247
     * Detach all users from a role.
248
     *
249
     * @param  bool  $reload
250
     *
251
     * @return int
252
     */
253 4
    public function detachAllUsers($reload = true)
254
    {
255 4
        event(new DetachingAllUsersFromRole($this));
256 4
        $results = $this->users()->detach();
257 4
        event(new DetachedAllUsersFromRole($this, $results));
258
259 4
        $this->loadUsers($reload);
260
261 4
        return $results;
262
    }
263
264
    /**
265
     * Attach a permission to a role.
266
     *
267
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $permission
268
     * @param  bool                                              $reload
269
     */
270 18
    public function attachPermission($permission, $reload = true)
271
    {
272 18
        if ($this->hasPermission($permission)) return;
273
274 18
        event(new AttachingPermissionToRole($this, $permission));
275 18
        $this->permissions()->attach($permission);
276 18
        event(new AttachedPermissionToRole($this, $permission));
277
278 18
        $this->loadPermissions($reload);
279 18
    }
280
281
    // TODO: Adding attach multiple permissions to a role ?
282
283
    /**
284
     * Detach a permission from a role.
285
     *
286
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $permission
287
     * @param  bool                                              $reload
288
     *
289
     * @return int
290
     */
291 2
    public function detachPermission($permission, $reload = true)
292
    {
293 2
        if ( ! $this->hasPermission($permission)) return 0;
294
295 2
        event(new DetachingPermissionFromRole($this, $permission));
296 2
        $results = $this->permissions()->detach($permission);
297 2
        event(new DetachedPermissionFromRole($this, $permission, $results));
298
299 2
        $this->loadPermissions($reload);
300
301 2
        return $results;
302
    }
303
304
    // TODO: Adding detach multiple permissions to a role ?
305
306
    /**
307
     * Detach all permissions from a role.
308
     *
309
     * @param  bool  $reload
310
     *
311
     * @return int
312
     */
313 4
    public function detachAllPermissions($reload = true)
314
    {
315 4
        if ($this->permissions->isEmpty()) return 0;
316
317 2
        event(new DetachingAllPermissionsFromRole($this));
318 2
        $results = $this->permissions()->detach();
319 2
        event(new DetachedAllPermissionsFromRole($this, $results));
320
321 2
        $this->loadPermissions($reload);
322
323 2
        return $results;
324
    }
325
326
    /* -----------------------------------------------------------------
327
     |  Check Methods
328
     | -----------------------------------------------------------------
329
     */
330
331
    /**
332
     * Check if role has the given user (User Model or Id).
333
     *
334
     * @param  \Arcanesoft\Contracts\Auth\Models\User|int  $id
335
     *
336
     * @return bool
337
     */
338 6
    public function hasUser($id)
339
    {
340 6
        if ($id instanceof Eloquent) $id = $id->getKey();
341
342 6
        return $this->users->contains('id', $id);
343
    }
344
345
    /**
346
     * Check if role has the given permission (Permission Model or Id).
347
     *
348
     * @param  \Arcanesoft\Contracts\Auth\Models\Permission|int  $id
349
     *
350
     * @return bool
351
     */
352 18
    public function hasPermission($id)
353
    {
354 18
        if ($id instanceof Eloquent)
355 18
            $id = $id->getKey();
356
357 18
        return $this->permissions->contains('id', $id);
358
    }
359
360
    /**
361
     * Check if role is associated with a permission by slug.
362
     *
363
     * @param  string  $slug
364
     *
365
     * @return bool
366
     */
367 6
    public function can($slug)
368
    {
369 6
        if ( ! $this->isActive())
370
            return false;
371
372 6
        return $this->permissions->filter(function (PermissionContract $permission) use ($slug) {
373 6
            return $permission->hasSlug($slug);
374 6
        })->first() !== null;
375
    }
376
377
    /**
378
     * Check if a role is associated with any of given permissions.
379
     *
380
     * @param  \Illuminate\Support\Collection|array  $permissions
381
     * @param  \Illuminate\Support\Collection        &$failed
382
     *
383
     * @return bool
384
     */
385 4
    public function canAny($permissions, &$failed = null)
386
    {
387 4
        $permissions = is_array($permissions) ? collect($permissions) : $permissions;
388
389 4
        $failed = $permissions->reject(function ($permission) {
390 4
            return $this->can($permission);
391 4
        })->values();
392
393 4
        return $permissions->count() !== $failed->count();
394
    }
395
396
    /**
397
     * Check if role is associated with all given permissions.
398
     *
399
     * @param  \Illuminate\Support\Collection|array  $permissions
400
     * @param  \Illuminate\Support\Collection        &$failed
401
     *
402
     * @return bool
403
     */
404 2
    public function canAll($permissions, &$failed = null)
405
    {
406 2
        $this->canAny($permissions, $failed);
407
408 2
        return $failed->isEmpty();
409
    }
410
411
    /**
412
     * Check if the role is locked.
413
     *
414
     * @return bool
415
     */
416 4
    public function isLocked()
417
    {
418 4
        return $this->is_locked;
419
    }
420
421
    /**
422
     * Check if slug is the same as the given value.
423
     *
424
     * @param  string  $value
425
     *
426
     * @return bool
427
     */
428 14
    public function hasSlug($value)
429
    {
430 14
        return $this->slug === $this->slugify($value);
431
    }
432
433
    /* -----------------------------------------------------------------
434
     |  Other Methods
435
     | -----------------------------------------------------------------
436
     */
437
438
    /**
439
     * Load the users.
440
     *
441
     * @param  bool  $load
442
     *
443
     * @return self
444
     */
445 8
    protected function loadUsers($load = true)
446
    {
447 8
        return $load ? $this->load('users') : $this;
448
    }
449
450
    /**
451
     * Load the permissions.
452
     *
453
     * @param  bool  $load
454
     *
455
     * @return self
456
     */
457 18
    protected function loadPermissions($load = true)
458
    {
459 18
        return $load ? $this->load('permissions') : $this;
460
    }
461
462
    /**
463
     * Slugify the value.
464
     *
465
     * @param  string  $value
466
     *
467
     * @return string
468
     */
469 66
    protected function slugify($value)
470
    {
471 66
        return Str::slug($value, config('laravel-auth.roles.slug-separator', '-'));
472
    }
473
}
474