Completed
Push — master ( d0984d...8e3192 )
by Jeremy
10:29 queued 05:27
created

RolesAndPermissionsHelpersTrait::getUsers()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace jeremykenedy\LaravelRoles\Traits;
4
5
use Illuminate\Support\Facades\DB;
6
7
trait RolesAndPermissionsHelpersTrait
8
{
9
    /**
10
     * Delete a permission.
11
     *
12
     * @param int $id The identifier
13
     *
14
     * @return collection
0 ignored issues
show
Bug introduced by
The type jeremykenedy\LaravelRoles\Traits\collection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
     */
16
    public function deletePermission($id)
17
    {
18
        $permission = $this->getPermission($id);
19
        $permission->delete();
20
21
        return $permission;
22
    }
23
24
    /**
25
     * Destroy all the deleted roles.
26
     *
27
     * @return array
28
     */
29
    public function destroyAllTheDeletedPermissions()
30
    {
31
        $deletedPermissions = $this->getDeletedPermissions()->get();
32
        $deletedPermissionsCount = $deletedPermissions->count();
33
        $status = 'error';
34
35
        if ($deletedPermissionsCount > 0) {
36
            foreach ($deletedPermissions as $deletedPermission) {
37
                $this->removeUsersAndRolesFromPermissions($deletedPermission);
38
                $deletedPermission->forceDelete();
39
            }
40
            $status = 'success';
41
        }
42
43
        return [
44
            'status' => $status,
45
            'count'  => $deletedPermissionsCount,
46
        ];
47
    }
48
49
    /**
50
     * Destroy a permission from storage.
51
     *
52
     * @param int $id The identifier
53
     *
54
     * @return collection
55
     */
56
    public function destroyPermission($id)
57
    {
58
        $permission = $this->getDeletedPermission($id);
59
        $this->removeUsersAndRolesFromPermissions($permission);
60
        $permission->forceDelete();
61
62
        return $permission;
63
    }
64
65
    /**
66
     * Delete a role.
67
     *
68
     * @param int $id The identifier
69
     *
70
     * @return collection
71
     */
72
    public function deleteRole($id)
73
    {
74
        $role = $this->getRole($id);
75
        $role->delete();
76
77
        return $role;
78
    }
79
80
    /**
81
     * Destroy a role from storage.
82
     *
83
     * @param int $id The identifier
84
     *
85
     * @return collection
86
     */
87
    public function destroyRole($id)
88
    {
89
        $role = $this->getDeletedRole($id);
90
        $this->removeUsersAndPermissionsFromRole($role);
91
        $role->forceDelete();
92
93
        return $role;
94
    }
95
96
    /**
97
     * Destroy all the deleted roles.
98
     *
99
     * @return array
100
     */
101
    public function destroyAllTheDeletedRoles()
102
    {
103
        $deletedRoles = $this->getDeletedRoles()->get();
104
        $deletedRolesCount = $deletedRoles->count();
105
        $status = 'error';
106
107
        if ($deletedRolesCount > 0) {
108
            foreach ($deletedRoles as $deletedRole) {
109
                $this->removeUsersAndPermissionsFromRole($deletedRole);
110
                $deletedRole->forceDelete();
111
            }
112
            $status = 'success';
113
        }
114
115
        return [
116
            'status' => $status,
117
            'count'  => $deletedRolesCount,
118
        ];
119
    }
120
121
    /**
122
     * Get Soft Deleted Permission.
123
     *
124
     * @param int $id
125
     *
126
     * @return \Illuminate\Http\Response || collection
0 ignored issues
show
Documentation Bug introduced by
The doc comment \Illuminate\Http\Response || collection at position 2 could not be parsed: Unknown type name '|' at position 2 in \Illuminate\Http\Response || collection.
Loading history...
127
     */
128
    public function getDeletedPermission($id)
129
    {
130
        $item = config('roles.models.permission')::onlyTrashed()->where('id', $id)->get();
131
        if (count($item) != 1) {
132
            return abort(redirect('laravelroles::roles.index')
133
                            ->with('error', trans('laravelroles::laravelroles.errors.errorDeletedPermissionNotFound')));
134
        }
135
136
        return $item[0];
137
    }
138
139
    /**
140
     * Get Soft Deleted Role.
141
     *
142
     * @param int $id
143
     *
144
     * @return \Illuminate\Http\Response || collection
0 ignored issues
show
Documentation Bug introduced by
The doc comment \Illuminate\Http\Response || collection at position 2 could not be parsed: Unknown type name '|' at position 2 in \Illuminate\Http\Response || collection.
Loading history...
145
     */
146
    public function getDeletedRole($id)
147
    {
148
        $item = config('roles.models.role')::onlyTrashed()->where('id', $id)->get();
149
        if (count($item) != 1) {
150
            return abort(redirect('laravelroles::roles.index')
151
                            ->with('error', trans('laravelroles::laravelroles.errors.errorDeletedRoleNotFound')));
152
        }
153
154
        return $item[0];
155
    }
156
157
    /**
158
     * Gets the roles.
159
     *
160
     * @return collection The roles.
161
     */
162
    public function getRoles()
163
    {
164
        return config('roles.models.role')::all();
165
    }
166
167
    /**
168
     * Gets the role.
169
     *
170
     * @param int $id The identifier
171
     *
172
     * @return collection The role.
173
     */
174
    public function getRole($id)
175
    {
176
        return config('roles.models.role')::findOrFail($id);
177
    }
178
179
    /**
180
     * Gets the permissions.
181
     *
182
     * @return collection The permissions.
183
     */
184
    public function getPermissions()
185
    {
186
        return config('roles.models.permission')::all();
187
    }
188
189
    /**
190
     * Gets the permission.
191
     *
192
     * @param int $id The identifier
193
     *
194
     * @return collection The permission.
195
     */
196
    public function getPermission($id)
197
    {
198
        return config('roles.models.permission')::findOrFail($id);
199
    }
200
201
    /**
202
     * Gets the users.
203
     *
204
     * @return collection The users.
205
     */
206
    public function getUsers()
207
    {
208
        return config('roles.models.defaultUser')::all();
209
    }
210
211
    /**
212
     * Gets the user.
213
     *
214
     * @param int $id The user id
215
     *
216
     * @return User The user.
0 ignored issues
show
Bug introduced by
The type jeremykenedy\LaravelRoles\Traits\User was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
217
     */
218
    public function getUser($id)
219
    {
220
        return config('roles.models.defaultUser')::findOrFail($id);
221
    }
222
223
    /**
224
     * Gets the deleted roles.
225
     *
226
     * @return collection The deleted roles.
227
     */
228
    public function getDeletedRoles()
229
    {
230
        return config('roles.models.role')::onlyTrashed();
231
    }
232
233
    /**
234
     * Gets the deleted permissions.
235
     *
236
     * @return collection The deleted permissions.
237
     */
238
    public function getDeletedPermissions()
239
    {
240
        return config('roles.models.permission')::onlyTrashed();
241
    }
242
243
    /**
244
     * Gets the permissions with roles.
245
     *
246
     * @param int $roleId The role Id
247
     *
248
     * @return collection The permissions with roles.
249
     */
250
    public function getPermissionsWithRoles($roleId = null)
251
    {
252
        $query = DB::table(config('roles.permissionsRoleTable'));
253
        if ($roleId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $roleId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
254
            $query->where('role_id', '=', $roleId);
255
        }
256
257
        return $query->get();
258
    }
259
260
    /**
261
     * Gets the permission users.
262
     *
263
     * @param int $permissionId The permission identifier
264
     *
265
     * @return Collection The permission users.
0 ignored issues
show
Bug introduced by
The type jeremykenedy\LaravelRoles\Traits\Collection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
266
     */
267
    public function getPermissionUsers($permissionId = null)
268
    {
269
        $query = DB::table(config('roles.permissionsUserTable'));
270
        if ($permissionId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $permissionId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
271
            $query->where('permission_id', '=', $permissionId);
272
        }
273
274
        return $query->get();
275
    }
276
277
    /**
278
     * Gets the permission models.
279
     *
280
     * @return The permission models.
0 ignored issues
show
Bug introduced by
The type jeremykenedy\LaravelRoles\Traits\The was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
281
     */
282
    public function getPermissionModels()
283
    {
284
        $permissionModel = config('roles.models.permission');
285
286
        return DB::table(config('roles.permissionsTable'))->pluck('model')->merge(collect(class_basename(new $permissionModel())))->unique();
0 ignored issues
show
Bug Best Practice introduced by
The expression return Illuminate\Suppor...ionModel())))->unique() returns the type Illuminate\Support\Collection which is incompatible with the documented return type jeremykenedy\LaravelRoles\Traits\The.
Loading history...
287
    }
