Files
sam-api/app/Services/Authz/RoleService.php

140 lines
3.8 KiB
PHP
Raw Normal View History

<?php
namespace App\Services\Authz;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;
class RoleService
{
protected static string $guard = 'api';
/** 목록 */
public static function index(array $params = [])
{
$tenantId = (int) app('tenant_id');
$page = (int) ($params['page'] ?? 1);
$size = (int) ($params['size'] ?? 10);
$q = trim((string) ($params['q'] ?? ''));
$query = Role::query()
->where('tenant_id', $tenantId)
->where('guard_name', self::$guard);
if ($q !== '') {
$query->where(function ($w) use ($q) {
$w->where('name', 'like', "%{$q}%")
->orWhere('description', 'like', "%{$q}%");
});
}
$list = $query->orderByDesc('id')
->paginate($size, ['*'], 'page', $page);
return $list;
}
/** 생성 */
public static function store(array $params = [])
{
$tenantId = (int) app('tenant_id');
$v = Validator::make($params, [
'name' => [
'required', 'string', 'max:100',
Rule::unique('roles', 'name')->where(fn ($q) => $q
->where('tenant_id', $tenantId)
->where('guard_name', self::$guard)),
],
'description' => 'nullable|string|max:255',
]);
if ($v->fails()) {
return ['error' => $v->errors()->first(), 'code' => 422];
}
// Spatie 팀(테넌트) 컨텍스트
app(PermissionRegistrar::class)->setPermissionsTeamId($tenantId);
$role = Role::create([
'tenant_id' => $tenantId,
'guard_name' => self::$guard,
'name' => $v->validated()['name'],
'description' => $params['description'] ?? null,
]);
return $role;
}
/** 단건 */
public static function show(int $id)
{
$tenantId = (int) app('tenant_id');
$role = Role::where('tenant_id', $tenantId)
->where('guard_name', self::$guard)
->find($id);
if (! $role) {
return ['error' => '역할을 찾을 수 없습니다.', 'code' => 404];
}
return $role;
}
/** 수정 */
public static function update(int $id, array $params = [])
{
$tenantId = (int) app('tenant_id');
$role = Role::where('tenant_id', $tenantId)
->where('guard_name', self::$guard)
->find($id);
if (! $role) {
return ['error' => '역할을 찾을 수 없습니다.', 'code' => 404];
}
$v = Validator::make($params, [
'name' => [
'sometimes', 'string', 'max:100',
Rule::unique('roles', 'name')
->where(fn ($q) => $q->where('tenant_id', $tenantId)->where('guard_name', self::$guard))
->ignore($role->id),
],
'description' => 'sometimes|nullable|string|max:255',
]);
if ($v->fails()) {
return ['error' => $v->errors()->first(), 'code' => 422];
}
$role->fill($v->validated())->save();
return $role->fresh();
}
/** 삭제 (하드삭제) */
public static function destroy(int $id)
{
$tenantId = (int) app('tenant_id');
$role = Role::where('tenant_id', $tenantId)
->where('guard_name', self::$guard)
->find($id);
if (! $role) {
return ['error' => '역할을 찾을 수 없습니다.', 'code' => 404];
}
DB::transaction(function () use ($role) {
$role->delete(); // Spatie Role 기본: soft delete 없음
});
return 'success';
}
}