Files
Gnuboard7/app/Console/Commands/Search/SearchIndexCommand.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

195 lines
6.9 KiB
PHP

<?php
namespace App\Console\Commands\Search;
use App\Console\Commands\Traits\HasUnifiedConfirm;
use App\Enums\SearchIndexStatus;
use App\Search\DTO\SearchIndexHealth;
use App\Search\SearchIndexMaintenanceManager;
use Illuminate\Console\Command;
/**
* 검색 인덱스 점검·재생성 커맨드
*
* 인덱스는 있는데 내용이 색인되지 않아 검색이 조용히 0건을 돌려주는 상태를 검출하고,
* 운영자가 선택하면 재생성합니다. 이 상태는 예외도 로그도 남기지 않으므로
* "원래 검색이 안 되는 줄" 알고 지나가기 쉽습니다.
*
* 점검 방법은 **활성 Scout 엔진의 유지보수기**가 정합니다. 확장이 자체 검색 엔진을
* 등록하면서 유지보수기를 함께 등록하면 이 커맨드가 그대로 그 엔진을 다룹니다
* (`core.search.index_maintainers` 필터 훅).
*
* 사용 예시:
* php artisan search:index # 활성 엔진의 인덱스 점검 (읽기 전용)
* php artisan search:index --repair # 색인 누락 인덱스 재생성
* php artisan search:index --filter=table=pages # 엔진별 필터 전달
* php artisan search:index --json # 기계 판독용 출력
*/
class SearchIndexCommand extends Command
{
use HasUnifiedConfirm;
protected $signature = 'search:index
{--repair : 색인이 누락된 인덱스를 재생성 (미지정 시 점검만)}
{--filter=* : 엔진별 필터 (key=value 형태, 다중 지정 가능. FULLTEXT: table, index, samples)}
{--json : 기계 판독용 JSON 출력}';
protected $description = '활성 검색 엔진의 인덱스가 실제로 내용을 색인하고 있는지 점검하고, 누락 시 재생성합니다';
/**
* 커맨드를 실행합니다.
*
* @param SearchIndexMaintenanceManager $manager 검색 인덱스 유지보수 진입점
* @return int 종료 코드 (색인 누락 잔존 시 1)
*/
public function handle(SearchIndexMaintenanceManager $manager): int
{
$driver = $manager->driver();
$filters = $this->parseFilters();
if (! $manager->hasMaintainer()) {
$this->components->warn(__('search.index.no_maintainer', ['driver' => $driver]));
return self::SUCCESS;
}
if (($reason = $manager->unavailableReason()) !== null) {
$this->components->warn($reason);
return self::SUCCESS;
}
$results = $manager->inspect($filters);
if ($results === []) {
$this->components->warn(__('search.index.no_targets', ['driver' => $driver]));
return self::SUCCESS;
}
$report = null;
if ($this->option('repair')) {
$targets = array_values(array_filter($results, fn (SearchIndexHealth $h) => $h->needsRebuild()));
if ($targets !== [] && $this->confirmRebuild($targets)) {
$report = $manager->repairStale($filters);
$results = $manager->inspect($filters);
}
}
if ($this->option('json')) {
$this->line((string) json_encode([
'driver' => $driver,
'results' => array_map(fn (SearchIndexHealth $h) => $h->toArray(), $results),
'repair' => $report?->toArray(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
} else {
$this->render($driver, $results, $report?->summary());
}
$remaining = array_filter($results, fn (SearchIndexHealth $h) => $h->needsRebuild());
return ($remaining === [] && ($report === null || $report->failed === [])) ? self::SUCCESS : self::FAILURE;
}
/**
* `--filter=key=value` 옵션을 연관 배열로 해석합니다.
*
* @return array<string, string>
*/
private function parseFilters(): array
{
$filters = [];
foreach ((array) $this->option('filter') as $raw) {
if (! is_string($raw) || ! str_contains($raw, '=')) {
continue;
}
[$key, $value] = explode('=', $raw, 2);
$key = trim($key);
if ($key !== '') {
$filters[$key] = trim($value);
}
}
return $filters;
}
/**
* 재생성 대상을 보여 주고 진행 여부를 확인합니다.
*
* @param array<int, SearchIndexHealth> $targets 재생성 대상
* @return bool 진행 여부
*/
private function confirmRebuild(array $targets): bool
{
$this->newLine();
$this->components->info(__('search.index.rebuild_targets', ['count' => count($targets)]));
foreach ($targets as $target) {
$this->line(' - '.$target->identifier.' ('.$target->measurement.')');
}
$this->components->warn(__('search.index.rebuild_cost_warning'));
if ($this->unifiedConfirm(__('search.index.rebuild_confirm'), true)) {
return true;
}
$this->components->info(__('search.index.rebuild_skipped'));
return false;
}
/**
* 판정 결과를 표로 출력합니다.
*
* @param string $driver 드라이버명
* @param array<int, SearchIndexHealth> $results 판정 결과
* @param string|null $repairSummary 재생성 요약 (수행했을 때만)
* @return void
*/
private function render(string $driver, array $results, ?string $repairSummary): void
{
$rows = array_map(fn (SearchIndexHealth $health) => [
$health->identifier,
'<fg='.$health->status->consoleColor().'>'.$health->status->label().'</>',
$health->measurement,
], $results);
$this->newLine();
$this->line(' '.__('search.index.driver_label', ['driver' => $driver]));
$this->table([__('search.index.col.index'), __('search.index.col.status'), __('search.index.col.measurement')], $rows);
$counts = [];
foreach (SearchIndexStatus::cases() as $case) {
$counts[$case->value] = count(array_filter($results, fn (SearchIndexHealth $h) => $h->status === $case));
}
$this->line(' '.__('search.index.counts', [
'healthy' => $counts[SearchIndexStatus::Healthy->value],
'degraded' => $counts[SearchIndexStatus::Degraded->value],
'stale' => $counts[SearchIndexStatus::Stale->value],
'skipped' => $counts[SearchIndexStatus::Skipped->value],
'total' => count($results),
]));
if ($repairSummary !== null) {
$this->newLine();
$this->components->info($repairSummary);
}
if ($counts[SearchIndexStatus::Stale->value] > 0 && ! $this->option('repair')) {
$this->newLine();
$this->components->warn(__('search.index.stale_hint'));
}
if ($counts[SearchIndexStatus::Degraded->value] > 0) {
$this->line(' <comment>'.__('search.index.degraded_hint').'</comment>');
}
}
}