288
289
    /**
290
     * Gets the permission item data.
291
     *
292
     * @param int $id The Permission ID
293
     *
294
     * @return array The Permission item data.
295
     */
296
    public function getPermissionItemData($id)
297
    {
298
        $permission = config('roles.models.permission')::findOrFail($id);
299
        $users = $this->getUsers();
300
        $roles = $this->getRoles();
301
        $permissions = $this->getPermissions();
302
        $sortedRolesWithUsers = $this->getSortedUsersWithRoles($roles, $users);
303
        $sortedPermissionsRolesUsers = $this->getSortedPermissonsWithRolesAndUsers($sortedRolesWithUsers, $permissions, $users);
304
305
        $data = [];
306
307
        foreach ($sortedPermissionsRolesUsers as $item) {
308
            if ($item['permission']->id === $permission->id) {
309
                $data = [
310
                    'item' => $item,
311
                ];
312
            }
313
        }
314
315
        return $data;
316
    }
317
318
    /**
319
     * Gets the role permissions.
320
     *
321
     * @param int $id The Role Id
322
     *
323
     * @return array The role permissions.
324
     */
325
    public function getRolePermissions($id)
326
    {
327
        $permissionPivots = $this->getPermissionsWithRoles($id);
328
        $permissions = [];
329
330
        if (count($permissionPivots) != 0) {
331
            foreach ($permissionPivots as $permissionPivot) {
332
                $permissions[] = $this->getPermission($permissionPivot->permission_id);
333
            }
334
        }
335
336
        return collect($permissions);
0 ignored issues
show
Bug Best Practice introduced by
The expression return collect($permissions) returns the type Illuminate\Support\Collection which is incompatible with the documented return type array.
Loading history...
337
    }
