Files
Gnuboard7/app/Repositories/RoleRepository.php
T
HeuJung b10e89bef0 fix(core,board,ecommerce,page,gdpr,ckeditor5,kginicis,admin_basic,basic): 목록 조회·검증 계층 정비 및 감사 지적 전건 처리
목록 조회 성능 축(깊은 OFFSET·정렬·색인)과 그 검증 계층에서 계획서 전수검수와 3회에 걸친
감사가 지적한 항목을 처리했다. 세부 경위는 의 각 회차 문서에 있다.

검증 계층 — 컨트롤러가 base Request 를 직접 주입받던 확장 13곳을 전용 FormRequest 로 옮겼다.
옮기면서 기존 동작 계약은 그대로 두었다: 상한 초과 limit 을 거부하지 않고 상한까지 반환하던
공개 API, per_page 를 범위로 조정하던 관리자 목록, 미지원 period 를 year 로 해석하던 인기글
목록 모두 종전과 같은 응답을 낸다. 상한/폴백을 rules 로 승격시키면 200 이던 응답이 422 가
되어 기존 링크가 깨지므로, 규칙은 타입만 닫고 클램프·폴백은 접근자가 맡는다. period 는
접근자가 닫힌 집합만 반환해 캐시 키 공간도 함께 닫힌다.

ckeditor5 이미지 업로드만 ResponseHelper 봉투를 쓰지 않는다. 응답을 파싱하는 주체가 CDN 으로
로드되는 상위 CKEditor5 43.3.1 의 SimpleUploadAdapter 라 규약을 바꿀 수 없어, 각 응답 지점에
사유를 명시한 면제를 부착하고 근거를 API 문서에 남겼다.

하네스 — 룰 5개의 대상 경로 패턴이 매처와 맞지 않아 번들 확장 컨트롤러가 검사 대상에서
통째로 빠져 있었다. 패턴을 고치자 확장 위반 17건이 드러나 전건 처리했다. severity 오타가
요약 집계 양쪽에 안 잡혀 "0 error" 로 보고되던 문제도 런너 사전 검증으로 막았다.

정렬 게이트 대조 하네스는 관계 정렬 변형만 쓰는 저장소를 탐지하지 못한 채 통과시키고 있었다.
탐지·제외·인자 파싱을 함께 고치고 단위 테스트를 신설했다.
2026-08-02 15:29:29 +09:00

240 lines
7.5 KiB
PHP

