- Added DTOs (`AssignUsersToRoleData`, `RoleUserData`, `UserSelectData`) for user-role operations and UI data mapping. - Updated `RoleService` and `AppRoleService` with methods for user-role assignment, detachment, retrieval, and search. - Enhanced Blade views and Livewire components to support user-role management in "Roles and Apps." - Adjusted `Role`, `User`, and related models to incorporate Spatie roles and permissions support. - Improved UI with search and selection capabilities for assigning users to roles.
65 lines
1.6 KiB
PHP
65 lines
1.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Data\Role\{CreateRoleData, RoleData};
|
|
use App\Models\Role;
|
|
use Illuminate\Support\Facades\DB;
|
|
use InvalidArgumentException;
|
|
use NoDiscard;
|
|
use Spatie\LaravelData\PaginatedDataCollection;
|
|
use Throwable;
|
|
|
|
final class RoleService
|
|
{
|
|
/**
|
|
* Create a new role.
|
|
* Returns the created role DTO
|
|
*
|
|
* @throws Throwable when an error occurs during the creation.
|
|
*/
|
|
#[NoDiscard]
|
|
public function create(CreateRoleData $data): RoleData
|
|
{
|
|
$role = DB::transaction(fn () => Role::query()->create([
|
|
'name' => $data->name,
|
|
'guard_name' => 'web',
|
|
]));
|
|
|
|
return RoleData::from($role);
|
|
}
|
|
|
|
/**
|
|
* @throws InvalidArgumentException when id is invalid.
|
|
* @throws Throwable when an error occurs during the deletion.
|
|
*/
|
|
public function delete(int $id): void
|
|
{
|
|
if ($id <= 0) {
|
|
throw new InvalidArgumentException('Invalid id');
|
|
}
|
|
|
|
DB::transaction(function () use ($id): void {
|
|
Role::query()->findOrFail($id)->delete();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Returns a Paginated Collection of roles with their connected apps DTO
|
|
*
|
|
* @return PaginatedDataCollection<int, RoleData>
|
|
*/
|
|
#[NoDiscard]
|
|
public function getAll(): PaginatedDataCollection
|
|
{
|
|
$roles = Role::query()
|
|
->with(['apps:id,name', 'users:id,name'])
|
|
->orderBy('id')
|
|
->paginate();
|
|
|
|
return RoleData::collect($roles, PaginatedDataCollection::class);
|
|
}
|
|
}
|