338
339
    /**
340
     * Gets the role permissions identifiers.
341
     *
342
     * @param int $id The Role Id
343
     *
344
     * @return array The role permissions Ids.
345
     */
346
    public function getRolePermissionsIds($id)
347
    {
348
        $permissionPivots = $this->getPermissionsWithRoles($id);
349
        $permissionIds = [];
350
351
        if (count($permissionPivots) != 0) {
352
            foreach ($permissionPivots as $permissionPivot) {
353
                $permissionIds[] = $permissionPivot->permission_id;
354
            }
355
        }
356
357
        return $permissionIds;
358
    }
359
360
    /**
361
     * Gets the role users.
362
     *
363
     * @param int $roleId The role identifier
364
     *
365
     * @return array The role users.
366
     */
367
    public function getRoleUsers($roleId)
368
    {
369
        $queryRolesPivot = DB::table(config('roles.roleUserTable'));
370
        $users = [];
371
372
        if ($roleId) {
373
            $queryRolesPivot->where('role_id', '=', $roleId);
374
        }
375
376
        $pivots = $queryRolesPivot->get();
377
378
        if ($pivots->count() > 0) {
379
            foreach ($pivots as $pivot) {
380
                $users[] = $this->getUser($pivot->user_id);
381
            }
382
        }
383
384
        return $users;
385
    }
386
387
    /**
388
     * Gets the deleted permission and details (Roles and Users).
389
     *
390
     * @param int $id The identifier
391
     *
392
     * @return Permission The permission and details.
393
     */
394
    public function getDeletedPermissionAndDetails($id)
395
    {
396
        $permission = $this->getDeletedPermission($id);
397
        $users = $this->getAllUsersForPermission($permission);
398
        $permission['users'] = $users;
399
400
        return $permission;
401
    }
402
403
    /**
404
     * Gets all users for permission.
405
     *
406
     * @param collection $permission The permission
407
     *
408
     * @return collection All users for permission.
409
     */
410
    public function getAllUsersForPermission($permission)
411
    {
412
        $roles = $permission->roles()->get();
413
        $users = [];
414
        foreach ($roles as $role) {
415
            $users[] = $this->getRoleUsers($role->id);
416
        }
417
        $users = array_shift($users);
418
        $permissionUserPivots = $this->getPermissionUsers($permission->id);
419
        if ($permissionUserPivots->count() > 0) {
420
            foreach ($permissionUserPivots as $permissionUserPivot) {
421
                $users[] = $this->getUser($permissionUserPivot->user_id);
422
            }
423
        }
424
425
        return collect($users)->unique();
0 ignored issues
show
Bug Best Practice introduced by
The expression return collect($users)->unique() returns the type Illuminate\Support\Collection which is incompatible with the documented return type jeremykenedy\LaravelRoles\Traits\collection.
Loading history...
426
    }