<?php
namespace App\Repositories;
use App\Contracts\Repositories\RoleRepositoryInterface;
use App\Enums\ExtensionOwnerType;
use App\Models\Role;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
class RoleRepository implements RoleRepositoryInterface
{
/**
* 모든 역할을 조회합니다.
*
* @return Collection 역할 컬렉션
*/
public function getAll(): Collection
{
return Role::with(['permissions'])
->orderBy('id')
->get();
}
/**
* 활성화된 역할들만 조회합니다.
*
* @return Collection 활성화된 역할 컬렉션
*/
public function getActiveRoles(): Collection
{
return Role::where('is_active', true)
->orderBy('id')
->get();
}
/**
* ID로 역할을 찾습니다.
*
* @param int $id 역할 ID
* @return Role|null 찾은 역할 모델 또는 null
*/
public function findById(int $id): ?Role
{
return Role::with(['permissions'])->find($id);
}
/**
* 식별자로 역할을 찾습니다.
*
* @param string $identifier 역할 식별자
* @return Role|null 찾은 역할 모델 또는 null
*/
public function findByIdentifier(string $identifier): ?Role
{
return Role::where('identifier', $identifier)->first();
}
/**
* 식별자로 역할에 소속된 사용자들을 조회합니다.
*
* 역할이 없거나 소속 사용자가 없으면 빈 컬렉션을 반환합니다.
*
* @param string $identifier 역할 식별자
* @return Collection 역할 소속 사용자 컬렉션
*/
public function getUsersByIdentifier(string $identifier): Collection
{
$role = Role::where('identifier', $identifier)->first();
return $role ? $role->users()->get() : new Collection;
}
/**
* 새로운 역할을 생성합니다.
*
* @param array $data 역할 생성 데이터
* @return Role 생성된 역할 모델
*/
public function create(array $data): Role
{
return Role::create($data);
}
/**
* 역할을 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return Role 생성 또는 업데이트된 역할 모델
*/
public function updateOrCreate(array $attributes, array $values): Role
{
return Role::updateOrCreate($attributes, $values);
}
/**
* 기존 역할을 업데이트합니다.
*
* @param Role $role 업데이트할 역할 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Role $role, array $data): bool
{
return $role->update($data);
}
/**
* 역할을 삭제합니다.
*
* @param Role $role 삭제할 역할 모델
* @return bool 삭제 성공 여부
*/
public function delete(Role $role): bool
{
return $role->delete();
}
/**
* 확장이 소유한 역할을 식별자로 찾습니다.
*
* @param string $identifier 역할 식별자
* @param ExtensionOwnerType $extensionType 확장 타입
* @param string $extensionIdentifier 확장 식별자
* @return Role|null 찾은 역할 모델 또는 null
*/
public function findExtensionRoleByIdentifier(string $identifier, ExtensionOwnerType $extensionType, string $extensionIdentifier): ?Role
{
return Role::where('identifier', $identifier)
->where('extension_type', $extensionType)
->where('extension_identifier', $extensionIdentifier)
->first();
}
/**
* 확장이 소유한 모든 역할을 조회합니다.
*
* @param ExtensionOwnerType $extensionType 확장 타입
* @param string $extensionIdentifier 확장 식별자
* @return Collection 해당 확장 소유 역할 컬렉션
*/
public function getByExtension(ExtensionOwnerType $extensionType, string $extensionIdentifier): Collection
{
return Role::where('extension_type', $extensionType)
->where('extension_identifier', $extensionIdentifier)
->get();
}
/**
* 역할에 권한을 할당합니다.
*
* 기존 권한을 유지하면서 새 권한만 추가합니다.
*
* @param Role $role 역할 모델
* @param int $permissionId 권한 ID
* @param array $pivotData 피벗 테이블에 저장할 추가 데이터
*/
public function attachPermission(Role $role, int $permissionId, array $pivotData = []): void
{
$role->permissions()->syncWithoutDetaching([
$permissionId => $pivotData,
]);
}
/**
* 역할에서 권한을 해제합니다.
*
* @param Role $role 역할 모델
* @param int $permissionId 권한 ID
* @return int 해제된 권한 수
*/
public function detachPermission(Role $role, int $permissionId): int
{
return $role->permissions()->detach($permissionId);
}
/**
* 역할의 모든 권한을 해제합니다.
*
* @param Role $role 역할 모델
* @return int 해제된 권한 수
*/
public function detachAllPermissions(Role $role): int
{
return $role->permissions()->detach();
}
/**
* 역할 목록을 페이지네이션하여 조회합니다.
*
* @param array $filters 필터 조건
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator 페이지네이션된 역할 목록
*/
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator
{
$query = Role::query()
->withCount('users')
->with('permissions');
// 검색 필터
if (! empty($filters['search'])) {
$search = $filters['search'];
$query->where(function ($q) use ($search) {
$q->where('identifier', 'like', "%{$search}%")
->orWhere('name->ko', 'like', "%{$search}%")
->orWhere('name->en', 'like', "%{$search}%");
});
}
// 활성화 상태 필터
if (isset($filters['is_active'])) {
$query->where('is_active', $filters['is_active']);
}
// 정렬 (코어/확장 소유 역할 먼저, 그 다음 사용자 생성 역할)
// 정렬 마지막의 기본키는 전순서 보장용이다. 시더가 일괄 생성한 역할은 created_at 이
// 한 타임스탬프에 몰려 있어(실측: 한 값에 최대 10행) 키가 없으면 동률 구간의 순서가
// 페이지마다 달라지고, 인접 페이지가 같은 역할을 중복 노출하면서 다른 역할을 누락한다.
$query->orderByRaw('CASE WHEN extension_type IS NOT NULL THEN 0 ELSE 1 END')
->orderBy('created_at', 'desc')
->orderBy('id', 'desc');
// audit:allow repository-paginate-column-pruning reason: 역할 정의 테이블 — 행 수가 운영상 고정(수십 건)이고 넓은 컬럼이 없다
return $query->paginate($perPage);
}
/**
* 역할에 할당된 권한 개수를 반환합니다.
*
* @param Role $role 역할 모델
* @return int 권한 개수
*/
public function getPermissionCount(Role $role): int
{
return $role->permissions()->count();
}
}