/ app / Http / Services / RoleService.php
RoleService.php
 1  <?php
 2  
 3  namespace App\Http\Services;
 4  
 5  use App\Models\User;
 6  use Exception;
 7  use Illuminate\Support\Collection;
 8  use Illuminate\Support\Facades\DB;
 9  use Spatie\Permission\Models\Role;
10  
11  
12  class RoleService
13  {
14      public static function search(string $searchString, string $sortField, string $sortDirection)
15      {
16          $query = Role::query();
17          $query->when($searchString, function ($query, $searchString) {
18              $query->where('name', 'like', '%' . $searchString . '%');
19          });
20          $query->orderBy($sortField, $sortDirection);
21  
22          return $query;
23      }
24  
25      public static function collectionWithParents(?\App\Models\Role $role): Collection
26      {
27          $roles = collect([]);
28  
29          if (!$role)
30              return $roles;
31  
32  
33          $roles->push($role);
34          $parent = $role->parent;
35  
36          while ($parent) {
37              $roles->push($parent);
38              $parent = $parent->parent;
39          }
40  
41          return $roles;
42      }
43  
44      public static function collectionWithDescendants(?\App\Models\Role $role): Collection
45      {
46          $roles = collect([]);
47  
48          if (!$role)
49              return $roles;
50  
51          $roles->push($role);
52          $child = $role->child;
53  
54          while ($child) {
55              $roles->push($child);
56              $child = $child->child;
57          }
58  
59          return $roles;
60      }
61  
62      public static function getAllCompatibleRoles(User $user): Collection
63      {
64          $roles = collect([]);
65  
66          foreach ($user->roles as $role) {
67              $roles = $roles->merge(self::collectionWithDescendants($role));
68          }
69  
70          return $roles;
71      }
72  
73      public static function create(string $name): void
74      {
75          DB::beginTransaction();
76          try {
77              Role::create(['name' => $name]);
78              DB::commit();
79          } catch (Exception $e) {
80              DB::rollBack();
81              logger()->error($e->getMessage());
82          }
83      }
84  
85      public static function assignPermissions(int $roleId, array $permissions)
86      {
87          DB::beginTransaction();
88          try {
89              Role::findOrFail($roleId)->givePermissionTo($permissions);
90              DB::commit();
91          } catch (Exception $e) {
92              DB::rollBack();
93              logger()->error($e->getMessage());
94          }
95      }
96  }