427
428
    /**
429
     * Gets the dashboard data.
430
     *
431
     * @return array The dashboard data and view.
432
     */
433
    public function getDashboardData()
434
    {
435
        $roles = $this->getRoles();
436
        $permissions = $this->getPermissions();
437
        $deletedRoleItems = $this->getDeletedRoles();
438
        $deletedPermissionsItems = $this->getDeletedPermissions();
439
        $users = $this->getUsers();
440
        $sortedRolesWithUsers = $this->getSortedUsersWithRoles($roles, $users);
441
        $sortedRolesWithPermissionsAndUsers = $this->getSortedRolesWithPermissionsAndUsers($sortedRolesWithUsers, $permissions);
442
        $sortedPermissionsRolesUsers = $this->getSortedPermissonsWithRolesAndUsers($sortedRolesWithUsers, $permissions, $users);
443
444
        $data = [
445
            'roles'                              => $roles,
446
            'permissions'                        => $permissions,
447
            'deletedRoleItems'                   => $deletedRoleItems,
448
            'deletedPermissionsItems'            => $deletedPermissionsItems,
449
            'users'                              => $users,
450
            'sortedRolesWithUsers'               => $sortedRolesWithUsers,
451
            'sortedRolesWithPermissionsAndUsers' => $sortedRolesWithPermissionsAndUsers,
452
            'sortedPermissionsRolesUsers'        => $sortedPermissionsRolesUsers,
453
        ];
454
455
        $view = 'laravelroles::laravelroles.crud.dashboard';
456
457
        return [
458
            'data' => $data,
459
            'view' => $view,
460
        ];
461
    }
462
463
    /**
464
     * Restore all the deleted permissions.
465
     *
466
     * @return array
467
     */
468
    public function restoreAllTheDeletedPermissions()
469
    {
470
        $deletedPermissions = $this->getDeletedPermissions()->get();
471
        $deletedPermissionsCount = $deletedPermissions->count();
472
        $status = 'error';
473
474
        if ($deletedPermissionsCount > 0) {
475
            foreach ($deletedPermissions as $deletedPermission) {
476
                $deletedPermission->restore();
477
            }
478
            $status = 'success';
479
        }
480
481
        return [
482
            'status' => $status,
483
            'count'  => $deletedPermissionsCount,
484
        ];
485
    }
486
487
    /**
488
     * Restore all the deleted roles.
489
     *
490
     * @return array
491
     */
492
    public function restoreAllTheDeletedRoles()
493
    {
494
        $deletedRoles = $this->getDeletedRoles()->get();
495
        $deletedRolesCount = $deletedRoles->count();
496
        $status = 'error';
497
498
        if ($deletedRolesCount > 0) {
499
            foreach ($deletedRoles as $deletedRole) {
500
                $deletedRole->restore();
501
            }
502
            $status = 'success';
503
        }
504
505
        return [
506
            'status' => $status,
507
            'count'  => $deletedRolesCount,
508
        ];
509
    }
510
511
    /**
512
     * Restore a deleted permission.
513
     *
514
     * @param int $id The identifier
515
     *
516
     * @return collection
517
     */
518
    public function restoreDeletedPermission($id)
519
    {
520
        $permission = $this->getDeletedPermission($id);
521
        $permission->restore();
522
523
        return $permission;
524
    }
525
526
    /**
527
     * Restore a deleted role.
528
     *
529
     * @param int $id The identifier
530
     *
531
     * @return collection
532
     */
533
    public function restoreDeletedRole($id)
534
    {
535
        $role = $this->getDeletedRole($id);
536
        $role->restore();
537
538
        return $role;
539
    }
540
541
    /**
542
     * Retrieves permission roles.
543
     *
544
     * @param Permission $permission               The permission
545
     * @param Collection $permissionsAndRolesPivot The permissions and roles pivot
546
     * @param Collection $sortedRolesWithUsers     The sorted roles with users
547
     *
548
     * @return Collection of permission roles
549
     */
550
    public function retrievePermissionRoles($permission, $permissionsAndRolesPivot, $sortedRolesWithUsers)
