목록이 뒤쪽 페이지로 갈수록 느려지는 원인은 건너뛰는 행의 넓은 컬럼까지 읽는 것이었다. 지연 조인(inner 는 키 컬럼만, outer 는 이번 페이지 행만 전체 컬럼)과 정렬 컬럼 해석을 코어 공통 트레이트로 두고 코어 8 + 확장 6 저장소에 적용했다. 감사 지적 처리: - 그룹 쿼리의 총 건수 오산 — count 는 groupBy 를 벗기지 않아 첫 그룹의 행 수를 총 건수로 돌려준다. getCountForPagination 으로 교정. - audit 전수 스캔이 버퍼 한계로 한 번도 동작하지 않던 결함과, 확장 경로를 놓치던 정규식 5건을 함께 고쳤다. 그동안 번들 확장의 위반이 보이지 않았다. raw 20건을 빌더 표현으로 치환하고 하드코딩 테이블명 16건을 모델 유래로 바꿨다. 이 과정에서 마이페이지 「내가 댓글 단 글」 검색이 조인 별칭 충돌로 SQL 오류를 내던 결함이 해소됐다. 재발 차단용 룰 2종을 신설하고, 컬럼 프루닝 룰을 error 로 승격했다 (전역 위반 0건 — warning 으로 두면 "0 error" 판정을 통과하며 무음으로 재누적된다). 정렬 허용 목록은 FormRequest 게이트를 덮어야 한다. 좁으면 검증을 통과한 정렬이 422 도 로그도 없이 기본값으로 되돌아간다(스케줄 실행 이력의 종료시각·소요시간 정렬이 그랬다). 호출처를 스캔해 매핑 완전성까지 검사하는 계약 테스트로 전수 강제한다. 해외 배송지 결함도 함께 고쳤다 — 조회는 city/state/postal_code 로 내려주고 폼은 intl_* 로 제출하는 비대칭 때문에, 수정 시 입력칸이 비어 보이고 저장하면 기존 값이 유실됐다. 쿠폰 수정의 유효기간 미검증과 1인당 사용 제한 부분 수정 차단도 함께 수정.
300 lines
9.3 KiB
PHP
300 lines
9.3 KiB
PHP
<?php
|
|
|
|
namespace App\Repositories;
|
|
|
|
use App\Contracts\Repositories\ScheduleRepositoryInterface;
|
|
use App\Enums\ScheduleFrequency;
|
|
use App\Enums\ScheduleResultStatus;
|
|
use App\Enums\ScheduleType;
|
|
use App\Helpers\PermissionHelper;
|
|
use App\Models\Schedule;
|
|
use App\Repositories\Concerns\HasMultipleSearchFilters;
|
|
use App\Repositories\Concerns\ResolvesSortSpec;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
|
class ScheduleRepository implements ScheduleRepositoryInterface
|
|
{
|
|
use HasMultipleSearchFilters;
|
|
use ResolvesSortSpec;
|
|
|
|
/**
|
|
* 검색 가능한 필드 목록
|
|
*/
|
|
private const SEARCHABLE_FIELDS = ['name', 'description', 'command'];
|
|
|
|
/**
|
|
* 허용 정렬 컬럼 (ScheduleListRequest 와 동일 집합)
|
|
*/
|
|
private const SORTABLE_COLUMNS = [
|
|
'created_at',
|
|
'name',
|
|
'next_run_at',
|
|
'last_run_at',
|
|
'is_active',
|
|
'last_result',
|
|
];
|
|
|
|
/**
|
|
* ID로 스케줄을 찾습니다.
|
|
*
|
|
* @param int $id 스케줄 ID
|
|
* @return Schedule|null 찾은 스케줄 모델 또는 null
|
|
*/
|
|
public function findById(int $id): ?Schedule
|
|
{
|
|
return Schedule::with('creator')->find($id);
|
|
}
|
|
|
|
/**
|
|
* 새로운 스케줄을 생성합니다.
|
|
*
|
|
* @param array $data 스케줄 생성 데이터
|
|
* @return Schedule 생성된 스케줄 모델
|
|
*/
|
|
public function create(array $data): Schedule
|
|
{
|
|
return Schedule::create($data);
|
|
}
|
|
|
|
/**
|
|
* 기존 스케줄을 업데이트합니다.
|
|
*
|
|
* @param Schedule $schedule 업데이트할 스케줄 모델
|
|
* @param array $data 업데이트할 데이터
|
|
* @return bool 업데이트 성공 여부
|
|
*/
|
|
public function update(Schedule $schedule, array $data): bool
|
|
{
|
|
return $schedule->update($data);
|
|
}
|
|
|
|
/**
|
|
* 스케줄을 삭제합니다.
|
|
*
|
|
* @param Schedule $schedule 삭제할 스케줄 모델
|
|
* @return bool 삭제 성공 여부
|
|
*/
|
|
public function delete(Schedule $schedule): bool
|
|
{
|
|
return $schedule->delete();
|
|
}
|
|
|
|
/**
|
|
* 모든 스케줄을 조회합니다.
|
|
*
|
|
* @return Collection 스케줄 컬렉션
|
|
*/
|
|
public function getAll(): Collection
|
|
{
|
|
return Schedule::with('creator')->get();
|
|
}
|
|
|
|
/**
|
|
* 필터링 및 페이지네이션이 적용된 스케줄 목록을 조회합니다.
|
|
*
|
|
* @param array $filters 필터 조건 배열
|
|
* @return LengthAwarePaginator 페이지네이션된 스케줄 목록
|
|
*/
|
|
public function getPaginatedSchedules(array $filters = []): LengthAwarePaginator
|
|
{
|
|
$query = Schedule::query()->with('creator');
|
|
|
|
// 권한 스코프 필터링
|
|
PermissionHelper::applyPermissionScope($query, 'core.schedules.read');
|
|
|
|
// 필터 조건 적용
|
|
$this->applyFilters($query, $filters);
|
|
|
|
// 정렬 적용 (허용 컬럼 화이트리스트로 해석)
|
|
foreach ($this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'created_at') as $sort) {
|
|
$query->orderBy($sort['column'], $sort['direction']);
|
|
}
|
|
|
|
// 페이지네이션 적용
|
|
$perPage = $filters['per_page'] ?? 15;
|
|
|
|
// audit:allow repository-paginate-column-pruning reason: 스케줄 정의 테이블 — 등록된 스케줄 수만큼만 존재하고 넓은 컬럼이 없다
|
|
return $query->paginate($perPage);
|
|
}
|
|
|
|
/**
|
|
* 쿼리에 필터 조건을 적용합니다.
|
|
*
|
|
* @param Builder $query Eloquent 쿼리 빌더
|
|
* @param array $filters 적용할 필터 조건 배열
|
|
* @return void
|
|
*/
|
|
private function applyFilters(Builder $query, array $filters): void
|
|
{
|
|
// 다중 검색 조건 적용
|
|
if (! empty($filters['filters']) && is_array($filters['filters'])) {
|
|
$this->applyMultipleSearchFilters($query, $filters['filters'], self::SEARCHABLE_FIELDS);
|
|
}
|
|
|
|
// 타입 필터
|
|
if (! empty($filters['type'])) {
|
|
$type = ScheduleType::tryFrom($filters['type']);
|
|
if ($type) {
|
|
$query->where('type', $type);
|
|
}
|
|
}
|
|
|
|
// 주기 필터
|
|
if (! empty($filters['frequency'])) {
|
|
$frequency = ScheduleFrequency::tryFrom($filters['frequency']);
|
|
if ($frequency) {
|
|
$query->where('frequency', $frequency);
|
|
}
|
|
}
|
|
|
|
// 상태 필터
|
|
if (! empty($filters['status'])) {
|
|
if ($filters['status'] === 'active') {
|
|
$query->where('is_active', true);
|
|
} elseif ($filters['status'] === 'inactive') {
|
|
$query->where('is_active', false);
|
|
}
|
|
}
|
|
|
|
// 마지막 실행 결과 필터
|
|
if (! empty($filters['last_result'])) {
|
|
$result = ScheduleResultStatus::tryFrom($filters['last_result']);
|
|
if ($result) {
|
|
$query->where('last_result', $result);
|
|
}
|
|
}
|
|
|
|
// 중복 실행 방지 필터
|
|
if (isset($filters['without_overlapping']) && $filters['without_overlapping'] !== '') {
|
|
$query->where('without_overlapping', (bool) $filters['without_overlapping']);
|
|
}
|
|
|
|
// 점검 모드 실행 필터
|
|
if (isset($filters['run_in_maintenance']) && $filters['run_in_maintenance'] !== '') {
|
|
$query->where('run_in_maintenance', (bool) $filters['run_in_maintenance']);
|
|
}
|
|
|
|
// 확장 타입 필터
|
|
if (! empty($filters['extension_type'])) {
|
|
$query->where('extension_type', $filters['extension_type']);
|
|
|
|
if (! empty($filters['extension_identifier'])) {
|
|
$query->where('extension_identifier', $filters['extension_identifier']);
|
|
}
|
|
}
|
|
|
|
// 날짜 필터
|
|
$this->applyDateFilters($query, $filters);
|
|
}
|
|
|
|
/**
|
|
* 날짜 필터를 적용합니다.
|
|
*
|
|
* @param Builder $query Eloquent 쿼리 빌더
|
|
* @param array $filters 필터 조건 배열
|
|
* @return void
|
|
*/
|
|
private function applyDateFilters(Builder $query, array $filters): void
|
|
{
|
|
if (! empty($filters['created_from'])) {
|
|
$query->whereDate('created_at', '>=', $filters['created_from']);
|
|
}
|
|
|
|
if (! empty($filters['created_to'])) {
|
|
$query->whereDate('created_at', '<=', $filters['created_to']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 스케줄 관련 통계 정보를 조회합니다.
|
|
*
|
|
* @return array 스케줄 통계 데이터 배열
|
|
*/
|
|
public function getStatistics(): array
|
|
{
|
|
return [
|
|
'total' => Schedule::count(),
|
|
'active' => Schedule::where('is_active', true)->count(),
|
|
'inactive' => Schedule::where('is_active', false)->count(),
|
|
'success' => Schedule::where('last_result', ScheduleResultStatus::Success)->count(),
|
|
'failed' => Schedule::where('last_result', ScheduleResultStatus::Failed)->count(),
|
|
'running' => Schedule::where('last_result', ScheduleResultStatus::Running)->count(),
|
|
'never_run' => Schedule::where('last_result', ScheduleResultStatus::Never)->count(),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 활성화된 스케줄들을 조회합니다.
|
|
*
|
|
* @return Collection 활성화된 스케줄 컬렉션
|
|
*/
|
|
public function getActiveSchedules(): Collection
|
|
{
|
|
return Schedule::active()->get();
|
|
}
|
|
|
|
/**
|
|
* 실행 대기 중인 스케줄들을 조회합니다.
|
|
*
|
|
* @return Collection 실행 대기 중인 스케줄 컬렉션
|
|
*/
|
|
public function getDueSchedules(): Collection
|
|
{
|
|
return Schedule::due()->get();
|
|
}
|
|
|
|
/**
|
|
* 여러 스케줄의 상태를 일괄 업데이트합니다.
|
|
*
|
|
* @param array $ids 스케줄 ID 배열
|
|
* @param bool $isActive 활성화 여부
|
|
* @return int 업데이트된 레코드 수
|
|
*/
|
|
public function bulkUpdateStatus(array $ids, bool $isActive): int
|
|
{
|
|
return Schedule::whereIn('id', $ids)->update(['is_active' => $isActive]);
|
|
}
|
|
|
|
/**
|
|
* 여러 스케줄을 일괄 삭제합니다.
|
|
*
|
|
* @param array $ids 스케줄 ID 배열
|
|
* @return int 삭제된 레코드 수
|
|
*/
|
|
public function bulkDelete(array $ids): int
|
|
{
|
|
return Schedule::whereIn('id', $ids)->delete();
|
|
}
|
|
|
|
/**
|
|
* 스케줄을 복제합니다.
|
|
*
|
|
* @param Schedule $schedule 복제할 스케줄
|
|
* @return Schedule 복제된 스케줄
|
|
*/
|
|
public function duplicate(Schedule $schedule): Schedule
|
|
{
|
|
$newSchedule = $schedule->replicate();
|
|
$newSchedule->name = $schedule->name.' ('.__('schedule.copy').')';
|
|
$newSchedule->is_active = false;
|
|
$newSchedule->last_result = ScheduleResultStatus::Never;
|
|
$newSchedule->last_run_at = null;
|
|
$newSchedule->save();
|
|
|
|
return $newSchedule;
|
|
}
|
|
|
|
/**
|
|
* ID 목록으로 스케줄들을 조회하고 ID 키 맵으로 반환합니다.
|
|
*
|
|
* @param array<int, int> $ids 스케줄 ID 목록
|
|
* @return Collection<int, Schedule> id => Schedule 매핑
|
|
*/
|
|
public function findManyByIdsKeyed(array $ids): Collection
|
|
{
|
|
return Schedule::whereIn('id', $ids)->get()->keyBy('id');
|
|
}
|
|
}
|