fix(core,board,ecommerce,page,gdpr,basic): 깊은 OFFSET 목록 조회 개선 및 raw/테이블명 전수 정리

목록이 뒤쪽 페이지로 갈수록 느려지는 원인은 건너뛰는 행의 넓은 컬럼까지 읽는 것이었다.
지연 조인(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인당 사용 제한 부분 수정 차단도 함께 수정.
This commit is contained in:
HeuJung committed 2026-08-02 14:36:37 +09:00
1 parent 95ffdf9eed
commit be9befe023
81 files changed
+5799 -457

No files matched your search

@@ -0,0 +1,556 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
/**
* 깊은 OFFSET 페이지네이션 비용 계측 커맨드
*
* 목록 조회는 OFFSET 이 커질수록 느려지는데, 그 원인이 "건너뛸 행의 넓은 컬럼까지 읽기"인지
* 확인하려면 같은 필터·정렬로 (1) 실제 목록 컬럼과 (2) 키 컬럼만 조회한 비용을 나란히 재야 한다.
* 본 커맨드는 그 두 축을 같은 조건에서 측정해 표로 출력한다.
*
* tinker 스크립트 대신 커맨드로 만든 이유: tinker 는 REPL 이라 스크립트 실행 후에도 STDIN 을
* 기다려 출력이 유실된다.
*/
class BenchPaginationCommand extends Command
{
protected $signature = 'g7:bench:pagination
{--table=board_posts : 계측 대상 프로파일 키}
{--offsets=0,20000,50000,99980 : 측정할 OFFSET 목록 (쉼표 구분)}
{--runs=3 : OFFSET 당 측정 횟수 (첫 회는 버림)}
{--seed=0 : 계측 전 합성 행 시딩 건수 (0 = 시딩 안 함)}
{--database= : 계측에 사용할 데이터베이스명 (미지정 시 기본 연결. 개발 DB 오염 방지용)}
{--fresh : 시딩 전에 대상 테이블을 비움 (운영 환경에서는 거부)}
{--explain : 각 OFFSET 의 실행 계획도 함께 수집}
{--json : 기계 판독용 JSON 출력}
{--list-profiles : 등록된 프로파일 목록 출력}';
protected $description = '깊은 OFFSET 목록 조회 비용을 목록 컬럼 / 키 컬럼 두 축으로 계측합니다';
/**
* 계측 프로파일 정의
*
* columns 는 해당 목록이 실제로 select 하는 컬럼이다. 스키마에 없는 컬럼은 실행 시 걸러낸다
* (확장 버전에 따라 컬럼 구성이 달라도 커맨드가 죽지 않도록).
*
* @return array<string, array{table: string, columns: array<int, string>, order: array<int, array{0: string, 1: string}>, soft_delete: bool}>
*/
private function profiles(): array
{
return [
'board_posts' => [
'table' => 'board_posts',
'columns' => ['id', 'board_id', 'title', 'author_name', 'view_count', 'is_notice', 'created_at'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
// 실제 목록은 게시판 하나를 조회한다. 필터 없이 재면 인덱스 선택이 달라져
// 화면에서 일어나는 일과 다른 것을 재게 된다.
'filters' => ['board_id' => 1],
'seed_overrides' => ['board_id' => 1, 'is_notice' => 0],
],
'orders' => [
'table' => 'ecommerce_orders',
'columns' => ['id', 'user_id', 'order_number', 'order_status', 'order_device', 'is_first_order', 'currency', 'currency_snapshot', 'total_amount', 'total_shipping_amount', 'total_paid_amount', 'total_cancelled_amount', 'total_refunded_amount', 'total_points_used_amount', 'total_earned_points_amount', 'mc_total_amount', 'mc_total_shipping_amount', 'ordered_at', 'created_at', 'updated_at', 'deleted_at'],
'order' => [['ordered_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
],
// 아래 두 목록은 응답 계약상 넓은 컬럼(changes/properties, body)을 그대로 노출하므로
// 컬럼 프루닝이 불가하다. 지연 조인만 적용했고, 계측 축도 select * vs select id 다.
'activity_logs' => [
'table' => 'activity_logs',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => false,
],
'notification_logs' => [
'table' => 'notification_logs',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => false,
],
'users' => [
'table' => 'users',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
],
'reports' => [
'table' => 'boards_reports',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
],
'coupon_issues' => [
'table' => 'ecommerce_promotion_coupon_issues',
'columns' => ['*'],
'order' => [['issued_at', 'desc'], ['id', 'desc']],
'soft_delete' => false,
],
'products' => [
'table' => 'ecommerce_products',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
],
'product_inquiries' => [
'table' => 'ecommerce_product_inquiries',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
],
'product_reviews' => [
'table' => 'ecommerce_product_reviews',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
],
'pages' => [
'table' => 'pages',
'columns' => ['*'],
'order' => [['created_at', 'desc'], ['id', 'desc']],
'soft_delete' => true,
],
'extra_fee_templates' => [
'table' => 'ecommerce_shipping_policy_extra_fee_templates',
'columns' => ['*'],
'order' => [['zipcode', 'asc'], ['id', 'asc']],
'soft_delete' => false,
],
];
}
/**
* 커맨드를 실행합니다.
*
* @return int 종료 코드
*/
public function handle(): int
{
$profiles = $this->profiles();
if ($this->option('list-profiles')) {
foreach ($profiles as $key => $profile) {
$this->line(sprintf('%-20s %s', $key, $profile['table']));
}
return self::SUCCESS;
}
$key = (string) $this->option('table');
if (! isset($profiles[$key])) {
$this->error("등록되지 않은 프로파일: {$key} (--list-profiles 로 목록 확인)");
return self::FAILURE;
}
$profile = $profiles[$key];
// 계측은 대량 시딩을 동반하므로 개발 DB 대신 폐기 가능한 DB 를 지정할 수 있어야 한다.
// config 가 캐시된 환경에서는 .env / --env 로 연결을 바꿀 수 없어 런타임 치환이 유일한 수단이다.
$database = (string) $this->option('database');
if ($database !== '') {
$connection = config('database.default');
config([
"database.connections.{$connection}.database" => $database,
"database.connections.{$connection}.write.database" => $database,
"database.connections.{$connection}.read.database" => $database,
]);
DB::purge($connection);
}
if (! Schema::hasTable($profile['table'])) {
$this->error("테이블이 없습니다: {$profile['table']} (해당 확장이 설치되어 있는지 확인)");
return self::FAILURE;
}
// 계측 결과가 환경에 좌우되므로 실행 환경을 먼저 드러낸다
$this->line(sprintf(
'환경: APP_ENV=%s / DB=%s / config:cache=%s',
config('app.env'),
config('database.default'),
app()->configurationIsCached() ? 'on' : 'off'
));
if ($this->option('fresh')) {
if (app()->environment('production')) {
$this->error('운영 환경에서는 --fresh 를 사용할 수 없습니다.');
return self::FAILURE;
}
// 다른 테이블이 FK 로 참조하면 TRUNCATE 가 거부되므로 제약을 잠시 내린다
Schema::withoutForeignKeyConstraints(function () use ($profile) {
DB::table($profile['table'])->truncate();
});
$this->warn("비움: {$profile['table']}");
}
$seed = (int) $this->option('seed');
if ($seed > 0) {
$this->seedRows($profile['table'], $seed, $profile['seed_overrides'] ?? []);
}
$columns = $this->existingColumns($profile['table'], $profile['columns']);
$order = $this->existingOrder($profile['table'], $profile['order']);
$offsets = $this->parseOffsets();
$runs = max(1, (int) $this->option('runs'));
$rows = [];
foreach ($offsets as $offset) {
// 세 축: 컬럼 인자를 생략했을 때(=select *) / 목록 컬럼만 / 키 컬럼만.
// 첫 축이 프루닝 이전 상태, 셋째 축이 지연 조인의 inner 에 해당한다.
$allMs = $this->measure($profile, ['*'], $order, $offset, $runs);
$listMs = $this->measure($profile, $columns, $order, $offset, $runs);
$idOnlyMs = $this->measure($profile, ['id'], $order, $offset, $runs);
$rows[] = [
'offset' => $offset,
'all_ms' => $allMs,
'list_ms' => $listMs,
'id_only_ms' => $idOnlyMs,
'ratio' => $idOnlyMs > 0 ? round($allMs / $idOnlyMs, 1) : null,
'explain' => $this->option('explain') ? $this->explain($profile, $columns, $order, $offset) : null,
// 지연 조인의 inner 가 실제로 어떤 계획을 타는지가 인덱스 설계의 근거다
'explain_id_only' => $this->option('explain') ? $this->explain($profile, ['id'], $order, $offset) : null,
];
}
if ($this->option('json')) {
$this->line(json_encode([
'profile' => $key,
'table' => $profile['table'],
'columns' => $columns,
'runs' => $runs,
'results' => $rows,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
}
$this->table(
['OFFSET', '전체 컬럼(ms)', '목록 컬럼(ms)', 'ID만(ms)', '전체÷ID'],
array_map(fn (array $row) => [
number_format($row['offset']),
number_format($row['all_ms'], 1),
number_format($row['list_ms'], 1),
number_format($row['id_only_ms'], 1),
$row['ratio'] !== null ? $row['ratio'].'×' : '-',
], $rows)
);
if ($this->option('explain')) {
foreach ($rows as $row) {
$this->newLine();
$this->line("EXPLAIN @ OFFSET {$row['offset']} — 목록 컬럼");
foreach ($row['explain'] as $line) {
$this->line(' '.$line);
}
$this->line("EXPLAIN @ OFFSET {$row['offset']} — ID 만 (지연 조인 inner)");
foreach ($row['explain_id_only'] as $line) {
$this->line(' '.$line);
}
}
}
return self::SUCCESS;
}
/**
* OFFSET 목록을 파싱합니다.
*
* @return array<int, int> 오름차순 정렬된 OFFSET 목록
*/
private function parseOffsets(): array
{
$offsets = array_map('intval', array_filter(explode(',', (string) $this->option('offsets')), 'strlen'));
sort($offsets);
return $offsets === [] ? [0] : $offsets;
}
/**
* 스키마에 실제로 존재하는 컬럼만 남깁니다.
*
* @param string $table 테이블명
* @param array<int, string> $columns 후보 컬럼
* @return array<int, string> 존재하는 컬럼 목록
*/
private function existingColumns(string $table, array $columns): array
{
// ['*'] 는 "목록이 전 컬럼을 그대로 노출한다" 는 선언이다. 응답 계약상 넓은 컬럼을
// 뺄 수 없는 목록(활동 로그의 changes, 알림 발송 이력의 body 등)이 여기 해당하며,
// 이 경우 계측의 비교 축은 "select * vs select id" 가 된다.
if ($columns === ['*']) {
return Schema::getColumnListing($table);
}
$existing = array_values(array_filter($columns, fn (string $column) => Schema::hasColumn($table, $column)));
return $existing === [] ? ['id'] : $existing;
}
/**
* 스키마에 존재하는 정렬 컬럼만 남깁니다.
*
* @param string $table 테이블명
* @param array<int, array{0: string, 1: string}> $order 후보 정렬
* @return array<int, array{0: string, 1: string}> 적용 가능한 정렬 목록
*/
private function existingOrder(string $table, array $order): array
{
$existing = array_values(array_filter($order, fn (array $spec) => Schema::hasColumn($table, $spec[0])));
return $existing === [] ? [['id', 'desc']] : $existing;
}
/**
* 한 조합을 여러 번 실행해 중앙값(ms)을 돌려줍니다.
*
* DB::enableQueryLog() 는 오버헤드와 메모리 누적이 있어 쓰지 않고 직접 시간을 잰다.
*
* @param array $profile 프로파일 정의
* @param array<int, string> $columns select 컬럼
* @param array<int, array{0: string, 1: string}> $order 정렬
* @param int $offset OFFSET
* @param int $runs 측정 횟수
* @return float 중앙값 (밀리초)
*/
private function measure(array $profile, array $columns, array $order, int $offset, int $runs): float
{
// 첫 회는 캐시 워밍 성격이라 버린다
$this->runQuery($profile, $columns, $order, $offset);
$samples = [];
for ($i = 0; $i < $runs; $i++) {
$start = microtime(true);
$this->runQuery($profile, $columns, $order, $offset);
$samples[] = (microtime(true) - $start) * 1000;
}
sort($samples);
return $samples[intdiv(count($samples), 2)];
}
/**
* 계측 대상 쿼리를 실행합니다.
*
* @param array $profile 프로파일 정의
* @param array<int, string> $columns select 컬럼
* @param array<int, array{0: string, 1: string}> $order 정렬
* @param int $offset OFFSET
*/
private function runQuery(array $profile, array $columns, array $order, int $offset): void
{
$this->buildQuery($profile, $columns, $order, $offset)->get();
}
/**
* 계측 대상 쿼리를 조립합니다.
*
* @param array $profile 프로파일 정의
* @param array<int, string> $columns select 컬럼
* @param array<int, array{0: string, 1: string}> $order 정렬
* @param int $offset OFFSET
* @return Builder 조립된 쿼리
*/
private function buildQuery(array $profile, array $columns, array $order, int $offset)
{
$query = DB::table($profile['table'])->select($columns);
if ($profile['soft_delete'] && Schema::hasColumn($profile['table'], 'deleted_at')) {
$query->whereNull('deleted_at');
}
foreach ($profile['filters'] ?? [] as $column => $value) {
if (Schema::hasColumn($profile['table'], $column)) {
$query->where($column, $value);
}
}
foreach ($order as $spec) {
$query->orderBy($spec[0], $spec[1]);
}
return $query->offset($offset)->limit(20);
}
/**
* 실행 계획을 수집합니다.
*
* @param array $profile 프로파일 정의
* @param array<int, string> $columns select 컬럼
* @param array<int, array{0: string, 1: string}> $order 정렬
* @param int $offset OFFSET
* @return array<int, string> 실행 계획 요약 줄 목록
*/
private function explain(array $profile, array $columns, array $order, int $offset): array
{
$query = $this->buildQuery($profile, $columns, $order, $offset);
try {
$plan = DB::select('EXPLAIN '.$query->toSql(), $query->getBindings());
} catch (\Throwable $e) {
return ['실행 계획 수집 실패: '.$e->getMessage()];
}
return array_map(function ($row) {
$row = (array) $row;
return sprintf(
'type=%s key=%s rows=%s filtered=%s extra=%s',
$row['type'] ?? '-',
$row['key'] ?? '-',
$row['rows'] ?? '-',
$row['filtered'] ?? '-',
$row['Extra'] ?? '-'
);
}, $plan);
}
/**
* 계측용 합성 행을 시딩합니다.
*
* 스키마를 introspect 해 NOT NULL + 기본값 없는 컬럼만 타입에 맞춰 채운다. 프로파일마다
* 별도 시더를 두면 대상이 늘 때마다 시더가 따라 늘어나므로 일반화한다.
*
* @param string $table 대상 테이블
* @param int $count 시딩 건수
* @param array<string, mixed> $overrides 컬럼별 고정값 (실제 조회 조건과 맞추기 위한 지정)
*/
private function seedRows(string $table, int $count, array $overrides = []): void
{
$columns = Schema::getColumns($table);
$fillable = array_values(array_filter(
$columns,
fn (array $column) => ! ($column['auto_increment'] ?? false)
&& ! $column['nullable']
&& ($column['default'] === null)
));
$this->info("시딩: {$table} {$count} 건");
$bar = $this->output->createProgressBar($count);
$chunk = [];
$chunkSize = 500;
for ($i = 1; $i <= $count; $i++) {
$row = [];
foreach ($fillable as $column) {
$row[$column['name']] = array_key_exists($column['name'], $overrides)
? $overrides[$column['name']]
: $this->synthesizeValue($column, $i);
}
foreach ($overrides as $name => $value) {
if (! array_key_exists($name, $row) && Schema::hasColumn($table, $name)) {
$row[$name] = $value;
}
}
$chunk[] = $row;
if (count($chunk) >= $chunkSize) {
$this->insertSynthetic($table, $chunk);
$bar->advance(count($chunk));
$chunk = [];
}
}
if ($chunk !== []) {
$this->insertSynthetic($table, $chunk);
$bar->advance(count($chunk));
}
$bar->finish();
$this->newLine(2);
}
/**
* 합성 행을 삽입합니다. (외래키 제약 일시 해제)
*
* 합성 값은 실제 부모 행을 가리키지 않으므로 FK 를 그대로 두면 삽입이 거부된다.
* 본 커맨드가 재는 것은 대상 테이블의 OFFSET 스캔 비용이고 조인은 측정 대상이 아니므로,
* 부모 무결성 없이 행 수와 행 폭만 재현하면 목적에 충분하다. 폐기 가능한 계측용 DB
* (`--database`)에서만 쓰는 것을 전제로 한다.
*
* @param string $table 대상 테이블
* @param array<int, array<string, mixed>> $chunk 삽입할 행 묶음
*/
private function insertSynthetic(string $table, array $chunk): void
{
Schema::withoutForeignKeyConstraints(function () use ($table, $chunk) {
DB::table($table)->insert($chunk);
});
}
/**
* 컬럼 타입에 맞는 합성 값을 만듭니다.
*
* @param array $column Schema::getColumns() 항목
* @param int $index 행 인덱스 (고유값 생성용)
* @return mixed 합성 값
*/
private function synthesizeValue(array $column, int $index): mixed
{
$type = strtolower((string) ($column['type_name'] ?? $column['type'] ?? 'varchar'));
return match (true) {
str_contains($type, 'int') => $index,
str_contains($type, 'decimal'), str_contains($type, 'float'), str_contains($type, 'double') => 1000,
str_contains($type, 'bool'), str_contains($type, 'tinyint') => 0,
str_contains($type, 'json') => '{}',
// 시간 컬럼을 한 값으로 채우면 정렬이 전부 동률이 되어 filesort 가 지배해 버린다.
// 정렬 인덱스 효과를 재는 것이 목적이므로 행마다 값을 분산시킨다.
str_contains($type, 'date'), str_contains($type, 'time') => now()->subMinutes($index),
str_contains($type, 'text') => str_repeat('벤치마크 본문 ', 100),
default => $this->synthesizeString($column, $index),
};
}
/**
* 문자열 컬럼의 선언 길이에 맞는 합성 값을 만듭니다.
*
* 컬럼 길이를 무시하고 고정 길이 문자열을 넣으면 `varchar(10)` 류(신고 대상 타입,
* 우편번호, 로그 타입 등)에서 "Data too long" 으로 시딩 자체가 실패한다.
*
* @param array $column Schema::getColumns() 항목
* @param int $index 행 인덱스 (고유값 생성용)
* @return string 합성 문자열
*/
private function synthesizeString(array $column, int $index): string
{
$length = 40;
// type 은 'varchar(10)' 형태로 선언 길이를 담고 있다
if (preg_match('/\((\d+)\)/', (string) ($column['type'] ?? ''), $m) === 1) {
$length = max(1, (int) $m[1]);
}
// 짧은 컬럼은 고유성 확보가 우선이라 인덱스 자체를 문자열로 쓴다
if ($length <= 12) {
return substr((string) $index, -$length);
}
return substr("bench-{$index}-".Str::random(8), 0, $length);
}
}
+51 -16
View File
@@ -7,7 +7,10 @@ use App\Helpers\PermissionHelper;
use App\Helpers\TimezoneHelper;
use App\Models\ActivityLog;
use App\Repositories\Concerns\HasMultipleSearchFilters;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
@@ -17,6 +20,25 @@ use Illuminate\Database\Eloquent\Model;
class ActivityLogRepository implements ActivityLogRepositoryInterface
{
use HasMultipleSearchFilters;
use PaginatesWithDeferredJoin;
use ResolvesSortSpec;
/**
* 활동 로그 목록 정렬 허용 컬럼
*
* 요청 값을 그대로 orderBy 에 넘기면 없는 컬럼으로 SQL 오류가 나거나 인덱스 없는 컬럼
* 정렬을 강제할 수 있다.
*
* @var array<int, string>
*/
private const SORTABLE_COLUMNS = [
'id',
'created_at',
'action',
'log_type',
'user_id',
];
/**
* 특정 모델의 활동 로그를 페이지네이션하여 조회합니다.
*
@@ -26,8 +48,8 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
*/
public function getPaginatedForModel(Model $model, array $filters = []): LengthAwarePaginator
{
$sortOrder = $filters['sort_order'] ?? 'desc';
$query = ActivityLog::forModel($model)->orderBy('created_at', $sortOrder);
$sortOrder = $this->normalizeSortDirection($filters['sort_order'] ?? null);
$query = ActivityLog::forModel($model);
if (isset($filters['action'])) {
$query->action($filters['action']);
@@ -37,7 +59,13 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
$query->byUser($filters['user_id']);
}
return $query->paginate($filters['per_page'] ?? 15);
// 컬럼을 좁히지 않는 이유는 getPaginated() 와 같다 — 리소스가 변경 내역을 그대로 노출한다
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: [['column' => 'created_at', 'direction' => $sortOrder]],
perPage: (int) ($filters['per_page'] ?? 15),
);
}
/**
@@ -48,7 +76,8 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
*/
public function getPaginated(array $filters = []): LengthAwarePaginator
{
$query = ActivityLog::query()->with('user:id,uuid,name,email');
// 관계는 지연 조인의 outer 에서만 로드한다 (inner 는 키 컬럼만 조회한다)
$query = ActivityLog::query();
// 스코프 기반 권한 필터링 (self: 본인 로그만, role: 소유역할 로그, null: 전체)
PermissionHelper::applyPermissionScope($query, 'core.activities.read');
@@ -92,11 +121,18 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
$query->where('created_at', '<=', TimezoneHelper::fromSiteDateTime($filters['date_to']));
}
$sortBy = $filters['sort_by'] ?? 'created_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'created_at');
return $query->paginate($filters['per_page'] ?? 15);
// 목록 컬럼을 좁히지 않는 이유: 활동 로그 리소스는 변경 내역(mediumText `changes`)과
// 부가 정보(`properties`)까지 그대로 노출하므로 컬럼을 빼면 응답 계약이 바뀐다.
// 지연 조인만으로도 이 넓은 컬럼들을 읽는 행 수가 이번 페이지 분량으로 고정된다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: $sort,
perPage: (int) ($filters['per_page'] ?? 15),
relations: ['user:id,uuid,name,email'],
);
}
/**
@@ -105,10 +141,9 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
* action/description 필드는 영어 키를 저장하므로,
* 검색어가 번역된 라벨과 일치하는 원본 키도 함께 검색합니다.
*
* @param \Illuminate\Database\Eloquent\Builder $query 쿼리 빌더
* @param string $search 검색어
* @param string $searchType 검색 유형 (all, action, description, ip_address)
* @return void
* @param Builder $query 쿼리 빌더
* @param string $search 검색어
* @param string $searchType 검색 유형 (all, action, description, ip_address)
*/
private function applyBilingualSearch($query, string $search, string $searchType): void
{
@@ -146,7 +181,7 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
/**
* 번역된 액션 라벨로 원본 action 값을 역추적합니다.
*
* @param string $searchLower 소문자 검색어
* @param string $searchLower 소문자 검색어
* @return array<string> 일치하는 action 값 목록
*/
private function findActionsByTranslatedLabel(string $searchLower): array
@@ -179,7 +214,7 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
/**
* 번역된 설명 텍스트로 원본 description_key를 역추적합니다.
*
* @param string $searchLower 소문자 검색어
* @param string $searchLower 소문자 검색어
* @return array<string> 일치하는 description_key 목록
*/
private function findDescriptionKeysByTranslatedText(string $searchLower): array
@@ -200,7 +235,7 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
/**
* 활동 로그를 삭제합니다.
*
* @param int $id 삭제할 활동 로그 ID
* @param int $id 삭제할 활동 로그 ID
* @return bool 삭제 성공 여부
*/
public function delete(int $id): bool
@@ -211,7 +246,7 @@ class ActivityLogRepository implements ActivityLogRepositoryInterface
/**
* 여러 활동 로그를 일괄 삭제합니다.
*
* @param array<int> $ids 삭제할 활동 로그 ID 목록
* @param array<int> $ids 삭제할 활동 로그 ID 목록
* @return int 삭제된 건수
*/
public function deleteMany(array $ids): int
@@ -0,0 +1,258 @@
<?php
namespace App\Repositories\Concerns;
use Closure;
use Illuminate\Contracts\Pagination\Paginator as PaginatorContract;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
/**
* 지연 조인(deferred join) 기반 목록 페이지네이션 Trait
*
* `OFFSET n` 은 건너뛸 n 건도 실제로 읽는다. 목록 SELECT 에 넓은 컬럼(text/longText/JSON)이
* 포함돼 있으면 그 n 건의 넓은 컬럼까지 함께 읽히고, 특히 InnoDB 는 행 밖 오버플로 페이지에
* 저장된 값을 앞부분만 필요해도 페이지째 읽는다. 그래서 페이지가 뒤로 갈수록 비용이 선형으로
* 커진다.
*
* 지연 조인은 이를 두 단계로 나눈다.
*
* 1. inner — 필터/정렬만으로 **키 컬럼만** 조회해 이번 페이지의 ID 집합을 구한다
* 2. outer — 그 ID 집합에 대해서만 목록 컬럼과 관계를 조회한다
*
* 넓은 컬럼을 읽는 행 수가 OFFSET 과 무관하게 `$perPage` 건으로 고정되므로 뒤쪽 페이지의
* 비용 증가가 사라진다.
*
* 호출 계약:
* - `$query` 에는 **필터/where 만** 적용한다 (`orderBy`/`with`/`select` 미적용)
* - `whereHas` 는 결과 집합을 결정하므로 그대로 둔다 — `with` 만 inner 에서 제거된다
* - 정렬은 닫힌 집합이어야 한다 (ResolvesSortSpec 참조). 인덱스 없는 컬럼 정렬은 inner 도
* 전체 스캔하므로 개선 폭이 보장되지 않는다
* - 키 컬럼은 정렬 마지막에 자동으로 덧붙는다 (동률 시 페이지 경계가 흔들리는 것을 방지)
*
* 목록 컬럼에 `SUBSTRING(content, 1, N)` 을 두는 것은 프루닝으로 인정하지 않는다. 오버플로
* 페이지 읽기가 그대로 발생하므로, 잘라내기는 outer(`$columns`)에서만 수행한다.
*
* @see ResolvesSortSpec 정렬 스펙 해석
*/
trait PaginatesWithDeferredJoin
{
/**
* 지연 조인으로 목록을 페이지네이션합니다.
*
* @param Builder $query 필터/where 만 적용된 쿼리 (orderBy/with/select 미적용)
* @param array $columns outer select 목록 (DB::raw 허용)
* @param array<int, array{column: string, direction: string}> $sort 정렬 스펙
* @param int $perPage 페이지당 건수
* @param int|null $page 현재 페이지 (null = 요청에서 해석)
* @param array<int, string> $relations outer 전용 eager load 관계
* @param array<int, string> $withCount outer 전용 관계 카운트
* @param string $keyName 키 컬럼명 (기본 id)
* @param int|null $total 전체 건수 (null = COUNT 수행, 값 지정 시 캐시 total 사용)
* @param bool $simple true = COUNT 없이 다음 페이지 유무만 판정
* @param bool $preserveIdOrder true = inner 가 정한 ID 순서를 outer 에서 그대로 복원
* @param string $pageName 페이지 쿼리 파라미터명
* @param Closure|null $outerUsing outer 에만 적용할 조인/집계 (inner 에서는 실행되지 않는다)
* @return PaginatorContract 페이지네이터 ($simple=true 면 Paginator, 아니면 LengthAwarePaginator)
*/
protected function paginateWithDeferredJoin(
Builder $query,
array $columns,
array $sort,
int $perPage,
?int $page = null,
array $relations = [],
array $withCount = [],
string $keyName = 'id',
?int $total = null,
bool $simple = false,
bool $preserveIdOrder = false,
string $pageName = 'page',
?Closure $outerUsing = null,
): PaginatorContract {
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$page = max(1, $page);
$sort = $this->normalizeSortSpecForKey($sort, $keyName);
// inner — 키 컬럼만 조회한다. with() 를 비우는 이유 두 가지:
// (a) 성능 — 관계 쿼리가 inner/outer 두 번 실행된다
// (b) 정합성 — inner 는 키 컬럼만 select 하므로 관계 FK 가 없어 eager load 가 깨진다
// whereHas 는 결과 집합을 결정하는 조건이라 setEagerLoads 로 지워지지 않는다 (의도된 구분).
$inner = (clone $query)->setEagerLoads([]);
if (! $simple && $total === null) {
// Laravel 의 paginate() 와 같은 집계 경로를 쓴다. count() 는 groupBy/having 이 있는
// 쿼리에서 `select count(*) ... group by ...` 를 그대로 실행해 **첫 그룹의 행 수**를
// 총 건수로 돌려준다. getCountForPagination() 은 그룹 쿼리를 서브쿼리로 감싸므로
// 그룹 수가 정확히 나온다. toBase() 는 글로벌 스코프를 적용한 뒤 기반 쿼리를 주므로
// 소프트 삭제/필터 조건이 집계에서 누락되지 않는다.
$total = (clone $inner)->toBase()->getCountForPagination();
}
$this->applySortSpec($inner, $sort);
// simple 모드는 다음 페이지 유무 판정을 위해 한 건을 더 읽는다 (Paginator 가 잘라낸다).
// forPage() 를 쓰면 offset 이 (page-1) * (perPage+1) 로 계산돼 페이지가 넘어갈수록
// 건너뛰는 행이 어긋나므로, offset 은 perPage 기준으로 직접 지정한다.
$fetchCount = $simple ? $perPage + 1 : $perPage;
$ids = $inner
->select($inner->getModel()->qualifyColumn($keyName))
->offset(($page - 1) * $perPage)
->limit($fetchCount)
->pluck($keyName);
$items = $ids->isEmpty()
? new Collection
: $this->fetchDeferredJoinRows($query, $columns, $sort, $ids->all(), $relations, $withCount, $keyName, $preserveIdOrder, $outerUsing);
$options = [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
];
if ($simple) {
return new Paginator($items, $perPage, $page, $options);
}
return new LengthAwarePaginator($items, $total ?? $items->count(), $perPage, $page, $options);
}
/**
* outer 쿼리를 실행해 실제 행을 조회합니다.
*
* @param Builder $query 필터가 적용된 원본 쿼리 (soft delete 스코프 보존을 위해 재사용)
* @param array $columns select 목록
* @param array<int, array{column: string, direction: string}> $sort 정렬 스펙
* @param array<int, mixed> $ids 이번 페이지의 키 값 목록
* @param array<int, string> $relations eager load 관계
* @param array<int, string> $withCount 관계 카운트
* @param string $keyName 키 컬럼명
* @param bool $preserveIdOrder ID 순서 그대로 복원 여부
* @param Closure|null $outerUsing outer 전용 조인/집계
* @return Collection 조회된 행 컬렉션
*/
private function fetchDeferredJoinRows(
Builder $query,
array $columns,
array $sort,
array $ids,
array $relations,
array $withCount,
string $keyName,
bool $preserveIdOrder,
?Closure $outerUsing = null,
): Collection {
$outer = (clone $query)->setEagerLoads([]);
$qualifiedKey = $outer->getModel()->qualifyColumn($keyName);
$outer->whereIn($qualifiedKey, $ids);
// 결과 집합을 좁히지 않는 조인/집계(최근 댓글 서브쿼리, 상관 COUNT 등)는 여기서만
// 붙인다. inner 에 두면 건너뛸 행 전체에 대해 실행되므로 OFFSET 이 깊어질수록 그
// 비용이 그대로 누적된다. whereIn 뒤에 적용하므로 이번 페이지 건수에만 실행된다.
if ($outerUsing !== null) {
$outerUsing($outer);
}
if (! empty($relations)) {
$outer->with($relations);
}
if (! empty($withCount)) {
$outer->withCount($withCount);
}
if ($preserveIdOrder) {
$this->applyIdOrder($outer, $qualifiedKey, $ids);
} else {
// 정렬 스펙에 키 컬럼이 포함돼 전순서가 보장되므로, 같은 스펙을 다시 적용하면
// inner 가 정한 순서와 결과가 동일하다 (MySQL 전용 FIELD() 가 필요 없다).
$this->applySortSpec($outer, $sort);
}
return $outer->get($columns);
}
/**
* 정렬 스펙을 쿼리에 적용합니다.
*
* @param Builder $query 대상 쿼리
* @param array<int, array{column: string, direction: string}> $sort 정렬 스펙
*/
private function applySortSpec(Builder $query, array $sort): void
{
foreach ($sort as $spec) {
$query->orderBy($spec['column'], $spec['direction']);
}
}
/**
* 정렬 스펙 끝에 키 컬럼을 덧붙여 전순서를 만듭니다.
*
* 정렬 컬럼에 중복이 많으면(상태/조회수/평점 등) 동률 행의 순서가 실행마다 달라져 페이지
* 경계에서 행이 중복되거나 누락된다. inner 와 outer 가 같은 순서를 갖도록 하는 전제이기도 하다.
*
* @param array<int, array{column: string, direction: string}> $sort 정렬 스펙
* @param string $keyName 키 컬럼명
* @return array<int, array{column: string, direction: string}> 키 컬럼이 보장된 정렬 스펙
*/
private function normalizeSortSpecForKey(array $sort, string $keyName): array
{
$normalized = [];
foreach ($sort as $spec) {
$column = $spec['column'] ?? null;
if (! is_string($column) || $column === '') {
continue;
}
$normalized[] = [
'column' => $column,
'direction' => strtolower($spec['direction'] ?? 'desc') === 'asc' ? 'asc' : 'desc',
];
}
foreach ($normalized as $spec) {
// 이미 키 컬럼으로 정렬한다면 그것으로 전순서가 성립한다
if ($spec['column'] === $keyName || str_ends_with($spec['column'], '.'.$keyName)) {
return $normalized;
}
}
$lastDirection = $normalized === [] ? 'desc' : end($normalized)['direction'];
$normalized[] = ['column' => $keyName, 'direction' => $lastDirection];
return $normalized;
}
/**
* inner 가 정한 ID 순서를 outer 에서 그대로 복원합니다.
*
* outer 에 존재하지 않는 표현식(집계/조인 서브쿼리 등)으로 정렬한 경우에만 사용한다.
* MySQL 전용 `FIELD()` 대신 표준 SQL `CASE WHEN` 을 쓴다 (DB 비의존 규정).
*
* @param Builder $query 대상 쿼리
* @param string $qualifiedKey 테이블명이 붙은 키 컬럼
* @param array<int, mixed> $ids 복원할 순서의 키 값 목록
*/
private function applyIdOrder(Builder $query, string $qualifiedKey, array $ids): void
{
$wrapped = $query->getQuery()->getGrammar()->wrap($qualifiedKey);
$cases = [];
$bindings = [];
foreach (array_values($ids) as $index => $id) {
$cases[] = "WHEN {$wrapped} = ? THEN {$index}";
$bindings[] = $id;
}
$query->orderByRaw('CASE '.implode(' ', $cases).' ELSE '.count($ids).' END', $bindings);
}
}
@@ -0,0 +1,105 @@
<?php
namespace App\Repositories\Concerns;
use BackedEnum;
/**
* 요청 유래 정렬 조건을 닫힌 집합으로 해석하는 Trait
*
* 요청 파라미터(`sort_by`/`sort_order` 등)를 그대로 `orderBy()` 에 넘기면 두 가지 문제가 생긴다.
*
* 1. 존재하지 않는 컬럼이 오면 SQL 오류가 나고, 그 오류 응답이 스키마 정보를 노출한다
* 2. 인덱스가 없는 넓은 컬럼으로 정렬을 강제할 수 있어 DoS 표면이 된다
*
* (Laravel 은 컬럼명을 백틱으로 감싸므로 고전적 SQL 인젝션은 성립하지 않는다 — 위 두 가지가 실제 위험이다.)
*
* 본 Trait 은 허용 컬럼 화이트리스트로 정렬 조건을 해석하고, 지연 조인 페이지네이션이 요구하는
* 정렬 스펙 배열 형태로 돌려준다.
*
* 정렬 선택지가 4개 이하로 고정된 곳은 `match` 표현식으로 이미 닫혀 있으므로 본 Trait 이 불필요하다.
* 요청 값이 동적 컬럼으로 흘러 들어가는 곳에만 사용한다.
*
* @see PaginatesWithDeferredJoin 해석 결과를 그대로 `$sort` 인자로 받는다
*/
trait ResolvesSortSpec
{
/**
* 요청 필터에서 정렬 스펙을 해석합니다.
*
* @param array $filters 요청 유래 필터 배열
* @param array<int, string> $allowedColumns 허용 정렬 컬럼 화이트리스트
* @param string $defaultColumn 화이트리스트에 없거나 미전송일 때 사용할 컬럼
* @param string $defaultDirection 기본 정렬 방향 (asc|desc)
* @param array<string, string> $columnAliases 요청 값 → 실제 컬럼 매핑 (예: ['author' => 'author_name'])
* @param string $columnKey 정렬 컬럼이 담긴 필터 키
* @param string $directionKey 정렬 방향이 담긴 필터 키
* @return array<int, array{column: string, direction: string}> 정렬 스펙 배열
*/
protected function resolveSortSpec(
array $filters,
array $allowedColumns,
string $defaultColumn,
string $defaultDirection = 'desc',
array $columnAliases = [],
string $columnKey = 'sort_by',
string $directionKey = 'sort_order',
): array {
$column = $this->normalizeSortValue($filters[$columnKey] ?? null);
$direction = $this->normalizeSortValue($filters[$directionKey] ?? null);
if ($column !== null && isset($columnAliases[$column])) {
$column = $columnAliases[$column];
}
if ($column === null || ! in_array($column, $allowedColumns, true)) {
$column = $defaultColumn;
}
return [[
'column' => $column,
'direction' => $this->normalizeSortDirection($direction, $defaultDirection),
]];
}
/**
* 정렬 방향 문자열을 asc/desc 로 정규화합니다.
*
* @param string|null $direction 요청 값
* @param string $default 허용 값이 아닐 때 사용할 기본 방향
* @return string asc 또는 desc
*/
protected function normalizeSortDirection(?string $direction, string $default = 'desc'): string
{
$normalized = strtolower((string) $direction);
if (in_array($normalized, ['asc', 'desc'], true)) {
return $normalized;
}
$fallback = strtolower($default);
return in_array($fallback, ['asc', 'desc'], true) ? $fallback : 'desc';
}
/**
* 정렬 관련 요청 값을 문자열로 정규화합니다. (Enum/빈 문자열 흡수)
*
* @param mixed $value 요청 값 (문자열 또는 BackedEnum)
* @return string|null 정규화된 문자열 (값이 없으면 null)
*/
private function normalizeSortValue(mixed $value): ?string
{
if ($value instanceof BackedEnum) {
$value = $value->value;
}
if (! is_string($value) && ! is_int($value)) {
return null;
}
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}
@@ -4,11 +4,25 @@ namespace App\Repositories;
use App\Contracts\Repositories\IdentityMessageDefinitionRepositoryInterface;
use App\Models\IdentityMessageDefinition;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class IdentityMessageDefinitionRepository implements IdentityMessageDefinitionRepositoryInterface
{
use ResolvesSortSpec;
/** 허용 정렬 컬럼 (AdminIdentityMessageDefinitionIndexRequest 와 동일 집합) */
private const SORTABLE_COLUMNS = [
'id',
'provider_id',
'scope_type',
'scope_value',
'is_active',
'created_at',
'updated_at',
];
/**
* ID로 메시지 정의 조회.
*
@@ -180,10 +194,11 @@ class IdentityMessageDefinitionRepository implements IdentityMessageDefinitionRe
});
}
$sortBy = $filters['sort_by'] ?? 'id';
$sortOrder = $filters['sort_order'] ?? 'asc';
$query->orderBy($sortBy, $sortOrder);
foreach ($this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'id', 'asc') as $sort) {
$query->orderBy($sort['column'], $sort['direction']);
}
// audit:allow repository-paginate-column-pruning reason: 본인인증 메시지 정의 테이블 — 정의 수가 고정이고 넓은 컬럼이 없다
return $query->paginate($perPage);
}
}
@@ -252,6 +252,7 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
});
}
// audit:allow repository-paginate-column-pruning reason: 본인인증 정책 정의 테이블 — 정책 수가 고정이고 넓은 컬럼이 없다
return $query->orderByDesc('created_at')->orderByDesc('id')->paginate($perPage);
}
@@ -4,7 +4,10 @@ namespace App\Repositories;
use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface;
use App\Enums\IdentityVerificationStatus;
use App\Models\IdentityPolicy;
use App\Models\IdentityVerificationLog;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
/**
@@ -14,6 +17,8 @@ use Illuminate\Support\Carbon;
*/
class IdentityVerificationLogRepository implements IdentityVerificationLogRepositoryInterface
{
use PaginatesWithDeferredJoin;
/**
* 검증 로그를 생성합니다.
*
@@ -130,7 +135,7 @@ class IdentityVerificationLogRepository implements IdentityVerificationLogReposi
*
* @param array $filters 검색 필터
* @param int $perPage 페이지당 항목 수
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 페이지네이터
* @return LengthAwarePaginator 페이지네이터
*/
public function search(array $filters, int $perPage = 20)
{
@@ -158,7 +163,7 @@ class IdentityVerificationLogRepository implements IdentityVerificationLogReposi
if (! empty($filters['source_type'])) {
$query->whereIn('origin_policy_key', function ($q) use ($filters) {
$q->select('key')
->from('identity_policies')
->from((new IdentityPolicy)->getTable())
->where('source_type', $filters['source_type']);
if (! empty($filters['source_identifier'])) {
$q->where('source_identifier', $filters['source_identifier']);
@@ -202,9 +207,15 @@ class IdentityVerificationLogRepository implements IdentityVerificationLogReposi
? $filters['sort_by']
: 'created_at';
$sortOrder = ($filters['sort_order'] ?? 'desc') === 'asc' ? 'asc' : 'desc';
$query->orderBy($sortBy, $sortOrder);
return $query->paginate($perPage);
// 본인인증 로그는 계속 쌓이는 이력이라 뒤쪽 페이지에서 OFFSET 비용이 커진다.
// 응답이 요청/응답 payload 를 그대로 노출하므로 컬럼은 좁히지 않고 지연 조인만 적용한다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: [['column' => $sortBy, 'direction' => $sortOrder]],
perPage: $perPage,
);
}
/**
+13 -8
View File
@@ -4,10 +4,13 @@ namespace App\Repositories;
use App\Contracts\Repositories\LanguagePackRepositoryInterface;
use App\Enums\LanguagePackScope;
use App\Enums\LanguagePackSourceType;
use App\Enums\LanguagePackStatus;
use App\Enums\TextDirection;
use App\Models\LanguagePack;
use App\Repositories\Concerns\HasMultipleSearchFilters;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
@@ -127,6 +130,7 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
*/
public function paginate(array $filters = [], int $perPage = 20): LengthAwarePaginator
{
// audit:allow repository-paginate-column-pruning reason: 언어팩 정의 테이블 — 설치된 팩 수만큼만 존재하고 넓은 컬럼이 없다
return $this->buildFilteredQuery($filters)->paginate($perPage);
}
@@ -148,9 +152,9 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
* (실제 미설치 번들은 Service 계층에서 합쳐집니다).
*
* @param array<string, mixed> $filters 필터 조건
* @return \Illuminate\Database\Eloquent\Builder<LanguagePack> 정렬까지 적용된 쿼리 빌더
* @return Builder<LanguagePack> 정렬까지 적용된 쿼리 빌더
*/
private function buildFilteredQuery(array $filters): \Illuminate\Database\Eloquent\Builder
private function buildFilteredQuery(array $filters): Builder
{
$query = LanguagePack::query();
@@ -165,7 +169,8 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
}
if (! empty($filters['status'])) {
if ($filters['status'] === LanguagePackStatus::Uninstalled->value) {
$query->whereRaw('1 = 0');
// 결과 없음 — 빈 whereIn 은 `0 = 1` 로 컴파일된다(raw 불필요)
$query->whereIn($query->getModel()->getKeyName(), []);
} else {
$query->where('status', $filters['status']);
}
@@ -282,10 +287,10 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
$pack->version = (string) ($manifest['version'] ?? '0.0.0');
$pack->license = $manifest['license'] ?? null;
$pack->description = is_array($manifest['description'] ?? null) ? $manifest['description'] : null;
$pack->status = \App\Enums\LanguagePackStatus::Uninstalled->value;
$pack->status = LanguagePackStatus::Uninstalled->value;
$pack->is_protected = false; // lang-packs/_bundled/ 패키지는 사용자가 install/uninstall 자유 (요구사항 #3)
$pack->manifest = $manifest;
$pack->source_type = \App\Enums\LanguagePackSourceType::Bundled->value;
$pack->source_type = LanguagePackSourceType::Bundled->value;
$pack->source_url = $bundledIdentifier;
$pack->setAttribute('bundled_identifier', $bundledIdentifier);
@@ -335,11 +340,11 @@ class LanguagePackRepository implements LanguagePackRepositoryInterface
$pack->locale = $locale;
$pack->locale_name = strtoupper($locale);
$pack->locale_native_name = $nativeName;
$pack->text_direction = \App\Enums\TextDirection::Ltr->value;
$pack->text_direction = TextDirection::Ltr->value;
$pack->version = $version;
$pack->status = \App\Enums\LanguagePackStatus::Active->value;
$pack->status = LanguagePackStatus::Active->value;
$pack->is_protected = true;
$pack->source_type = \App\Enums\LanguagePackSourceType::BuiltIn->value;
$pack->source_type = LanguagePackSourceType::BuiltIn->value;
$pack->source_url = $langPathRelative;
$pack->manifest = [
'identifier' => $identifier,
+41 -15
View File
@@ -3,15 +3,24 @@
namespace App\Repositories;
use App\Contracts\Repositories\MenuRepositoryInterface;
use App\Helpers\PermissionHelper;
use App\Enums\ExtensionOwnerType;
use App\Helpers\PermissionHelper;
use App\Models\Menu;
use App\Models\Module;
use App\Models\Plugin;
use App\Models\User;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
class MenuRepository implements MenuRepositoryInterface
{
use ResolvesSortSpec;
/** 허용 정렬 컬럼 (MenuListRequest 와 동일 집합) */
private const SORTABLE_COLUMNS = ['created_at', 'name', 'slug', 'order'];
/**
* 모든 메뉴를 조회합니다.
*
@@ -37,6 +46,14 @@ class MenuRepository implements MenuRepositoryInterface
->get();
}
/**
* 관리용 최상위 메뉴 목록을 조회합니다. (비활성 확장 메뉴 제외)
*
* @param array $activeModuleIdentifiers 활성 모듈 식별자 목록
* @param array $activePluginIdentifiers 활성 플러그인 식별자 목록
* @param User|null $user 접근 권한 판정 대상 사용자 (null 이면 역할 필터 미적용)
* @return Collection 최상위 메뉴 컬렉션 (자식 메뉴 포함)
*/
public function getTopLevelMenusForManagement(array $activeModuleIdentifiers = [], array $activePluginIdentifiers = [], ?User $user = null): Collection
{
$extensionFilter = function ($query) use ($activeModuleIdentifiers, $activePluginIdentifiers) {
@@ -67,13 +84,13 @@ class MenuRepository implements MenuRepositoryInterface
}
return $query->with(['creator', 'roles', 'children' => function ($query) use ($extensionFilter, $user) {
$query->where($extensionFilter);
if ($user) {
$query->accessibleBy($user);
}
$query->with('roles')
->orderBy('order');
}])
$query->where($extensionFilter);
if ($user) {
$query->accessibleBy($user);
}
$query->with('roles')
->orderBy('order');
}])
->orderBy('order')
->get();
}
@@ -260,7 +277,7 @@ class MenuRepository implements MenuRepositoryInterface
$q->where('extension_type', ExtensionOwnerType::Module)
->whereExists(function ($subQuery) {
$subQuery->select(DB::raw(1))
->from('modules')
->from((new Module)->getTable())
->whereColumn('modules.identifier', 'menus.extension_identifier')
->where('modules.status', 'active');
});
@@ -270,7 +287,7 @@ class MenuRepository implements MenuRepositoryInterface
$q->where('extension_type', ExtensionOwnerType::Plugin)
->whereExists(function ($subQuery) {
$subQuery->select(DB::raw(1))
->from('plugins')
->from((new Plugin)->getTable())
->whereColumn('plugins.identifier', 'menus.extension_identifier')
->where('plugins.status', 'active');
});
@@ -359,6 +376,15 @@ class MenuRepository implements MenuRepositoryInterface
return (int) Menu::where('parent_id', $parentId)->max('order');
}
/**
* 필터 조건이 적용된 최상위 메뉴 목록을 조회합니다.
*
* @param array $filters 필터 조건 배열 (sort_by/sort_order/검색 필드)
* @param array $activeModuleIdentifiers 활성 모듈 식별자 목록
* @param array $activePluginIdentifiers 활성 플러그인 식별자 목록
* @param User|null $user 접근 권한 판정 대상 사용자 (null 이면 역할 필터 미적용)
* @return Collection 최상위 메뉴 컬렉션 (자식 메뉴 포함)
*/
public function getFilteredTopLevelMenus(array $filters, array $activeModuleIdentifiers = [], array $activePluginIdentifiers = [], ?User $user = null): Collection
{
$extensionFilter = function ($query) use ($activeModuleIdentifiers, $activePluginIdentifiers) {
@@ -418,10 +444,10 @@ class MenuRepository implements MenuRepositoryInterface
}
}
// 정렬
$sortBy = $filters['sort_by'] ?? 'order';
$sortOrder = $filters['sort_order'] ?? 'asc';
$query->orderBy($sortBy, $sortOrder);
// 정렬 (허용 컬럼 화이트리스트로 해석)
foreach ($this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'order', 'asc') as $sort) {
$query->orderBy($sort['column'], $sort['direction']);
}
// 자식 메뉴도 동일한 조건 적용하여 로드
return $query->with(['creator', 'roles', 'children' => function ($childQuery) use ($extensionFilter, $filters, $user) {
@@ -444,7 +470,7 @@ class MenuRepository implements MenuRepositoryInterface
/**
* 필터 연산자를 쿼리에 적용합니다.
*
* @param \Illuminate\Database\Eloquent\Builder $query 쿼리 빌더
* @param Builder $query 쿼리 빌더
* @param string $field 필드명
* @param string $value 검색 값
* @param string $operator 연산자 (like, eq, starts_with, ends_with)
@@ -4,15 +4,28 @@ namespace App\Repositories;
use App\Contracts\Repositories\NotificationDefinitionRepositoryInterface;
use App\Models\NotificationDefinition;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class NotificationDefinitionRepository implements NotificationDefinitionRepositoryInterface
{
use ResolvesSortSpec;
/** 허용 정렬 컬럼 (NotificationDefinitionIndexRequest 와 동일 집합) */
private const SORTABLE_COLUMNS = [
'id',
'type',
'extension_type',
'is_active',
'created_at',
'updated_at',
];
/**
* ID로 알림 정의 조회.
*
* @param int $id
* @param int $id
* @return NotificationDefinition|null
*/
public function findById(int $id): ?NotificationDefinition
@@ -23,7 +36,7 @@ class NotificationDefinitionRepository implements NotificationDefinitionReposito
/**
* 타입으로 알림 정의 조회.
*
* @param string $type
* @param string $type
* @return NotificationDefinition|null
*/
public function findByType(string $type): ?NotificationDefinition
@@ -34,7 +47,7 @@ class NotificationDefinitionRepository implements NotificationDefinitionReposito
/**
* 활성 상태인 특정 타입 알림 정의 조회.
*
* @param string $type
* @param string $type
* @return NotificationDefinition|null
*/
public function getActiveByType(string $type): ?NotificationDefinition
@@ -58,7 +71,7 @@ class NotificationDefinitionRepository implements NotificationDefinitionReposito
* 알림 목록 응답에서 N+1 회피 목적으로 한 번 호출하여 [type => label] 맵을 생성합니다.
* 라벨 fallback 우선순위: 사용자 로케일 → ko → en → type 식별자
*
* @param string|null $locale 사용자 로케일 (null이면 app()->getLocale())
* @param string|null $locale 사용자 로케일 (null이면 app()->getLocale())
* @return array<string, string>
*/
public function getLabelMap(?string $locale = null): array
@@ -86,8 +99,8 @@ class NotificationDefinitionRepository implements NotificationDefinitionReposito
/**
* 특정 확장의 알림 정의 목록 조회.
*
* @param string $extensionType
* @param string $extensionIdentifier
* @param string $extensionType
* @param string $extensionIdentifier
* @return Collection
*/
public function getByExtension(string $extensionType, string $extensionIdentifier): Collection
@@ -98,8 +111,8 @@ class NotificationDefinitionRepository implements NotificationDefinitionReposito
/**
* 알림 정의 수정.
*
* @param NotificationDefinition $definition
* @param array $data
* @param NotificationDefinition $definition
* @param array $data
* @return NotificationDefinition
*/
public function update(NotificationDefinition $definition, array $data): NotificationDefinition
@@ -112,8 +125,8 @@ class NotificationDefinitionRepository implements NotificationDefinitionReposito
/**
* 페이지네이션 목록 조회.
*
* @param array $filters
* @param int $perPage
* @param array $filters
* @param int $perPage
* @return LengthAwarePaginator
*/
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator
@@ -148,10 +161,11 @@ class NotificationDefinitionRepository implements NotificationDefinitionReposito
});
}
$sortBy = $filters['sort_by'] ?? 'id';
$sortOrder = $filters['sort_order'] ?? 'asc';
$query->orderBy($sortBy, $sortOrder);
foreach ($this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'id', 'asc') as $sort) {
$query->orderBy($sort['column'], $sort['direction']);
}
// audit:allow repository-paginate-column-pruning reason: 알림 정의 테이블 — 정의 수가 고정이고 넓은 컬럼이 없다
return $query->paginate($perPage);
}
}
+36 -5
View File
@@ -6,12 +6,35 @@ use App\Contracts\Repositories\NotificationLogRepositoryInterface;
use App\Enums\NotificationLogStatus;
use App\Models\NotificationLog;
use App\Models\User;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class NotificationLogRepository implements NotificationLogRepositoryInterface
{
use PaginatesWithDeferredJoin;
use ResolvesSortSpec;
/**
* 발송 이력 목록 정렬 허용 컬럼
*
* 요청 값을 그대로 orderBy 에 넘기면 없는 컬럼으로 SQL 오류가 나거나 인덱스 없는 컬럼
* 정렬을 강제할 수 있다.
*
* @var array<int, string>
*/
private const SORTABLE_COLUMNS = [
'id',
'sent_at',
'created_at',
'status',
'channel',
'notification_type',
'recipient_name',
];
/**
* 최근 발송된 알림 로그를 발송 시각 최신순으로 조회합니다 (대시보드 최근 알림).
*
@@ -81,7 +104,8 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
*/
public function getPaginated(array $filters = [], int $perPage = 20, ?User $scopeUser = null): LengthAwarePaginator
{
$query = NotificationLog::with(['senderUser', 'recipientUser']);
// 관계는 지연 조인의 outer 에서만 로드한다 (inner 는 키 컬럼만 조회한다)
$query = NotificationLog::query();
// notification-logs scope: 전달된 사용자의 권한 스코프 적용
if ($scopeUser) {
@@ -125,11 +149,18 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
});
}
$sortBy = $filters['sort_by'] ?? 'sent_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'sent_at');
return $query->paginate($perPage);
// 목록 컬럼을 좁히지 않는 이유: 이 목록의 리소스는 렌더링된 본문(longText `body`)까지
// 그대로 노출하므로 컬럼을 빼면 응답 계약이 바뀐다. 지연 조인만으로도 본문을 읽는
// 행 수가 OFFSET 과 무관하게 이번 페이지 분량으로 고정된다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: $sort,
perPage: $perPage,
relations: ['senderUser', 'recipientUser'],
);
}
/**
+29 -1
View File
@@ -11,6 +11,11 @@ class NotificationRepository implements NotificationRepositoryInterface
{
/**
* 사용자의 알림 목록을 페이지네이션으로 조회합니다.
*
* @param User $user 대상 사용자
* @param array $filters 필터 조건 (read: unread|read)
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator 페이지네이션된 알림 목록
*/
public function getByUser(User $user, array $filters = [], int $perPage = 20): LengthAwarePaginator
{
@@ -22,11 +27,17 @@ class NotificationRepository implements NotificationRepositoryInterface
$query->whereNotNull('read_at');
}
// audit:allow repository-paginate-column-pruning reason: 사용자 1명에 종속된 알림함 —
// $user->notifications() 로 이미 좁혀지고, 목록이 표시하는 본문 자체가 data(JSON) 라
// 걷어낼 넓은 컬럼이 없다
return $query->orderBy('created_at', 'desc')->paginate($perPage);
}
/**
* 사용자의 미읽음 알림 수를 반환합니다.
*
* @param User $user 대상 사용자
* @return int 미읽음 알림 수
*/
public function getUnreadCount(User $user): int
{
@@ -35,6 +46,10 @@ class NotificationRepository implements NotificationRepositoryInterface
/**
* 특정 알림을 읽음 처리합니다.
*
* @param User $user 대상 사용자
* @param string $notificationId 알림 ID
* @return DatabaseNotification|null 읽음 처리된 알림 (없으면 null)
*/
public function markAsRead(User $user, string $notificationId): ?DatabaseNotification
{
@@ -51,6 +66,10 @@ class NotificationRepository implements NotificationRepositoryInterface
/**
* 지정된 알림들을 일괄 읽음 처리합니다.
*
* @param User $user 대상 사용자
* @param array $ids 알림 ID 배열
* @return int 읽음 처리된 알림 수
*/
public function markBatchAsRead(User $user, array $ids): int
{
@@ -61,6 +80,9 @@ class NotificationRepository implements NotificationRepositoryInterface
/**
* 사용자의 모든 미읽음 알림을 읽음 처리합니다.
*
* @param User $user 대상 사용자
* @return int 읽음 처리된 알림 수
*/
public function markAllAsRead(User $user): int
{
@@ -73,6 +95,10 @@ class NotificationRepository implements NotificationRepositoryInterface
/**
* 알림을 삭제합니다.
*
* @param User $user 대상 사용자
* @param string $notificationId 알림 ID
* @return bool 삭제 성공 여부 (알림이 없으면 false)
*/
public function delete(User $user, string $notificationId): bool
{
@@ -88,7 +114,7 @@ class NotificationRepository implements NotificationRepositoryInterface
/**
* 사용자의 모든 알림을 삭제합니다.
*
* @param User $user
* @param User $user
* @return int 삭제된 알림 수
*/
public function deleteAll(User $user): int
@@ -99,6 +125,8 @@ class NotificationRepository implements NotificationRepositoryInterface
/**
* 오래된 알림을 정리합니다.
*
* @param int $readRetentionDays 읽은 알림 보관 일수 (0 이하면 정리하지 않음)
* @param int $unreadRetentionDays 미읽음 알림 보관 일수 (0 이하면 정리하지 않음)
* @return array{deleted_read: int, deleted_unread: int}
*/
public function cleanup(int $readRetentionDays, int $unreadRetentionDays): array
+1
View File
@@ -218,6 +218,7 @@ class RoleRepository implements RoleRepositoryInterface
$query->orderByRaw('CASE WHEN extension_type IS NOT NULL THEN 0 ELSE 1 END')
->orderBy('created_at', 'desc');
// audit:allow repository-paginate-column-pruning reason: 역할 정의 테이블 — 행 수가 운영상 고정(수십 건)이고 넓은 컬럼이 없다
return $query->paginate($perPage);
}
+38 -23
View File
@@ -4,15 +4,20 @@ namespace App\Repositories;
use App\Contracts\Repositories\ScheduleHistoryRepositoryInterface;
use App\Models\ScheduleHistory;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
{
use PaginatesWithDeferredJoin;
use ResolvesSortSpec;
/**
* ID로 실행 이력을 찾습니다.
*
* @param int $id 이력 ID
* @param int $id 이력 ID
* @return ScheduleHistory|null 찾은 이력 모델 또는 null
*/
public function findById(int $id): ?ScheduleHistory
@@ -23,7 +28,7 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
/**
* 새로운 실행 이력을 생성합니다.
*
* @param array $data 이력 생성 데이터
* @param array $data 이력 생성 데이터
* @return ScheduleHistory 생성된 이력 모델
*/
public function create(array $data): ScheduleHistory
@@ -34,8 +39,8 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
/**
* 기존 실행 이력을 업데이트합니다.
*
* @param ScheduleHistory $history 업데이트할 이력 모델
* @param array $data 업데이트할 데이터
* @param ScheduleHistory $history 업데이트할 이력 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(ScheduleHistory $history, array $data): bool
@@ -46,7 +51,7 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
/**
* 실행 이력을 삭제합니다.
*
* @param ScheduleHistory $history 삭제할 이력 모델
* @param ScheduleHistory $history 삭제할 이력 모델
* @return bool 삭제 성공 여부
*/
public function delete(ScheduleHistory $history): bool
@@ -57,8 +62,8 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
/**
* 특정 스케줄의 실행 이력을 페이지네이션하여 조회합니다.
*
* @param int $scheduleId 스케줄 ID
* @param array $filters 필터 조건 배열
* @param int $scheduleId 스케줄 ID
* @param array $filters 필터 조건 배열
* @return LengthAwarePaginator 페이지네이션된 이력 목록
*/
public function getPaginatedByScheduleId(int $scheduleId, array $filters = []): LengthAwarePaginator
@@ -67,40 +72,50 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
->where('schedule_id', $scheduleId);
// 상태 필터
if (!empty($filters['status'])) {
if (! empty($filters['status'])) {
$query->where('status', $filters['status']);
}
// 트리거 유형 필터
if (!empty($filters['trigger_type'])) {
if (! empty($filters['trigger_type'])) {
$query->where('trigger_type', $filters['trigger_type']);
}
// 날짜 필터
if (!empty($filters['started_from'])) {
if (! empty($filters['started_from'])) {
$query->whereDate('started_at', '>=', $filters['started_from']);
}
if (!empty($filters['started_to'])) {
if (! empty($filters['started_to'])) {
$query->whereDate('started_at', '<=', $filters['started_to']);
}
// 정렬 적용
$sortBy = $filters['sort_by'] ?? 'started_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
// 정렬 — 요청 값은 허용 목록으로만 해석한다.
// 허용 집합은 ScheduleHistoryListRequest 의 `in:` 규칙과 동일해야 한다. 저장소 목록이
// 그보다 좁으면 게이트를 통과한 정렬이 조용히 기본값으로 되돌아간다 (종료시각/소요시간).
$sort = $this->resolveSortSpec(
$filters,
['started_at', 'ended_at', 'duration', 'status'],
'started_at'
);
// 페이지네이션 적용
$perPage = $filters['per_page'] ?? 15;
$perPage = (int) ($filters['per_page'] ?? 15);
return $query->paginate($perPage);
// 실행 이력은 계속 쌓이며 출력/에러 메시지를 그대로 노출하므로, 컬럼은 좁히지 않고
// 지연 조인으로 넓은 컬럼을 읽는 행 수만 이번 페이지 분량으로 고정한다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: $sort,
perPage: $perPage,
);
}
/**
* 특정 스케줄의 최근 실행 이력을 조회합니다.
*
* @param int $scheduleId 스케줄 ID
* @param int $limit 조회 개수
* @param int $scheduleId 스케줄 ID
* @param int $limit 조회 개수
* @return Collection 최근 이력 컬렉션
*/
public function getRecentByScheduleId(int $scheduleId, int $limit = 10): Collection
@@ -115,7 +130,7 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
/**
* 여러 이력을 일괄 삭제합니다.
*
* @param array $ids 이력 ID 배열
* @param array $ids 이력 ID 배열
* @return int 삭제된 레코드 수
*/
public function bulkDelete(array $ids): int
@@ -126,7 +141,7 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
/**
* 특정 스케줄의 모든 이력을 삭제합니다.
*
* @param int $scheduleId 스케줄 ID
* @param int $scheduleId 스케줄 ID
* @return int 삭제된 레코드 수
*/
public function deleteByScheduleId(int $scheduleId): int
@@ -137,7 +152,7 @@ class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
/**
* 특정 기간 이전의 이력을 삭제합니다.
*
* @param int $days 보관 기간 (일)
* @param int $days 보관 기간 (일)
* @return int 삭제된 레코드 수
*/
public function deleteOlderThan(int $days): int
+44 -29
View File
@@ -3,12 +3,13 @@
namespace App\Repositories;
use App\Contracts\Repositories\ScheduleRepositoryInterface;
use App\Helpers\PermissionHelper;
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;
@@ -16,16 +17,29 @@ 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
* @param int $id 스케줄 ID
* @return Schedule|null 찾은 스케줄 모델 또는 null
*/
public function findById(int $id): ?Schedule
@@ -36,7 +50,7 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 새로운 스케줄을 생성합니다.
*
* @param array $data 스케줄 생성 데이터
* @param array $data 스케줄 생성 데이터
* @return Schedule 생성된 스케줄 모델
*/
public function create(array $data): Schedule
@@ -47,8 +61,8 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 기존 스케줄을 업데이트합니다.
*
* @param Schedule $schedule 업데이트할 스케줄 모델
* @param array $data 업데이트할 데이터
* @param Schedule $schedule 업데이트할 스케줄 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Schedule $schedule, array $data): bool
@@ -59,7 +73,7 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 스케줄을 삭제합니다.
*
* @param Schedule $schedule 삭제할 스케줄 모델
* @param Schedule $schedule 삭제할 스케줄 모델
* @return bool 삭제 성공 여부
*/
public function delete(Schedule $schedule): bool
@@ -80,7 +94,7 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 필터링 및 페이지네이션이 적용된 스케줄 목록을 조회합니다.
*
* @param array $filters 필터 조건 배열
* @param array $filters 필터 조건 배열
* @return LengthAwarePaginator 페이지네이션된 스케줄 목록
*/
public function getPaginatedSchedules(array $filters = []): LengthAwarePaginator
@@ -93,33 +107,34 @@ class ScheduleRepository implements ScheduleRepositoryInterface
// 필터 조건 적용
$this->applyFilters($query, $filters);
// 정렬 적용
$sortBy = $filters['sort_by'] ?? 'created_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
// 정렬 적용 (허용 컬럼 화이트리스트로 해석)
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 적용할 필터 조건 배열
* @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'])) {
if (! empty($filters['filters']) && is_array($filters['filters'])) {
$this->applyMultipleSearchFilters($query, $filters['filters'], self::SEARCHABLE_FIELDS);
}
// 타입 필터
if (!empty($filters['type'])) {
if (! empty($filters['type'])) {
$type = ScheduleType::tryFrom($filters['type']);
if ($type) {
$query->where('type', $type);
@@ -127,7 +142,7 @@ class ScheduleRepository implements ScheduleRepositoryInterface
}
// 주기 필터
if (!empty($filters['frequency'])) {
if (! empty($filters['frequency'])) {
$frequency = ScheduleFrequency::tryFrom($filters['frequency']);
if ($frequency) {
$query->where('frequency', $frequency);
@@ -135,7 +150,7 @@ class ScheduleRepository implements ScheduleRepositoryInterface
}
// 상태 필터
if (!empty($filters['status'])) {
if (! empty($filters['status'])) {
if ($filters['status'] === 'active') {
$query->where('is_active', true);
} elseif ($filters['status'] === 'inactive') {
@@ -144,7 +159,7 @@ class ScheduleRepository implements ScheduleRepositoryInterface
}
// 마지막 실행 결과 필터
if (!empty($filters['last_result'])) {
if (! empty($filters['last_result'])) {
$result = ScheduleResultStatus::tryFrom($filters['last_result']);
if ($result) {
$query->where('last_result', $result);
@@ -162,10 +177,10 @@ class ScheduleRepository implements ScheduleRepositoryInterface
}
// 확장 타입 필터
if (!empty($filters['extension_type'])) {
if (! empty($filters['extension_type'])) {
$query->where('extension_type', $filters['extension_type']);
if (!empty($filters['extension_identifier'])) {
if (! empty($filters['extension_identifier'])) {
$query->where('extension_identifier', $filters['extension_identifier']);
}
}
@@ -177,17 +192,17 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 날짜 필터를 적용합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param array $filters 필터 조건 배열
* @param Builder $query Eloquent 쿼리 빌더
* @param array $filters 필터 조건 배열
* @return void
*/
private function applyDateFilters(Builder $query, array $filters): void
{
if (!empty($filters['created_from'])) {
if (! empty($filters['created_from'])) {
$query->whereDate('created_at', '>=', $filters['created_from']);
}
if (!empty($filters['created_to'])) {
if (! empty($filters['created_to'])) {
$query->whereDate('created_at', '<=', $filters['created_to']);
}
}
@@ -233,8 +248,8 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 여러 스케줄의 상태를 일괄 업데이트합니다.
*
* @param array $ids 스케줄 ID 배열
* @param bool $isActive 활성화 여부
* @param array $ids 스케줄 ID 배열
* @param bool $isActive 활성화 여부
* @return int 업데이트된 레코드 수
*/
public function bulkUpdateStatus(array $ids, bool $isActive): int
@@ -245,7 +260,7 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 여러 스케줄을 일괄 삭제합니다.
*
* @param array $ids 스케줄 ID 배열
* @param array $ids 스케줄 ID 배열
* @return int 삭제된 레코드 수
*/
public function bulkDelete(array $ids): int
@@ -256,13 +271,13 @@ class ScheduleRepository implements ScheduleRepositoryInterface
/**
* 스케줄을 복제합니다.
*
* @param Schedule $schedule 복제할 스케줄
* @param Schedule $schedule 복제할 스케줄
* @return Schedule 복제된 스케줄
*/
public function duplicate(Schedule $schedule): Schedule
{
$newSchedule = $schedule->replicate();
$newSchedule->name = $schedule->name . ' (' . __('schedule.copy') . ')';
$newSchedule->name = $schedule->name.' ('.__('schedule.copy').')';
$newSchedule->is_active = false;
$newSchedule->last_result = ScheduleResultStatus::Never;
$newSchedule->last_run_at = null;
+19 -8
View File
@@ -6,6 +6,8 @@ use App\Contracts\Repositories\UserRepositoryInterface;
use App\Helpers\PermissionHelper;
use App\Models\User;
use App\Repositories\Concerns\HasMultipleSearchFilters;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
@@ -15,12 +17,19 @@ use Laravel\Sanctum\PersonalAccessToken;
class UserRepository implements UserRepositoryInterface
{
use HasMultipleSearchFilters;
use PaginatesWithDeferredJoin;
use ResolvesSortSpec;
/**
* 검색 가능한 필드 목록
*/
private const SEARCHABLE_FIELDS = ['name', 'email'];
/**
* 허용 정렬 컬럼 (UserListRequest 와 동일 집합)
*/
private const SORTABLE_COLUMNS = ['created_at', 'name', 'email', 'last_login_at'];
/**
* 이메일로 사용자를 찾습니다.
*
@@ -100,21 +109,23 @@ class UserRepository implements UserRepositoryInterface
// 권한 스코프 필터링
PermissionHelper::applyPermissionScope($query, 'core.users.read');
// roles 관계 eager loading
$query->with('roles');
// 검색 조건 적용
$this->applyFilters($query, $filters);
// 정렬 적용
$sortBy = $filters['sort_by'] ?? 'created_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
// 정렬 적용 (허용 컬럼 화이트리스트로 해석)
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'created_at');
// 페이지네이션 적용
$perPage = $filters['per_page'] ?? 15;
return $query->paginate($perPage);
// 지연 조인: inner 는 id 만 훑고 roles eager loading 은 해당 페이지에만 적용된다
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: $sort,
perPage: $perPage,
relations: ['roles'],
);
}
/**