551
    {
552
        $roles = [];
553
        foreach ($permissionsAndRolesPivot as $permissionAndRoleKey => $permissionAndRoleValue) {
554
            if ($permission->id === $permissionAndRoleValue->permission_id) {
555
                foreach ($sortedRolesWithUsers as $sortedRolesWithUsersItemKey => $sortedRolesWithUsersItemValue) {
556
                    if ($sortedRolesWithUsersItemValue['role']->id === $permissionAndRoleValue->role_id) {
557
                        $roles[] = $sortedRolesWithUsersItemValue['role'];
558
                    }
559
                }
560
            }
561
        }
562
563
        return collect($roles);
0 ignored issues
show
Bug Best Practice introduced by
The expression return collect($roles) returns the type Illuminate\Support\Collection which is incompatible with the documented return type jeremykenedy\LaravelRoles\Traits\Collection.
Loading history...
564
    }
565
566
    /**
567
     * Retrieves permission users.
568
     *
569
     * @param Permission $permission               The permission
570
     * @param Collection $permissionsAndRolesPivot The permissions and roles pivot
571
     * @param Collection $sortedRolesWithUsers     The sorted roles with users
572
     * @param Collection $permissionUsersPivot     The permission users pivot
573
     * @param Collection $users                    The users
574
     *
575
     * @return Collection of Permission Users
576
     */
577
    public function retrievePermissionUsers($permission, $permissionsAndRolesPivot, $sortedRolesWithUsers, $permissionUsersPivot, $appUsers)
578
    {
579
        $users = [];
580
        $userIds = [];
581
582
        // Get Users from permissions associated with roles
583
        foreach ($permissionsAndRolesPivot as $permissionsAndRolesPivotItemKey => $permissionsAndRolesPivotItemValue) {
584
            if ($permission->id === $permissionsAndRolesPivotItemValue->permission_id) {
585
                foreach ($sortedRolesWithUsers as $sortedRolesWithUsersItemKey => $sortedRolesWithUsersItemValue) {
586
                    if ($permissionsAndRolesPivotItemValue->role_id === $sortedRolesWithUsersItemValue['role']->id) {
587
                        foreach ($sortedRolesWithUsersItemValue['users'] as $sortedRolesWithUsersItemValueUser) {
588
                            $users[] = $sortedRolesWithUsersItemValueUser;
589
                        }
590
                    }
591
                }
592
            }
593
        }
594
595
        // Setup Users IDs from permissions associated with roles
596
        foreach ($users as $userKey => $userValue) {
597
            $userIds[] = $userValue->id;
598
        }
599
600
        // Get Users from permissions pivot table that are not already in users from permissions associated with roles
601
        foreach ($permissionUsersPivot as $permissionUsersPivotKey => $permissionUsersPivotItem) {
602
            if (!in_array($permissionUsersPivotItem->user_id, $userIds) && $permission->id === $permissionUsersPivotItem->permission_id) {
603
                foreach ($appUsers as $appUser) {
604
                    if ($appUser->id === $permissionUsersPivotItem->user_id) {
605
                        $users[] = $appUser;
606
                    }
607
                }
608
            }
609
        }
610
611
        return collect($users);
0 ignored issues
show
Bug Best Practice introduced by
The expression return collect($users) returns the type Illuminate\Support\Collection which is incompatible with the documented return type jeremykenedy\LaravelRoles\Traits\Collection.
Loading history...
612
    }
613
614
    /**
615
     * Gets the sorted users with roles.
616
     *
617
     * @param collection $roles The roles
618
     * @param collection $users The users
619
     *
620
     * @return collection The sorted users with roles.
621
     */
622
    public function getSortedUsersWithRoles($roles, $users)
623
    {
624
        $sortedUsersWithRoles = [];
625
626
        foreach ($roles as $rolekey => $roleValue) {
627
            $sortedUsersWithRoles[] = [
628
                'role'   => $roleValue,
629
                'users'  => [],
630
            ];
631
            foreach ($users as $user) {
632
                foreach ($user->roles as $userRole) {
633
                    if ($userRole->id === $sortedUsersWithRoles[$rolekey]['role']['id']) {
634
                        $sortedUsersWithRoles[$rolekey]['users'][] = $user;
635
                    }
636
                }
637
            }
638
        }
639
640
        return collect($sortedUsersWithRoles);
0 ignored issues
show
Bug Best Practice introduced by
The expression return collect($sortedUsersWithRoles) returns the type Illuminate\Support\Collection which is incompatible with the documented return type jeremykenedy\LaravelRoles\Traits\collection.
Loading history...
641
    }
