91 lines
2.1 KiB
PHP
91 lines
2.1 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Services;
|
||
|
|
|
||
|
|
use App\Models\Role;
|
||
|
|
use App\Models\Permission;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Service to handle Role-related operations.
|
||
|
|
*/
|
||
|
|
class RoleService
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Store a new role.
|
||
|
|
*
|
||
|
|
* @param array $data Data to create the role.
|
||
|
|
* @return Role The created role.
|
||
|
|
*/
|
||
|
|
public function store(array $data): Role
|
||
|
|
{
|
||
|
|
return Role::create([
|
||
|
|
'name' => $data['name'],
|
||
|
|
'slug' => $data['slug'],
|
||
|
|
'description' => $data['description'] ?? null,
|
||
|
|
'is_protected' => false,
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Update an existing role.
|
||
|
|
*
|
||
|
|
* @param Role $role The role to update.
|
||
|
|
* @param array $data Data to update the role.
|
||
|
|
* @return bool True if successful, false if protected.
|
||
|
|
*/
|
||
|
|
public function update(Role $role, array $data): bool
|
||
|
|
{
|
||
|
|
if ($role->is_protected) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
return $role->update([
|
||
|
|
'name' => $data['name'],
|
||
|
|
'slug' => $data['slug'],
|
||
|
|
'description' => $data['description'] ?? null,
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Delete a role.
|
||
|
|
*
|
||
|
|
* @param Role $role The role to delete.
|
||
|
|
* @return bool True if successful, false if protected or has users.
|
||
|
|
*/
|
||
|
|
public function delete(Role $role): bool
|
||
|
|
{
|
||
|
|
if ($role->is_protected) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($role->users()->exists()) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
return $role->delete();
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Toggle a permission for a role.
|
||
|
|
*
|
||
|
|
* @param Role $role The role to modify.
|
||
|
|
* @param int $permissionId The ID of the permission to toggle.
|
||
|
|
* @param bool $isActive Whether the permission should be attached.
|
||
|
|
* @return bool True if successful, false if protected.
|
||
|
|
*/
|
||
|
|
public function togglePermission(Role $role, int $permissionId, bool $isActive): bool
|
||
|
|
{
|
||
|
|
if ($role->is_protected) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($isActive) {
|
||
|
|
$role->permissions()->syncWithoutDetaching([$permissionId]);
|
||
|
|
} else {
|
||
|
|
$role->permissions()->detach($permissionId);
|
||
|
|
}
|
||
|
|
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|