Files
Gnuboard7/app/Repositories/ScheduleHistoryRepository.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

171 lines
5.9 KiB
PHP

<?php
namespace App\Repositories;
use App\Contracts\Repositories\ScheduleHistoryRepositoryInterface;
use App\Models\ScheduleHistory;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Repositories\Concerns\ResolvesSortSpec;
use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
{
use PaginatesWithDeferredJoin;
use ResolvesSortSpec;
/**
* ID로 실행 이력을 찾습니다.
*
* @param int $id 이력 ID
* @return ScheduleHistory|null 찾은 이력 모델 또는 null
*/
public function findById(int $id): ?ScheduleHistory
{
return ScheduleHistory::with(['schedule', 'triggeredBy'])->find($id);
}
/**
* 새로운 실행 이력을 생성합니다.
*
* @param array $data 이력 생성 데이터
* @return ScheduleHistory 생성된 이력 모델
*/
public function create(array $data): ScheduleHistory
{
return ScheduleHistory::create($data);
}
/**
* 기존 실행 이력을 업데이트합니다.
*
* @param ScheduleHistory $history 업데이트할 이력 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(ScheduleHistory $history, array $data): bool
{
return $history->update($data);
}
/**
* 실행 이력을 삭제합니다.
*
* @param ScheduleHistory $history 삭제할 이력 모델
* @return bool 삭제 성공 여부
*/
public function delete(ScheduleHistory $history): bool
{
return $history->delete();
}
/**
* 특정 스케줄의 실행 이력을 페이지네이션하여 조회합니다.
*
* @param int $scheduleId 스케줄 ID
* @param array $filters 필터 조건 배열
* @return LengthAwarePaginator 페이지네이션된 이력 목록
*/
public function getPaginatedByScheduleId(int $scheduleId, array $filters = []): LengthAwarePaginator
{
// 관계는 쿼리에 미리 붙이지 않는다 — 지연 조인 트레이트가 inner/outer 양쪽에서
// setEagerLoads([]) 로 지우므로, 여기서 with() 하면 outer 에서도 사라져
// ScheduleHistoryResource 의 whenLoaded('triggeredBy') 가 항상 비게 된다.
// 로드는 relations: 인자로 넘긴다.
$query = ScheduleHistory::query()
->where('schedule_id', $scheduleId);
// 상태 필터
if (! empty($filters['status'])) {
$query->where('status', $filters['status']);
}
// 트리거 유형 필터
if (! empty($filters['trigger_type'])) {
$query->where('trigger_type', $filters['trigger_type']);
}
// 기간 필터 — whereDate 는 컬럼에 DATE() 를 씌워 인덱스를 못 쓰게 만든다.
// 같은 결과를 내는 범위 조건으로 바꿔 started_at 인덱스를 살린다
// (종료일은 그날 23:59:59.999999 까지 포함해야 whereDate 와 동일한 경계를 갖는다).
if (! empty($filters['started_from'])) {
$query->where('started_at', '>=', Carbon::parse($filters['started_from'])->startOfDay());
}
if (! empty($filters['started_to'])) {
$query->where('started_at', '<=', Carbon::parse($filters['started_to'])->endOfDay());
}
// 정렬 — 요청 값은 허용 목록으로만 해석한다.
// 허용 집합은 ScheduleHistoryListRequest 의 `in:` 규칙과 동일해야 한다. 저장소 목록이
// 그보다 좁으면 게이트를 통과한 정렬이 조용히 기본값으로 되돌아간다 (종료시각/소요시간).
$sort = $this->resolveSortSpec(
$filters,
['started_at', 'ended_at', 'duration', 'status'],
'started_at'
);
$perPage = (int) ($filters['per_page'] ?? 15);
// 실행 이력은 계속 쌓이며 출력/에러 메시지를 그대로 노출하므로, 컬럼은 좁히지 않고
// 지연 조인으로 넓은 컬럼을 읽는 행 수만 이번 페이지 분량으로 고정한다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: $sort,
perPage: $perPage,
relations: ['triggeredBy'],
);
}
/**
* 특정 스케줄의 최근 실행 이력을 조회합니다.
*
* @param int $scheduleId 스케줄 ID
* @param int $limit 조회 개수
* @return Collection 최근 이력 컬렉션
*/
public function getRecentByScheduleId(int $scheduleId, int $limit = 10): Collection
{
return ScheduleHistory::with('triggeredBy')
->where('schedule_id', $scheduleId)
->orderByDesc('started_at')
->limit($limit)
->get();
}
/**
* 여러 이력을 일괄 삭제합니다.
*
* @param array $ids 이력 ID 배열
* @return int 삭제된 레코드 수
*/
public function bulkDelete(array $ids): int
{
return ScheduleHistory::whereIn('id', $ids)->delete();
}
/**
* 특정 스케줄의 모든 이력을 삭제합니다.
*
* @param int $scheduleId 스케줄 ID
* @return int 삭제된 레코드 수
*/
public function deleteByScheduleId(int $scheduleId): int
{
return ScheduleHistory::where('schedule_id', $scheduleId)->delete();
}
/**
* 특정 기간 이전의 이력을 삭제합니다.
*
* @param int $days 보관 기간 (일)
* @return int 삭제된 레코드 수
*/
public function deleteOlderThan(int $days): int
{
return ScheduleHistory::where('started_at', '<', now()->subDays($days))->delete();
}
}