642
643
    /**
644
     * Gets the sorted roles with permissions.
645
     *
646
     * @param collection $sortedRolesWithUsers The sorted roles with users
647
     * @param collection $permissions          The permissions
648
     *
649
     * @return collection The sorted roles with permissions.
650
     */
651
    public function getSortedRolesWithPermissionsAndUsers($sortedRolesWithUsers, $permissions)
652
    {
653
        $sortedRolesWithPermissions = [];
654
        $permissionsAndRoles = $this->getPermissionsWithRoles();
655
656
        foreach ($sortedRolesWithUsers as $sortedRolekey => $sortedRoleValue) {
657
            $role = $sortedRoleValue['role'];
658
            $users = $sortedRoleValue['users'];
659
            $sortedRolesWithPermissions[] = [
660
                'role'          => $role,
661
                'permissions'   => collect([]),
662
                'users'         => collect([]),
663
            ];
664
665
            // Add Permission with Role
666
            foreach ($permissionsAndRoles as $permissionAndRole) {
667
                if ($permissionAndRole->role_id == $role->id) {
668
                    foreach ($permissions as $permissionKey => $permissionValue) {
669
                        if ($permissionValue->id == $permissionAndRole->permission_id) {
670
                            $sortedRolesWithPermissions[$sortedRolekey]['permissions'][] = $permissionValue;
671
                        }
672
                    }
673
                }
674
            }
675
676
            // Add Users with Role
677
            foreach ($users as $user) {
678
                foreach ($user->roles as $userRole) {
679
                    if ($userRole->id === $sortedRolesWithPermissions[$sortedRolekey]['role']['id']) {
680
                        $sortedRolesWithPermissions[$sortedRolekey]['users'][] = $user;
681
                    }
682
                }
683
            }
684
        }
685
686
        return collect($sortedRolesWithPermissions);
0 ignored issues
show
Bug Best Practice introduced by
The expression return collect($sortedRolesWithPermissions) returns the type Illuminate\Support\Collection which is incompatible with the documented return type jeremykenedy\LaravelRoles\Traits\collection.
Loading history...
687
    }
688
689
    /**
690
     * Gets the sorted permissons with roles and users.
691
     *
692
     * @param collection $sortedRolesWithUsers The sorted roles with users
693
     * @param collection $permissions          The permissions
694
     * @param colection  $users                The users
0 ignored issues
show
Bug introduced by
The type jeremykenedy\LaravelRoles\Traits\colection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
695
     *
696
     * @return collection The sorted permissons with roles and users.
697
     */
698
    public function getSortedPermissonsWithRolesAndUsers($sortedRolesWithUsers, $permissions, $users)
699
    {
700
        $sortedPermissionsWithRoles = [];
701
        $permissionsAndRolesPivot = $this->getPermissionsWithRoles();
702
        $permissionUsersPivot = $this->getPermissionUsers();
703
704
        foreach ($permissions as $permissionKey => $permissionValue) {
705
            $sortedPermissionsWithRoles[] = [
706
                'permission'    => $permissionValue,
707
                'roles'         => $this->retrievePermissionRoles($permissionValue, $permissionsAndRolesPivot, $sortedRolesWithUsers),
708
                'users'         => $this->retrievePermissionUsers($permissionValue, $permissionsAndRolesPivot, $sortedRolesWithUsers, $permissionUsersPivot, $users),
709
            ];
710
        }
711
712
        return collect($sortedPermissionsWithRoles);
0 ignored issues
show
Bug Best Practice introduced by
The expression return collect($sortedPermissionsWithRoles) returns the type Illuminate\Support\Collection which is incompatible with the documented return type jeremykenedy\LaravelRoles\Traits\collection.
Loading history...
713
    }
714
715
    /**
716
     * Removes an users and permissions from role.
717
     *
718
     * @param Role$role   The role
719
     *
720
     * @return void
721
     */
722
    public function removeUsersAndPermissionsFromRole($role)
