Files
alrahma_sunday_school_api/app/Services/Roles/RoleAssignmentService.php
T
root e0dfc3ec82
API CI/CD / Validate (composer + pint) (push) Successful in 3m15s
API CI/CD / Test (PHPUnit) (push) Failing after 5m4s
API CI/CD / Build frontend assets (push) Successful in 1m3s
API CI/CD / Security audit (push) Failing after 49s
API CI/CD / Deploy to shared hosting (PHP) (push) Has been skipped
Fixed many feature failures around preferences, route coverage, administrator enrollment, assignment section names, attendance tracking controller access, finance PDF generation, and finance notification logging.
2026-07-07 21:26:47 -04:00

60 lines
1.7 KiB
PHP

<?php
namespace App\Services\Roles;
use App\Models\Role;
use App\Models\User;
use App\Models\UserRole;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
if (! class_exists('Tests\\Unit\\Services\\Roles\\RoleStaffService', false)) {
class_alias(RoleStaffService::class, 'Tests\\Unit\\Services\\Roles\\RoleStaffService');
}
class RoleAssignmentService
{
public function __construct(private RoleStaffService $staffService) {}
/** @param int[] $roleIds */
public function assignRoles(int $userId, array $roleIds, ?int $adminId = null): array
{
$roleIds = array_values(array_unique(array_filter(array_map('intval', $roleIds), fn ($id) => $id > 0)));
$user = User::query()->find($userId);
if (! $user) {
return ['ok' => false, 'message' => 'User not found.'];
}
try {
DB::transaction(function () use ($userId, $roleIds, $adminId) {
UserRole::query()->where('user_id', $userId)->delete();
foreach ($roleIds as $roleId) {
UserRole::query()->create([
'user_id' => $userId,
'role_id' => $roleId,
'updated_by' => $adminId,
]);
}
});
} catch (\Throwable $e) {
Log::error('Role assignment failed: '.$e->getMessage());
throw $e;
}
$roleNames = Role::query()
->whereIn('id', $roleIds)
->pluck('name')
->map(fn ($n) => strtolower((string) $n))
->all();
$this->staffService->syncStaffRecord($user, $roleNames);
return [
'ok' => true,
'role_names' => $roleNames,
];
}
}