723
    {
724
        $users = $this->getUsers();
725
        $roles = $this->getRoles();
726
        $sortedRolesWithUsers = $this->getSortedUsersWithRoles($roles, $users);
727
        $roleUsers = [];
728
729
        // Remove Users Attached to Role
730
        foreach ($sortedRolesWithUsers as $sortedRolesWithUsersKey => $sortedRolesWithUsersValue) {
731
            if ($sortedRolesWithUsersValue['role'] == $role) {
732
                $roleUsers[] = $sortedRolesWithUsersValue['users'];
733
            }
734
        }
735
        foreach ($roleUsers as $roleUserKey => $roleUserValue) {
736
            if (!empty($roleUserValue)) {
737
                $roleUserValue[$roleUserKey]->detachRole($role);
738
            }
739
        }
740
741
        // Remove Permissions from Role
742
        $role->detachAllPermissions();
743
    }
744
745
    /**
746
     * Removes an users and permissions from permission.
747
     *
748
     * @param Permission $permission The Permission
749
     *
750
     * @return void
751
     */
752
    public function removeUsersAndRolesFromPermissions($permission)
753
    {
754
        $users = $this->getUsers();
755
        $roles = $this->getRoles();
756
        $permissions = $this->getPermissions();
757
        $sortedRolesWithUsers = $this->getSortedUsersWithRoles($roles, $users);
758
        $sortedPermissionsRolesUsers = $this->getSortedPermissonsWithRolesAndUsers($sortedRolesWithUsers, $permissions, $users);
759
760
        foreach ($sortedPermissionsRolesUsers as $sortedPermissionsRolesUsersKey => $sortedPermissionsRolesUsersItem) {
761
            if ($sortedPermissionsRolesUsersItem['permission']->id === $permission->id) {
762
763
                // Remove Permission from roles
764
                foreach ($sortedPermissionsRolesUsersItem['roles'] as $permissionRoleKey => $permissionRoleItem) {
765
                    $permissionRoleItem->detachPermission($permission);
766
                }
767
768
                // Permission Permission from Users
769
                foreach ($sortedPermissionsRolesUsersItem['users'] as $permissionUserKey => $permissionUserItem) {
770
                    $permissionUserItem->detachPermission($permission);
771
                }
772
            }
773
        }
774
    }
775
776
    /**
777
     * Stores role with permissions.
778
     *
779
     * @param array  $roleData        The role data
780
     * @param object $rolePermissions The role permissions
781
     *
782
     * @return collection The Role
783
     */
784
    public function storeRoleWithPermissions($roleData, $rolePermissions)
785
    {
786
        $role = config('roles.models.role')::create($roleData);
787
788
        if ($rolePermissions) {
0 ignored issues
show
introduced by
$rolePermissions is of type object, thus it always evaluated to true.
Loading history...
789
            $permissionIds = [];
790
            foreach ($rolePermissions as $permission) {
791
                $permissionIds[] = json_decode($permission)->id;
792
            }
793
            $role->syncPermissions($permissionIds);
794
        }
795
796
        return $role;
797
    }
798
799
    /**
800
     * Update Role with permissions.
801
     *
802
     * @param int    $id              The identifier
803
     * @param array  $roleData        The role data
804
     * @param object $rolePermissions The role permissions
805
     *
806
     * @return collection The Role
807
     */
808
    public function updateRoleWithPermissions($id, $roleData, $rolePermissions)
809
    {
810
        $role = config('roles.models.role')::findOrFail($id);
811
812
        $role->fill($roleData);
813
        $role->save();
814
        $role->detachAllPermissions();
815
816
        if ($rolePermissions) {
0 ignored issues
show
introduced by
$rolePermissions is of type object, thus it always evaluated to true.
Loading history...
817
            $permissionIds = [];
818
            foreach ($rolePermissions as $permission) {
819
                $permissionIds[] = json_decode($permission)->id;
820
            }
821
            $role->syncPermissions($permissionIds);
822
        }
823
824
        return $role;
825
    }
826
827
    /**
828
     * Stores a new permission.
829
     *
830
     * @param array $permissionData The permission data
831
     *
832
     * @return collection The New Permission
833
     */
834
    public function storeNewPermission($permissionData)
835
    {
836
        return config('roles.models.permission')::create($permissionData);
837
    }
838
839
    /**
840
     * Update a permission.
841
     *
842
     * @param int   $id             The identifier
843
     * @param array $permissionData The permission data
844
     *
845
     * @return collection
846
     */
847
    public function updatePermission($id, $permissionData)
848
    {
849
        $permission = config('roles.models.permission')::findOrFail($id);
850
        $permission->fill($permissionData);
851
        $permission->save();
852
853
        return $permission;
854
    }
855
}
856