feat(api-docs): API 레퍼런스 문서 전면화 — 추출 파이프라인·전 대상 문서화·audit 강제

코드에만 존재하던 REST API 계약(약 663 엔드포인트)을 코어/확장 책임별로
분리된 마크다운 레퍼런스로 전면 문서화한다. 674개 규모에서 수기 문서는
반드시 drift 하므로 "코드 추출 → 스캐폴딩 → 사람이 서술 채움 → 하네스가
커버리지 강제" 하이브리드로 구성했다.

추출 파이프라인 (app/Support/ApiDoc):
- ApiRouteInventory / FormRequestIntrospector / ApiEndpointProbe(실측 HTTP) /
 ResponseSchemaInferrer / ApiDocScaffolder / ColumnCommentResolver /
 ResourceFieldDescriber / ParameterDescriber
- api:docgen 커맨드(--scope/--seed/--check/--dry-run/--base-url/--user) +
 응답/파라미터 in-place 백필 커맨드 2종(재생성 없이 TODO 셀만 치환, 멱등)
- ApiDocSampleSeeder 계약 + 코어/확장 시더로 실측용 완전 샘플 멱등 생성

문서화 (실측 기반, GET read-only 실호출):
- 코어 291엔드포인트 35파일(docs/backend/api) + 규정 docs/backend/api-documentation.md
- 확장: ecommerce(231)·board(80)·page(17)·hello_module(2)·pay_kginicis(22)·
 gdpr(15)·ckeditor5(2)·marketing(2)·verification_kginicis(1)
- 표준 4구성(헤더·요청 파라미터·응답 필드·에러 표) + 엔드포인트 용도 서술
- 파라미터 용도·응답 필드 설명 셀 전수 채움(도메인 지식 수기)

하네스:
- audit 룰 api-doc-coverage — API 표면(라우트/컨트롤러/FormRequest/Resource)
 변경 시 대응 문서 미동반이면 차단. 전 대상 문서 완비로 error 승격
- file-rules 리마인더(컨트롤러/라우트 편집 시), coverage.json, dev-dashboard 카드
- docs/backend/routing.md 확장 공개 API URL 스킴 정정(/api/modules|plugins/{id})
- /AGENTS.md/docs-index 동기
This commit is contained in:
HeuJung committed 2026-07-08 18:22:33 +09:00
1 parent 49b21e788c
commit 70452745c4
131 files changed
+32105 -21

No files matched your search

+374
View File
@@ -0,0 +1,374 @@
<?php
namespace App\Support\ApiDoc;
use App\Contracts\ApiDoc\ApiDocSampleSeeder;
use App\Models\ActivityLog;
use App\Models\LanguagePack;
use App\Models\Menu;
use App\Models\NotificationDefinition;
use App\Models\NotificationLog;
use App\Models\NotificationTemplate;
use App\Models\Permission;
use App\Models\Role;
use App\Models\Schedule;
use App\Models\User;
/**
* API 문서 실측용 완전 샘플 데이터 서비스
*
* 각 API 도메인의 대표 엔티티에 모든 필드가 채워진 완전한 샘플 레코드를
* 멱등하게 생성하고, docgen 이 상세 GET 실측에 사용할 도메인별 대표 route key
* 맵을 제공합니다. 개발 환경 전용 — 생성된 샘플은 개발 DB 에 남습니다.
*/
class ApiDocSampleService implements ApiDocSampleSeeder
{
/**
* @var string 샘플 레코드 식별용 마커 (이메일/식별자 prefix)
*/
private const MARKER = 'apidoc-sample';
/**
* 도메인별 완전 샘플을 멱등 생성하고 대표 route key 맵을 반환합니다.
*
* @return array<string, array{model: class-string, key: string, value: string}> 도메인 => 대표 레코드 정보
*/
public function seed(): array
{
$map = [];
// permissions → roles → users 순: user 가 role 을, role 이 permission 을 참조
$map['permissions'] = $this->seedPermission();
$map['roles'] = $this->seedRole();
$map['users'] = $this->seedUser();
$map['menus'] = $this->seedMenu();
$map['notification-definitions'] = $this->seedNotificationDefinition();
$map['schedules'] = $this->seedSchedule();
$map['activity-logs'] = $this->seedActivityLog();
$map['language-packs'] = $this->seedLanguagePack();
$map['notification-logs'] = $this->seedNotificationLog();
$map['notification-templates'] = $this->seedNotificationTemplate();
return array_filter($map);
}
/**
* 완전한 사용자 샘플을 생성하고 roles 관계를 연결합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedUser(): array
{
$user = User::query()->where('email', self::MARKER.'-user@example.com')->first();
if (! $user) {
$user = User::factory()->complete()->create([
'name' => 'API 문서 샘플 사용자',
'email' => self::MARKER.'-user@example.com',
]);
$role = Role::query()->where('identifier', self::MARKER.'-role')->first()
?? Role::query()->where('identifier', 'admin')->first()
?? Role::query()->first()
?? Role::factory()->create(['identifier' => self::MARKER.'-role-fallback']);
$user->roles()->syncWithoutDetaching([$role->id]);
}
return ['model' => User::class, 'key' => $user->getRouteKeyName(), 'value' => (string) $user->getRouteKey()];
}
/**
* 완전한 역할 샘플을 생성하고 permissions 관계를 연결합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedRole(): array
{
$role = Role::query()->where('identifier', self::MARKER.'-role')->first();
if (! $role) {
$role = Role::factory()->create([
'identifier' => self::MARKER.'-role',
'name' => ['ko' => 'API 문서 샘플 역할', 'en' => 'API Doc Sample Role'],
'description' => ['ko' => '문서 실측용 역할', 'en' => 'Sample role for API docs'],
'is_active' => true,
]);
$permissionIds = Permission::query()->limit(3)->pluck('id')->all();
if ($permissionIds !== []) {
$role->permissions()->syncWithoutDetaching($permissionIds);
}
}
return ['model' => Role::class, 'key' => $role->getRouteKeyName(), 'value' => (string) $role->getRouteKey()];
}
/**
* 완전한 권한 샘플(부모-자식 계층)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedPermission(): array
{
$permission = Permission::query()->where('identifier', self::MARKER.'.parent')->first();
if (! $permission) {
$permission = Permission::factory()->create([
'identifier' => self::MARKER.'.parent',
'name' => ['ko' => 'API 문서 샘플 권한', 'en' => 'API Doc Sample Permission'],
'description' => ['ko' => '문서 실측용 권한', 'en' => 'Sample permission'],
'type' => 'admin',
]);
Permission::factory()->create([
'parent_id' => $permission->id,
'identifier' => self::MARKER.'.child',
'name' => ['ko' => '하위 권한', 'en' => 'Child Permission'],
'type' => 'admin',
]);
}
return ['model' => Permission::class, 'key' => $permission->getRouteKeyName(), 'value' => (string) $permission->getRouteKey()];
}
/**
* 완전한 메뉴 샘플(부모-자식)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedMenu(): array
{
$menu = Menu::query()->where('slug', self::MARKER.'-menu')->first();
if (! $menu) {
$creator = User::query()->where('email', self::MARKER.'-user@example.com')->first();
$menu = Menu::factory()->create([
'name' => ['ko' => 'API 문서 샘플 메뉴', 'en' => 'API Doc Sample Menu'],
'slug' => self::MARKER.'-menu',
'url' => '/admin/apidoc-sample',
'icon' => 'fas fa-book',
'is_active' => true,
'created_by' => $creator?->id,
]);
Menu::factory()->create([
'name' => ['ko' => '하위 메뉴', 'en' => 'Child Menu'],
'slug' => self::MARKER.'-menu-child',
'parent_id' => $menu->id,
'created_by' => $creator?->id,
]);
}
return ['model' => Menu::class, 'key' => $menu->getRouteKeyName(), 'value' => (string) $menu->getRouteKey()];
}
/**
* 완전한 알림 정의 샘플(템플릿 포함)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedNotificationDefinition(): array
{
$definition = NotificationDefinition::query()->where('type', self::MARKER.'.event')->first();
if (! $definition) {
$definition = NotificationDefinition::factory()->create([
'type' => self::MARKER.'.event',
'name' => ['ko' => 'API 문서 샘플 알림', 'en' => 'API Doc Sample Notification'],
'description' => ['ko' => '문서 실측용 알림 정의', 'en' => 'Sample notification'],
'channels' => ['database', 'mail'],
'is_active' => true,
]);
}
return ['model' => NotificationDefinition::class, 'key' => $definition->getRouteKeyName(), 'value' => (string) $definition->getRouteKey()];
}
/**
* 완전한 스케줄 샘플(실행 이력 포함)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedSchedule(): array
{
$schedule = Schedule::query()->where('name', 'API 문서 샘플 스케줄')->first();
if (! $schedule) {
$creator = $this->sampleUser();
$schedule = Schedule::create([
'name' => 'API 문서 샘플 스케줄',
'description' => '문서 실측용 스케줄',
'type' => 'artisan',
'command' => 'cache:clear',
'expression' => '0 3 * * *',
'frequency' => 'daily',
'without_overlapping' => true,
'run_in_maintenance' => false,
'timeout' => 300,
'is_active' => true,
'last_result' => 'success',
'last_run_at' => now()->subDay(),
'next_run_at' => now()->addDay(),
'created_by' => $creator?->id,
]);
}
return ['model' => Schedule::class, 'key' => $schedule->getRouteKeyName(), 'value' => (string) $schedule->getRouteKey()];
}
/**
* 완전한 활동 로그 샘플(actor + changes 포함)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedActivityLog(): array
{
$log = ActivityLog::query()->where('description_key', 'apidoc.sample.action')->first();
if (! $log) {
$user = $this->sampleUser();
$log = ActivityLog::create([
'log_type' => 'admin',
'loggable_type' => User::class,
'loggable_id' => $user?->id,
'user_id' => $user?->id,
'action' => 'user.update',
'description_key' => 'apidoc.sample.action',
'description_params' => ['name' => 'API 문서 샘플'],
'properties' => ['source' => 'apidoc'],
'changes' => ['status' => ['old' => 'inactive', 'new' => 'active']],
'ip_address' => '127.0.0.1',
'user_agent' => 'ApiDocgen/1.0',
'created_at' => now(),
]);
}
return ['model' => ActivityLog::class, 'key' => $log->getRouteKeyName(), 'value' => (string) $log->getRouteKey()];
}
/**
* 완전한 언어팩 샘플(manifest 채움)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedLanguagePack(): array
{
$pack = LanguagePack::query()->where('identifier', 'apidoc-sample-lang')->first();
if (! $pack) {
$installer = $this->sampleUser();
$pack = LanguagePack::create([
'identifier' => 'apidoc-sample-lang',
'vendor' => 'apidoc',
'scope' => 'core',
'target_identifier' => null,
'locale' => 'fr',
'locale_name' => 'French',
'locale_native_name' => 'Français',
'text_direction' => 'ltr',
'version' => '1.0.0',
'latest_version' => '1.0.0',
'license' => 'MIT',
'description' => ['ko' => '문서 실측용 언어팩', 'en' => 'Sample language pack'],
'status' => 'active',
'is_protected' => false,
'manifest' => [
'name' => ['ko' => 'API 문서 샘플 언어팩', 'en' => 'API Doc Sample Pack'],
'version' => '1.0.0',
'locale' => 'fr',
],
'source_type' => 'bundled',
'installed_by' => $installer?->id,
'installed_at' => now()->subDays(3),
'activated_at' => now()->subDays(3),
]);
}
return ['model' => LanguagePack::class, 'key' => $pack->getRouteKeyName(), 'value' => (string) $pack->getRouteKey()];
}
/**
* 완전한 알림 로그 샘플(수신자/발신자 포함)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedNotificationLog(): array
{
$log = NotificationLog::query()->where('notification_type', 'apidoc.sample.event')->first();
if (! $log) {
$user = $this->sampleUser();
$log = NotificationLog::create([
'channel' => 'mail',
'notification_type' => 'apidoc.sample.event',
'extension_type' => 'core',
'extension_identifier' => '',
'recipient_user_id' => $user?->id,
'recipient_identifier' => $user?->email,
'recipient_name' => $user?->name,
'sender_user_id' => $user?->id,
'subject' => 'API 문서 샘플 알림',
'body' => '문서 실측용 알림 본문입니다.',
'status' => 'sent',
'error_message' => null,
'source' => 'apidoc',
'sent_at' => now()->subHour(),
]);
}
return ['model' => NotificationLog::class, 'key' => $log->getRouteKeyName(), 'value' => (string) $log->getRouteKey()];
}
/**
* 완전한 알림 템플릿 샘플(정의 연결)을 생성합니다.
*
* @return array{model: class-string, key: string, value: string} 대표 레코드 정보
*/
private function seedNotificationTemplate(): array
{
$this->seedNotificationDefinition();
$definitionId = NotificationDefinition::query()->where('type', self::MARKER.'.event')->value('id');
$template = NotificationTemplate::query()
->where('definition_id', $definitionId)
->where('channel', 'mail')
->first();
if (! $template && $definitionId) {
$updater = $this->sampleUser();
$template = NotificationTemplate::create([
'definition_id' => $definitionId,
'channel' => 'mail',
'subject' => 'API 문서 샘플 템플릿 제목',
'body' => '안녕하세요 {{name}} 님, 문서 실측용 본문입니다.',
'click_url' => '/admin/apidoc-sample',
'recipients' => [['type' => 'role', 'value' => 'admin']],
'is_active' => true,
'is_default' => false,
'updated_by' => $updater?->id,
]);
}
if (! $template) {
return [];
}
return ['model' => NotificationTemplate::class, 'key' => $template->getRouteKeyName(), 'value' => (string) $template->getRouteKey()];
}
/**
* 시드된 완전 샘플 사용자를 반환합니다 (연관 엔티티의 소유자/actor 용).
*
* @return User|null 샘플 사용자 (없으면 null)
*/
private function sampleUser(): ?User
{
return User::query()->where('email', self::MARKER.'-user@example.com')->first();
}
}
+357
View File
@@ -0,0 +1,357 @@
<?php
namespace App\Support\ApiDoc;
use Illuminate\Support\Str;
/**
* API 문서 스캐폴딩 생성기
*
* 라우트 메타데이터 + 요청 파라미터 + 실측 응답 스키마를 표준 마크다운 포맷으로
* 조립합니다. @generated 블록 경계로 기존 문서의 사람 서술을 보존(idempotent)합니다.
*/
class ApiDocScaffolder
{
/**
* @var string 생성 블록 시작 마커 접두
*/
private const GEN_START = '<!-- @generated:start:';
/**
* @var string 생성 블록 종료 마커
*/
private const GEN_END = '<!-- @generated:end -->';
/**
* @param ResourceFieldDescriber $fieldDescriber accessor/computed 필드 설명기
* @param ParameterDescriber $paramDescriber 공통 요청 파라미터 설명기
*/
public function __construct(
private readonly ResourceFieldDescriber $fieldDescriber = new ResourceFieldDescriber,
private readonly ParameterDescriber $paramDescriber = new ParameterDescriber
) {}
/**
* 단일 엔드포인트의 마크다운 섹션을 생성합니다.
*
* @param array<string, mixed> $route 라우트 메타데이터
* @param array<string, mixed> $request FormRequest 분석 결과
* @param array<string, mixed>|null $schema 실측 응답 스키마 (null=실측 안 됨)
* @param array<string, mixed> $probeMeta 실측 메타 (status, skipped_reason)
* @param array<string, string> $commentMap 컬럼명 => 주석 (필드 설명 기본값)
* @return string 마크다운 섹션
*/
public function endpointSection(array $route, array $request, ?array $schema, array $probeMeta, array $commentMap = []): string
{
$name = $route['name'] ?: '(unnamed)';
$heading = "### {$route['method']} {$route['uri']}";
$genKey = $name;
$lines = [];
$lines[] = $heading;
$lines[] = self::GEN_START.$genKey.' -->';
$lines[] = "- **라우트명**: `{$name}`";
if ($route['controller']) {
$lines[] = "- **컨트롤러**: `{$route['controller']}@{$route['controller_method']}`";
}
$lines[] = '- **인증/권한**: '.$this->authLine($route);
$lines[] = '';
$lines[] = '**요청 파라미터**';
$lines[] = '';
$lines[] = $this->requestParamTable($route, $request);
if (! empty($request['hook_filters'])) {
$hooks = implode('`, `', $request['hook_filters']);
$lines[] = '';
$lines[] = "> 이 엔드포인트는 확장이 파라미터를 추가할 수 있습니다 (`{$hooks}`).";
}
$lines[] = '';
$lines[] = '**응답 필드** (`data` 내부)';
$lines[] = '';
$lines[] = $this->responseFieldTable($schema, $probeMeta, $commentMap);
$lines[] = '';
$lines[] = '**에러 응답**';
$lines[] = '';
$lines[] = $this->errorTable($route, $request);
$lines[] = '';
$lines[] = self::GEN_END;
$lines[] = '';
$lines[] = '**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->';
$lines[] = '';
return implode("\n", $lines)."\n";
}
/**
* 인증/권한 라인을 구성합니다.
*
* @param array<string, mixed> $route 라우트 메타데이터
* @return string 인증/권한 설명
*/
private function authLine(array $route): string
{
$mw = $route['middleware'] ?? [];
$parts = [];
// optional.sanctum(회원/비회원 모두 접근 — Bearer 토큰 있으면 인증, 없으면 guest)은
// auth:sanctum(인증 필수)과 계약이 다르므로 별도 표기한다. 'sanctum' 부분일치가
// optional.sanctum 까지 auth:sanctum 으로 오표기하던 회귀를 막는다.
if ($this->hasMiddleware($mw, 'optional.sanctum')) {
$parts[] = '`optional.sanctum` (선택적 인증: 회원/비회원 모두 접근)';
} elseif ($this->hasMiddleware($mw, 'sanctum')) {
$parts[] = '`auth:sanctum`';
}
if ($this->hasMiddleware($mw, 'AdminMiddleware')) {
$parts[] = '`admin`';
}
if ($route['permission']) {
$parts[] = "`permission:{$route['permission']}`";
}
return $parts === [] ? '공개 (인증 불필요)' : implode(' + ', $parts);
}
/**
* 미들웨어 목록에 특정 토큰이 포함되는지 확인합니다.
*
* @param array<int, string> $middleware 미들웨어 목록
* @param string $needle 검색 토큰
* @return bool 포함 여부
*/
private function hasMiddleware(array $middleware, string $needle): bool
{
foreach ($middleware as $mw) {
if (Str::contains($mw, $needle)) {
return true;
}
}
return false;
}
/**
* 요청 파라미터 표를 생성합니다.
*
* @param array<string, mixed> $route 라우트 메타데이터
* @param array<string, mixed> $request FormRequest 분석 결과
* @return string 마크다운 표
*/
private function requestParamTable(array $route, array $request): string
{
$rows = [];
foreach ($route['path_params'] as $pathParam) {
$desc = $this->paramDescriber->describe($pathParam, 'path', 'string');
$descCell = $desc !== null ? $this->escapeCell($desc) : '<!-- TODO: 용도 -->';
$rows[] = "| {$pathParam} | path | string | 예 | — | {$descCell} |";
}
$location = in_array($route['method'], ['GET', 'DELETE'], true) ? 'query' : 'body';
foreach ($request['params'] as $p) {
$required = $p['required'] ? '예' : '아니오';
$allowed = $p['allowed'] !== '' ? $p['allowed'] : '—';
$desc = $this->paramDescriber->describe($p['name'], $location, $p['type']);
$descCell = $desc !== null ? $this->escapeCell($desc) : '<!-- TODO: 용도 -->';
$rows[] = "| {$p['name']} | {$location} | {$p['type']} | {$required} | {$allowed} | {$descCell} |";
}
if ($rows === []) {
return '_요청 파라미터 없음._';
}
return "| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |\n| --- | --- | --- | --- | --- | --- |\n".implode("\n", $rows);
}
/**
* 응답 필드 표를 생성합니다.
*
* @param array<string, mixed>|null $schema 실측 응답 스키마
* @param array<string, mixed> $probeMeta 실측 메타
* @param array<string, string> $commentMap 컬럼명 => 주석 (필드 설명 기본값)
* @return string 마크다운 표 또는 실측 제외 사유
*/
private function responseFieldTable(?array $schema, array $probeMeta, array $commentMap = []): string
{
if ($schema === null) {
$reason = $probeMeta['skipped_reason'] ?? 'not-probed';
return "<!-- 실측 제외: {$reason} — 응답 필드는 사람이 작성하세요. -->";
}
$note = '';
if ($schema['shape'] === 'collection') {
$note = '_목록 응답: `data.data[]` 배열 항목의 필드'.($schema['pagination'] ? ' + `data.pagination`' : '').'._';
} elseif ($schema['shape'] === 'object') {
$note = '_단건 응답: `data` 객체의 필드._';
}
if ($schema['fields'] === []) {
return $note."\n\n<!-- 실측 응답에 필드 없음(빈 목록 등) — 데이터가 있는 상태로 재실측하거나 사람이 작성. -->";
}
$rows = [];
foreach ($schema['fields'] as $f) {
// 필드 설명 우선순위:
// 1) 리소스 계약 사전 (accessor/computed — status_label, is_owner, *_at 등)
// 2) 컬럼 주석 (한국어 comment — 테이블 실제 컬럼)
// 3) TODO (사람 보강)
// 계약 사전이 앞서는 이유: created_at 은 어느 테이블이든 "생성 일시" 이고,
// status_label 은 컬럼이 아니라 Enum label() 산물이라 주석이 없기 때문.
$desc = $this->fieldDescriber->describe($f['name'], $f['type'] ?? '')
?? ($commentMap[$f['name']] ?? null);
$descCell = $desc !== null ? $this->escapeCell($desc) : '<!-- TODO: 설명 -->';
$rows[] = "| {$f['name']} | {$f['type']} | `{$f['sample']}` | {$descCell} |";
}
$table = "| 필드 | 타입 | 실측 예시값 | 용도/설명 |\n| --- | --- | --- | --- |\n".implode("\n", $rows);
return $note !== '' ? $note."\n\n".$table : $table;
}
/**
* 에러 응답 표를 생성합니다.
*
* 라우트 메타에서 대표 에러 상태코드와 발생 조건을 자동 추론합니다.
* - 401: 인증 필수(`auth:sanctum`) 미들웨어. `optional.sanctum`(선택 인증)은 제외.
* - 403: `admin` 미들웨어 또는 `permission:` 요구 → 권한 부족 시.
* - 422: FormRequest 검증 규칙 존재 → 검증 실패 시.
* - 404: path 파라미터 존재 → 대상 리소스 미발견 시.
*
* 자동 추론은 대표 상태코드의 초안이며, 도메인 특이 에러(409 충돌·429 제한 등)는
* `@generated` 블록 밖 사람 서술에서 보강한다.
*
* @param array<string, mixed> $route 라우트 메타데이터
* @param array<string, mixed> $request FormRequest 분석 결과
* @return string 마크다운 표
*/
private function errorTable(array $route, array $request): string
{
$mw = $route['middleware'] ?? [];
$rows = [];
// 401: 인증 필수. optional.sanctum(선택 인증)은 미인증도 허용하므로 제외.
if (! $this->hasMiddleware($mw, 'optional.sanctum') && $this->hasMiddleware($mw, 'sanctum')) {
$rows[] = '| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |';
}
// 403: admin 게이트 또는 permission 요구 → 권한 부족.
if ($this->hasMiddleware($mw, 'AdminMiddleware') || ! empty($route['permission'])) {
$cond = ! empty($route['permission'])
? "요구 권한(`{$route['permission']}`)이 없는 경우"
: '관리자 권한이 없는 경우';
$rows[] = "| 403 | Forbidden | {$cond} |";
}
// 422: FormRequest 검증 규칙 존재 → 검증 실패. (훅 주입 규칙 포함 가능)
$hasValidation = ! empty($request['params']) || ! empty($request['hook_filters']);
if ($hasValidation) {
$rows[] = '| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |';
}
// 404: path 파라미터 존재 → 대상 리소스 미발견.
if (! empty($route['path_params'])) {
$rows[] = '| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |';
}
if ($rows === []) {
return '_대표 에러 없음 (공개 조회). <!-- TODO: 도메인 특이 에러가 있으면 보강 -->_';
}
return "| 상태코드 | 의미 | 발생 조건 |\n| --- | --- | --- |\n".implode("\n", $rows);
}
/**
* 마크다운 표 셀 안에서 안전하도록 파이프/개행을 이스케이프합니다.
*
* @param string $text 원본 텍스트
* @return string 이스케이프된 텍스트
*/
private function escapeCell(string $text): string
{
return str_replace(['|', "\n", "\r"], ['\\|', ' ', ''], $text);
}
/**
* 기존 문서에 새 생성 블록을 병합합니다. 사람 서술은 보존합니다.
*
* @param string|null $existing 기존 문서 내용 (null=신규)
* @param string $header 문서 헤더 (제목 + TL;DR 등)
* @param array<int, string> $sections 엔드포인트 섹션 목록 (라우트명 순)
* @param array<int, string> $sectionKeys 각 섹션의 라우트명 키
* @return string 병합된 문서 내용
*/
public function mergeDocument(?string $existing, string $header, array $sections, array $sectionKeys): string
{
if ($existing === null) {
return $header."\n".implode("\n", $sections);
}
$merged = $header."\n";
foreach ($sections as $i => $section) {
$key = $sectionKeys[$i];
$preserved = $this->extractHumanProse($existing, $key);
$merged .= $this->applyPreservedProse($section, $preserved)."\n";
}
return $merged;
}
/**
* 기존 문서에서 특정 엔드포인트의 사람 서술(생성 블록 밖)을 추출합니다.
*
* @param string $existing 기존 문서
* @param string $key 라우트명 키
* @return string|null 보존할 사람 서술 (없으면 null)
*/
private function extractHumanProse(string $existing, string $key): ?string
{
$startMarker = self::GEN_START.$key.' -->';
$startPos = strpos($existing, $startMarker);
if ($startPos === false) {
return null;
}
$endPos = strpos($existing, self::GEN_END, $startPos);
if ($endPos === false) {
return null;
}
$afterGen = substr($existing, $endPos + strlen(self::GEN_END));
// 다음 ### 헤딩 전까지가 이 엔드포인트의 사람 서술
$nextHeading = preg_match('/\n### /', $afterGen, $m, PREG_OFFSET_CAPTURE)
? $m[0][1]
: strlen($afterGen);
$prose = trim(substr($afterGen, 0, $nextHeading));
// 기본 TODO 스텁만 있으면 보존할 것 없음
if ($prose === '' || Str::contains($prose, 'TODO: 이 엔드포인트의 용도')) {
return null;
}
return $prose;
}
/**
* 새 섹션의 기본 서술 스텁을 보존된 사람 서술로 치환합니다.
*
* @param string $section 새로 생성된 섹션
* @param string|null $preserved 보존할 사람 서술
* @return string 서술이 반영된 섹션
*/
private function applyPreservedProse(string $section, ?string $preserved): string
{
if ($preserved === null) {
return $section;
}
$stub = '**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->';
return str_replace($stub, $preserved, $section);
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
namespace App\Support\ApiDoc;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Laravel\Sanctum\PersonalAccessToken;
/**
* API 엔드포인트 실측 프로브
*
* 임시 Sanctum 토큰을 발급해 실제 HTTP 요청으로 엔드포인트를 호출하고,
* 실제 응답 JSON 에서 필드 스키마(키·타입·샘플값)를 관측합니다.
* 쓰기 메서드는 기본적으로 실호출하지 않으며 GET/HEAD 만 read-only 로 실측합니다.
*/
class ApiEndpointProbe
{
/**
* @var string 실측 대상 기준 URL
*/
private string $baseUrl;
/**
* @var string|null 발급된 임시 토큰 평문
*/
private ?string $token = null;
/**
* @var string 임시 토큰 식별용 이름
*/
private string $tokenName = 'api-docgen-probe';
/**
* @param string|null $baseUrl 기준 URL (null 이면 .env 의 APP_URL 직접 사용)
*/
public function __construct(?string $baseUrl = null)
{
// config('app.url') 은 테스트 환경에서 override 될 수 있으므로(test.example.com 등),
// 실측은 .env 의 APP_URL 을 우선 신뢰한다. 명시 인자가 있으면 그것을 최우선한다.
$resolved = $baseUrl
?: (string) env('APP_URL')
?: (string) config('app.url');
$this->baseUrl = rtrim($resolved, '/');
}
/**
* 실측 기준 URL 을 반환합니다.
*
* @return string 기준 URL
*/
public function baseUrl(): string
{
return $this->baseUrl;
}
/**
* 실측용 관리자 토큰을 발급합니다.
*
* @param int|null $userId 토큰 발급 대상 사용자 ID (null 이면 첫 관리자)
* @return bool 발급 성공 여부
*/
public function authenticate(?int $userId = null): bool
{
$user = $userId
? User::find($userId)
: User::query()->orderBy('id')->first();
if (! $user) {
return false;
}
$this->cleanupTokens();
$this->token = $user->createToken($this->tokenName)->plainTextToken;
return true;
}
/**
* GET 엔드포인트를 실호출하여 응답을 관측합니다.
*
* @param string $method HTTP 메서드
* @param string $uri 라우트 URI (path 파라미터 치환 완료된 실제 경로)
* @return array{ok: bool, status: int|null, body: array<string, mixed>|null, skipped_reason: string|null}
*/
public function probe(string $method, string $uri): array
{
$method = strtoupper($method);
// 쓰기 메서드는 부수효과 위험으로 실호출하지 않는다 (정적 문서화로 대체).
if (! in_array($method, ['GET', 'HEAD'], true)) {
return ['ok' => false, 'status' => null, 'body' => null, 'skipped_reason' => 'write-method'];
}
// path 파라미터가 남아 있으면(치환 실패) 실호출 불가.
if (Str::contains($uri, '{')) {
return ['ok' => false, 'status' => null, 'body' => null, 'skipped_reason' => 'unresolved-path-param'];
}
if (! $this->token) {
return ['ok' => false, 'status' => null, 'body' => null, 'skipped_reason' => 'no-token'];
}
try {
$response = Http::withoutVerifying()
->withToken($this->token)
->acceptJson()
->timeout(15)
->get($this->baseUrl.$uri);
$json = $response->json();
return [
'ok' => $response->successful() && is_array($json),
'status' => $response->status(),
'body' => is_array($json) ? $json : null,
'skipped_reason' => null,
];
} catch (\Throwable $e) {
return ['ok' => false, 'status' => null, 'body' => null, 'skipped_reason' => 'request-failed: '.$e->getMessage()];
}
}
/**
* 발급한 임시 토큰을 정리합니다.
*/
public function cleanup(): void
{
$this->cleanupTokens();
$this->token = null;
}
/**
* 실측용 토큰 레코드를 모두 삭제합니다.
*/
private function cleanupTokens(): void
{
PersonalAccessToken::query()
->where('name', $this->tokenName)
->delete();
}
}
+442
View File
@@ -0,0 +1,442 @@
<?php
namespace App\Support\ApiDoc;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Route as RouteFacade;
use Illuminate\Support\Str;
/**
* API 라우트 인벤토리
*
* 등록된 라우트를 전수 수집하여 API 문서 생성에 필요한 메타데이터
* (메서드·URI·라우트명·소유 확장·권한·컨트롤러 액션)로 정규화합니다.
*/
class ApiRouteInventory
{
/**
* API 라우트를 전수 수집하여 정규화된 배열로 반환합니다.
*
* @param string|null $scope 범위 필터 (null=전체, 'core', 'module:{id}', 'plugin:{id}')
* @return array<int, array<string, mixed>> 정규화된 라우트 메타데이터 목록
*/
public function collect(?string $scope = null): array
{
$routes = [];
foreach (RouteFacade::getRoutes() as $route) {
/** @var Route $route */
$uri = $route->uri();
if (! Str::startsWith($uri, 'api/')) {
continue;
}
$name = $route->getName() ?? '';
$owner = $this->resolveOwner($name, $uri);
if ($scope !== null && ! $this->matchesScope($owner, $scope)) {
continue;
}
foreach ($this->normalizeRoute($route, $uri, $name, $owner) as $entry) {
$routes[] = $entry;
}
}
// route:list 는 활성 확장만 노출한다. 비활성/미설치 확장을 명시 범위로 지정하면
// (module:{id} / plugin:{id}) 등록된 라우트가 0건이 되므로, 그 확장의 번들 라우트
// 파일을 프로바이더와 동일한 prefix/name 규약으로 임시 라우터에 로드해 폴백 수집한다.
if ($routes === [] && $scope !== null && $scope !== 'core' && $scope !== 'all') {
$routes = $this->collectFromBundledFiles($scope);
}
usort($routes, fn ($a, $b) => [$a['owner']['key'], $a['uri'], $a['method']] <=> [$b['owner']['key'], $b['uri'], $b['method']]);
return $routes;
}
/**
* 하나의 라우트를 HTTP 메서드별 정규화 엔트리 배열로 변환합니다.
*
* @param Route $route 라우트 인스턴스
* @param string $uri 라우트 URI ('api/' prefix 포함)
* @param string $name 라우트명
* @param array{type: string, id: string|null, key: string} $owner 소유 주체
* @return array<int, array<string, mixed>> 정규화된 엔트리 목록
*/
private function normalizeRoute(Route $route, string $uri, string $name, array $owner): array
{
$entries = [];
$middleware = $this->gatherMiddleware($route);
foreach ($this->httpMethods($route) as $method) {
$entries[] = [
'method' => $method,
'uri' => '/'.ltrim($uri, '/'),
'name' => $name,
'owner' => $owner,
'action' => $route->getActionName(),
'controller' => $this->controllerClass($route),
'controller_method' => $this->controllerMethod($route),
'middleware' => $middleware,
'permission' => $this->resolvePermission($middleware),
'path_params' => $this->pathParams($uri),
'path_bindings' => $this->pathBindings($route),
'domain_group' => $this->domainGroup($name, $uri, $owner),
];
}
return $entries;
}
/**
* 라우트의 미들웨어 목록을 안전하게 수집합니다.
*
* `gatherMiddleware()` 는 컨트롤러 정의 미들웨어를 읽기 위해 컨트롤러를 인스턴스화한다.
* 비활성/미설치 확장은 서비스 바인딩이 부팅되지 않아 인스턴스화가 실패할 수 있으므로,
* 실패 시 라우트에 직접 부여된 정적 미들웨어(`middleware()`)로 폴백한다.
*
* @param Route $route 라우트 인스턴스
* @return array<int, string> 미들웨어 목록
*/
private function gatherMiddleware(Route $route): array
{
try {
return $route->gatherMiddleware();
} catch (\Throwable) {
return $route->middleware();
}
}
/**
* 비활성/미설치 확장의 번들 라우트 파일을 임시 라우터에 로드해 수집합니다.
*
* 프로바이더(`ModuleRouteServiceProvider`/`PluginRouteServiceProvider`)와 동일한
* prefix(`api/{modules|plugins}/{id}`)·name(`api.{modules|plugins}.{id}.`)·`api`
* 미들웨어 그룹으로 `src/routes/api.php` 를 라우터에 로드한다. `api/` 로 시작하는
* 라우트만 대상이므로 web(admin) 라우트는 자동 제외된다(그 라우트는 API 문서 대상이 아니다).
*
* 라우트 파일은 `use Illuminate\Support\Facades\Route` 로 전역 파사드에 등록하므로,
* 등록 전 라우트 이름 스냅샷을 떠서 이번 로드로 추가된 라우트만 골라낸다. 이 커맨드는
* CLI 단발 프로세스라 전역 라우트 테이블 추가가 웹 요청에 영향을 주지 않는다.
*
* @param string $scope 범위 필터 (`module:{id}` / `plugin:{id}`)
* @return array<int, array<string, mixed>> 정규화된 라우트 메타데이터 목록
*/
private function collectFromBundledFiles(string $scope): array
{
if (! preg_match('/^(module|plugin):(.+)$/', $scope, $m)) {
return [];
}
[$type, $id] = [$m[1], $m[2]];
$dir = $type === 'module' ? 'modules' : 'plugins';
$apiRouteFile = base_path("{$dir}/_bundled/{$id}/src/routes/api.php");
if (! is_file($apiRouteFile)) {
return [];
}
$urlPrefix = "api/{$dir}/{$id}";
$namePrefix = "api.{$dir}.{$id}.";
// 등록 전 스냅샷 — 이미 등록된(활성) 라우트와 이번 로드분을 구분한다.
$existing = [];
foreach (RouteFacade::getRoutes() as $route) {
/** @var Route $route */
$existing[spl_object_id($route)] = true;
}
try {
RouteFacade::prefix($urlPrefix)
->name($namePrefix)
->middleware('api')
->group($apiRouteFile);
RouteFacade::getRoutes()->refreshNameLookups();
} catch (\Throwable) {
return [];
}
$routes = [];
foreach (RouteFacade::getRoutes() as $route) {
/** @var Route $route */
if (isset($existing[spl_object_id($route)])) {
continue;
}
$uri = $route->uri();
if (! Str::startsWith($uri, 'api/')) {
continue;
}
$name = $route->getName() ?? '';
$owner = $this->resolveOwner($name, $uri);
// 폴백 대상 확장 소유로 확정되지 않으면(코어 등) 제외
if ($owner['key'] !== $scope) {
continue;
}
foreach ($this->normalizeRoute($route, $uri, $name, $owner) as $entry) {
$routes[] = $entry;
}
}
return $routes;
}
/**
* 라우트명/URI 로 소유 주체(코어/모듈/플러그인)를 판별합니다.
*
* @param string $name 라우트명
* @param string $uri 라우트 URI
* @return array{type: string, id: string|null, key: string} 소유 주체 정보
*/
private function resolveOwner(string $name, string $uri): array
{
if (preg_match('/^api\.modules\.([^.]+)\./', $name, $m) && $this->isRealExtensionId($m[1])) {
return ['type' => 'module', 'id' => $m[1], 'key' => 'module:'.$m[1]];
}
if (preg_match('/^api\.plugins\.([^.]+)\./', $name, $m) && $this->isRealExtensionId($m[1])) {
return ['type' => 'plugin', 'id' => $m[1], 'key' => 'plugin:'.$m[1]];
}
// 라우트명이 비어도 URI prefix 로 보조 판별
if (preg_match('#^api/modules/([^/{]+)/#', $uri, $m) && $this->isRealExtensionId($m[1])) {
return ['type' => 'module', 'id' => $m[1], 'key' => 'module:'.$m[1]];
}
if (preg_match('#^api/plugins/([^/{]+)/#', $uri, $m) && $this->isRealExtensionId($m[1])) {
return ['type' => 'plugin', 'id' => $m[1], 'key' => 'plugin:'.$m[1]];
}
// 코어가 제공하는 확장 메타/에셋 라우트(/api/modules/{identifier}/license,
// /api/modules/bundle.js 등)는 실제 확장 소유가 아니라 코어 소유다.
return ['type' => 'core', 'id' => null, 'key' => 'core'];
}
/**
* 세그먼트가 실제 확장 식별자인지 판별합니다 (플레이스홀더/에셋 라우트 제외).
*
* @param string $segment URI/라우트명 세그먼트
* @return bool 실제 확장 식별자 여부
*/
private function isRealExtensionId(string $segment): bool
{
// {identifier} 같은 라우트 파라미터, bundle/assets 같은 코어 에셋 라우트 제외.
// 실제 확장 식별자는 vendor-name 형태로 하이픈을 포함한다.
if (Str::startsWith($segment, '{') || in_array($segment, ['assets', 'bundle', 'bundle.js', 'bundle.css'], true)) {
return false;
}
return Str::contains($segment, '-');
}
/**
* 소유 주체가 지정된 범위 필터에 매칭되는지 확인합니다.
*
* @param array{type: string, id: string|null, key: string} $owner 소유 주체
* @param string $scope 범위 필터
* @return bool 매칭 여부
*/
private function matchesScope(array $owner, string $scope): bool
{
if ($scope === 'all') {
return true;
}
if ($scope === 'core') {
return $owner['type'] === 'core';
}
return $owner['key'] === $scope;
}
/**
* 라우트의 HTTP 메서드 목록을 반환합니다 (HEAD 제외).
*
* @param Route $route 라우트 인스턴스
* @return array<int, string> HTTP 메서드 목록
*/
private function httpMethods(Route $route): array
{
return array_values(array_filter(
$route->methods(),
fn ($m) => $m !== 'HEAD'
));
}
/**
* 컨트롤러 클래스명을 반환합니다.
*
* @param Route $route 라우트 인스턴스
* @return string|null 컨트롤러 FQCN (클로저면 null)
*/
private function controllerClass(Route $route): ?string
{
$action = $route->getActionName();
if ($action === 'Closure' || ! Str::contains($action, '@')) {
return null;
}
return Str::before($action, '@');
}
/**
* 컨트롤러 메서드명을 반환합니다.
*
* @param Route $route 라우트 인스턴스
* @return string|null 메서드명 (클로저면 null)
*/
private function controllerMethod(Route $route): ?string
{
$action = $route->getActionName();
if ($action === 'Closure' || ! Str::contains($action, '@')) {
return null;
}
return Str::after($action, '@');
}
/**
* 미들웨어 목록에서 permission 식별자를 추출합니다.
*
* @param array<int, string> $middleware 미들웨어 목록
* @return string|null permission 식별자 (예: core.users.read)
*/
private function resolvePermission(array $middleware): ?string
{
foreach ($middleware as $mw) {
if (! Str::contains($mw, 'PermissionMiddleware') && ! Str::startsWith($mw, 'permission:')) {
continue;
}
$args = Str::after($mw, ':');
// permission:admin,core.users.read,except:self:user → core.users.read
foreach (explode(',', $args) as $part) {
$part = trim($part);
if (Str::contains($part, '.') && ! Str::startsWith($part, 'except')) {
return $part;
}
}
}
return null;
}
/**
* URI 의 path 파라미터 목록을 추출합니다.
*
* @param string $uri 라우트 URI
* @return array<int, string> path 파라미터명 목록
*/
private function pathParams(string $uri): array
{
preg_match_all('/\{([^}?]+)\??\}/', $uri, $m);
return $m[1] ?? [];
}
/**
* path 파라미터명 → 바인딩된 Eloquent 모델 클래스 맵을 추출합니다.
*
* @param Route $route 라우트 인스턴스
* @return array<string, string> 파라미터명 => 모델 FQCN
*/
private function pathBindings(Route $route): array
{
$bindings = [];
try {
foreach ($route->signatureParameters() as $param) {
$type = $param->getType();
if ($type instanceof \ReflectionNamedType && ! $type->isBuiltin()) {
$class = $type->getName();
if (is_subclass_of($class, Model::class)) {
$bindings[$param->getName()] = $class;
}
}
}
} catch (\Throwable) {
// signatureParameters 실패 시 빈 맵
}
return $bindings;
}
/**
* 문서 파일 그룹핑용 도메인 키를 산출합니다.
*
* @param string $name 라우트명
* @param string $uri 라우트 URI
* @param array{type: string, id: string|null, key: string} $owner 소유 주체
* @return string 도메인 키 (예: users, products)
*/
private function domainGroup(string $name, string $uri, array $owner): string
{
// 라우트명 구조: api.{context}.{resource}.{action} 또는
// api.modules.{ext-id}.{context}.{resource}.{action}
// 도메인 = 앞쪽 연속된 context/소유 세그먼트를 걷어낸 뒤의 첫 세그먼트(리소스).
// 위치 기반이므로 'auth' 같은 리소스가 skip 리스트에 걸려 소실되지 않는다.
// 'modules'/'plugins' 는 확장 소유 prefix(api.modules.{id}.*)로도, 코어 확장관리
// 리소스(api.admin.modules.*)로도 쓰인다. 소유 prefix 는 owner['id'] 스킵으로 이미
// 걷히므로, leading 에는 순수 컨텍스트(api/admin/user/me/public)만 둔다.
$leading = ['api', 'admin', 'user', 'me', 'public'];
$segments = array_values(array_filter(explode('.', $name), fn ($s) => $s !== ''));
$i = 0;
while ($i < count($segments)) {
$seg = $segments[$i];
// 확장 소유 prefix 세그먼트(modules/plugins + ext-id)만 스킵
$isOwnerPrefix = in_array($seg, ['modules', 'plugins'], true) && isset($segments[$i + 1]) && $segments[$i + 1] === $owner['id'];
$isLeading = in_array($seg, $leading, true) || $isOwnerPrefix || ($owner['id'] !== null && $seg === $owner['id']);
if (! $isLeading) {
break;
}
$i++;
}
// context(me 등) 직후가 REST 액션명이면 리소스가 아니라 그 컨텍스트가 도메인이다
// (api.me.show → 'me', api.me.destroy → 'me'). 아니면 그 세그먼트가 리소스.
$restActions = ['show', 'index', 'store', 'update', 'destroy', 'edit', 'create'];
if (isset($segments[$i])) {
if (in_array($segments[$i], $restActions, true) && $i > 0 && in_array($segments[$i - 1], $leading, true)) {
return Str::slug($segments[$i - 1]) ?: 'misc';
}
return Str::slug($segments[$i]) ?: 'misc';
}
// 리소스 세그먼트가 없으면(context 직속) 마지막 컨텍스트를 도메인으로.
if ($i > 0 && isset($segments[$i - 1]) && in_array($segments[$i - 1], $leading, true)) {
return Str::slug($segments[$i - 1]) ?: 'misc';
}
// 라우트명이 비었으면 URI 에서 소유/컨텍스트 prefix 를 걷어낸 첫 리소스 세그먼트
$parts = array_values(array_filter(explode('/', $uri), fn ($p) => $p !== '' && ! Str::startsWith($p, '{')));
$uriLeading = ['api', 'admin', 'user', 'me', 'public'];
foreach ($parts as $p) {
if (in_array($p, $uriLeading, true) || ($owner['id'] !== null && $p === $owner['id'])) {
continue;
}
if (in_array($p, ['modules', 'plugins'], true) && ($owner['id'] !== null)) {
continue;
}
return Str::slug($p) ?: 'misc';
}
return 'misc';
}
}
@@ -0,0 +1,71 @@
<?php
namespace App\Support\ApiDoc;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
/**
* 컬럼 주석 해석기
*
* 모델 테이블의 컬럼 주석(한국어 comment) 을 조회해 응답 필드 설명의 기본값으로
* 제공합니다. G7 은 마이그레이션 한국어 comment 를 필수화하므로, 이 주석이 필드
* 설명의 SSoT 가 됩니다. 정적 스키마 조회이므로 실측 없이도 동작합니다.
*/
class ColumnCommentResolver
{
/**
* @var array<string, array<string, string>> 테이블별 컬럼 주석 캐시
*/
private array $cache = [];
/**
* 모델 테이블의 컬럼명 => 주석 맵을 반환합니다.
*
* @param class-string|null $modelClass 모델 FQCN
* @return array<string, string> 컬럼명 => 주석
*/
public function forModel(?string $modelClass): array
{
if (! $modelClass || ! class_exists($modelClass) || ! is_subclass_of($modelClass, Model::class)) {
return [];
}
try {
$table = (new $modelClass)->getTable();
} catch (\Throwable) {
return [];
}
return $this->forTable($table);
}
/**
* 테이블의 컬럼명 => 주석 맵을 반환합니다 (캐시).
*
* @param string $table 테이블명
* @return array<string, string> 컬럼명 => 주석
*/
public function forTable(string $table): array
{
if (isset($this->cache[$table])) {
return $this->cache[$table];
}
$map = [];
try {
foreach (Schema::getColumns($table) as $column) {
$comment = $column['comment'] ?? null;
if (is_string($comment) && $comment !== '') {
$map[$column['name']] = $comment;
}
}
} catch (\Throwable) {
// 테이블 부재/드라이버 미지원 시 빈 맵
}
return $this->cache[$table] = $map;
}
}
@@ -0,0 +1,200 @@
<?php
namespace App\Support\ApiDoc;
use Illuminate\Foundation\Http\FormRequest;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
/**
* FormRequest 정적 분석기
*
* 컨트롤러 메서드 시그니처에서 FormRequest 를 찾아 rules() 를 리플렉션으로
* 읽고, 요청 파라미터의 타입·필수 여부·허용값을 문서용 메타데이터로 변환합니다.
*/
class FormRequestIntrospector
{
/**
* 컨트롤러 메서드의 첫 FormRequest 파라미터에서 rules 메타데이터를 추출합니다.
*
* @param string|null $controller 컨트롤러 FQCN
* @param string|null $method 메서드명
* @return array{request_class: string|null, params: array<int, array<string, mixed>>, hook_filters: array<int, string>}
*/
public function introspect(?string $controller, ?string $method): array
{
$empty = ['request_class' => null, 'params' => [], 'hook_filters' => []];
if (! $controller || ! $method || ! class_exists($controller)) {
return $empty;
}
try {
$ref = new ReflectionMethod($controller, $method);
} catch (\ReflectionException) {
return $empty;
}
$requestClass = $this->findFormRequestParam($ref);
if (! $requestClass) {
return $empty;
}
$rules = $this->extractRules($requestClass);
return [
'request_class' => $requestClass,
'params' => $this->rulesToParams($rules),
'hook_filters' => $this->extractHookFilters($requestClass),
];
}
/**
* 메서드 파라미터 중 FormRequest 하위 클래스를 찾습니다.
*
* @param ReflectionMethod $ref 메서드 리플렉션
* @return class-string<FormRequest>|null FormRequest FQCN
*/
private function findFormRequestParam(ReflectionMethod $ref): ?string
{
foreach ($ref->getParameters() as $param) {
$type = $param->getType();
if (! $type instanceof ReflectionNamedType || $type->isBuiltin()) {
continue;
}
$class = $type->getName();
if (is_subclass_of($class, FormRequest::class)) {
return $class;
}
}
return null;
}
/**
* FormRequest 인스턴스를 만들어 rules() 를 호출합니다.
*
* @param class-string<FormRequest> $requestClass FormRequest FQCN
* @return array<string, mixed> 검증 규칙 배열
*/
private function extractRules(string $requestClass): array
{
try {
$instance = new $requestClass;
if (! method_exists($instance, 'rules')) {
return [];
}
$rules = $instance->rules();
return is_array($rules) ? $rules : [];
} catch (\Throwable) {
// rules() 가 컨테이너/route 의존이면 정적 호출 실패 — 파라미터 표는 비운다.
return [];
}
}
/**
* 검증 규칙 배열을 문서용 파라미터 메타데이터로 변환합니다.
*
* @param array<string, mixed> $rules 검증 규칙 배열
* @return array<int, array<string, mixed>> 파라미터 메타데이터 목록
*/
private function rulesToParams(array $rules): array
{
$params = [];
foreach ($rules as $field => $rule) {
// 중첩 필드(items.*.id)는 상위만 대표로 노출
if (str_contains((string) $field, '.')) {
continue;
}
$tokens = is_array($rule) ? $rule : explode('|', (string) $rule);
$tokens = array_map(fn ($t) => is_string($t) ? $t : '', $tokens);
$params[] = [
'name' => $field,
'type' => $this->inferType($tokens),
'required' => in_array('required', $tokens, true),
'allowed' => $this->inferAllowed($tokens),
];
}
return $params;
}
/**
* 규칙 토큰에서 파라미터 타입을 유추합니다.
*
* @param array<int, string> $tokens 규칙 토큰 목록
* @return string 유추된 타입
*/
private function inferType(array $tokens): string
{
foreach (['integer', 'numeric', 'boolean', 'array', 'string', 'date', 'email', 'file', 'image', 'uuid'] as $type) {
foreach ($tokens as $t) {
if ($t === $type || str_starts_with($t, $type)) {
return $type === 'numeric' ? 'number' : $type;
}
}
}
return 'string';
}
/**
* 규칙 토큰에서 허용값(in:, max:, min: 등)을 유추합니다.
*
* @param array<int, string> $tokens 규칙 토큰 목록
* @return string 허용값 설명 (없으면 빈 문자열)
*/
private function inferAllowed(array $tokens): string
{
$parts = [];
foreach ($tokens as $t) {
if (str_starts_with($t, 'in:')) {
$parts[] = '`'.str_replace(',', '`, `', substr($t, 3)).'`';
} elseif (str_starts_with($t, 'max:')) {
$parts[] = 'max '.substr($t, 4);
} elseif (str_starts_with($t, 'min:')) {
$parts[] = 'min '.substr($t, 4);
} elseif (str_starts_with($t, 'between:')) {
$parts[] = 'between '.substr($t, 8);
}
}
return implode(', ', $parts);
}
/**
* FormRequest 소스에서 HookManager::applyFilters 훅 이름을 추출합니다.
*
* @param class-string<FormRequest> $requestClass FormRequest FQCN
* @return array<int, string> 훅 필터 이름 목록
*/
private function extractHookFilters(string $requestClass): array
{
try {
$file = (new ReflectionClass($requestClass))->getFileName();
if (! $file || ! is_readable($file)) {
return [];
}
$source = file_get_contents($file);
preg_match_all('/applyFilters\(\s*[\'"]([a-z0-9_.-]+)[\'"]/i', $source, $m);
return array_values(array_unique($m[1] ?? []));
} catch (\Throwable) {
return [];
}
}
}
+394
View File
@@ -0,0 +1,394 @@
<?php
namespace App\Support\ApiDoc;
use Illuminate\Support\Str;
/**
* 요청 파라미터 설명기
*
* G7 전역에서 의미가 표준화된 공통 요청 파라미터(페이지네이션·정렬·검색·필터·
* 소프트삭제 토글 등)와, 일관된 명명 규칙(*_id / *Id / is_* / *_date / sort_* 등)의
* 설명을 코드에서 확인된 계약 그대로 서술합니다.
*
* ResourceFieldDescriber(응답 필드)의 요청 파라미터 대응물입니다. 도메인 특이
* 파라미터(예: refund_priority, temp_key)는 여기서 커버하지 않고 사람 서술(TODO)로
* 남깁니다 — 자동 채움은 "도메인 무관하게 의미가 고정된 파라미터"에만 한정합니다.
*/
class ParameterDescriber
{
/**
* @var array<string, string> 정확 이름 => 설명 (위치 무관 공통 파라미터)
*/
private const EXACT = [
// 페이지네이션
'page' => '조회할 페이지 번호 (1부터 시작)',
'per_page' => '페이지당 항목 수',
'limit' => '반환할 최대 항목 수',
'offset' => '건너뛸 항목 수 (오프셋 페이지네이션)',
'cursor' => '커서 기반 페이지네이션의 다음 페이지 커서',
// 정렬
'sort' => '정렬 기준 (필드명, `-` 접두 시 내림차순)',
'sort_by' => '정렬 기준 필드명',
'sort_field' => '정렬 기준 필드명',
'sort_direction' => '정렬 방향 (asc / desc)',
'order_by' => '정렬 기준 필드명',
'direction' => '정렬 방향 (asc / desc)',
// sort_order / order 는 문맥에 따라 정렬 방향(문자열 asc/desc)과
// 표시 순서 값(정수)으로 갈리므로 EXACT 에 두지 않고 describe() 에서
// 타입으로 분기한다.
// 검색/필터
'search' => '검색어 (지정한 검색 대상 필드에서 부분 일치)',
'q' => '검색어 (부분 일치)',
'keyword' => '검색 키워드 (부분 일치)',
'search_keyword' => '검색 키워드 (부분 일치)',
'search_field' => '검색 대상 필드명 (검색어를 적용할 컬럼)',
'search_type' => '검색 유형 (검색 대상/방식 구분)',
'filters' => '추가 필터 조건 맵 (필드별 조건)',
'filter' => '필터 조건',
'start_date' => '조회 기간 시작일 (이 날짜 이후 데이터)',
'end_date' => '조회 기간 종료일 (이 날짜 이전 데이터)',
'date_from' => '조회 기간 시작일',
'date_to' => '조회 기간 종료일',
'from' => '조회 시작 값 (기간/범위 하한)',
'to' => '조회 종료 값 (기간/범위 상한)',
'scope' => '조회 범위 한정 키',
// 상태 토글/플래그
'is_active' => '활성 여부 (true 활성 / false 비활성)',
'is_default' => '기본값 지정 여부',
'active' => '활성 여부',
'published' => '발행 여부 (발행된 항목만 필터)',
'enabled' => '사용 여부',
'force' => '강제 실행 여부 (안전 확인/선행 검사 우회)',
'with_trashed' => '소프트 삭제된 항목 포함 여부',
'only_trashed' => '소프트 삭제된 항목만 조회 여부',
// 대량 처리
'ids' => '대상 리소스 식별자 배열 (대량 작업 대상)',
'items' => '처리 대상 항목 배열',
// 국제화
'locale' => '로케일 코드 (표시 언어/지역)',
'language' => '언어 코드',
'country_code' => '국가 코드 (ISO 3166-1 alpha-2)',
'timezone' => '타임존 식별자',
// 인증/보안 공통
'password' => '비밀번호',
'current_password' => '현재 비밀번호 (변경 전 확인용)',
'password_confirmation' => '비밀번호 확인 (password 와 일치해야 함)',
'token' => '인증/검증 토큰',
'email' => '이메일 주소',
// 주소 공통
'zipcode' => '우편번호',
'address' => '기본 주소',
'address_detail' => '상세 주소',
'recipient_name' => '수령인 이름',
'recipient_phone' => '수령인 연락처',
'address_line_1' => '주소 1행 (기본 주소)',
'address_line_2' => '주소 2행 (상세 주소)',
'intl_city' => '도시 (국제 주소)',
'intl_state' => '주/도 (국제 주소)',
'intl_postal_code' => '우편번호 (국제 주소)',
'region' => '지역/권역',
// SEO 메타 공통 (근거: Seo\* / Page\* / Product\* FormRequest 의
// meta_title/meta_description — 검색엔진 노출용 메타 태그 값. 도메인 무관.)
'meta_title' => 'SEO 메타 제목 (검색엔진/소셜 공유 표시 제목)',
'meta_description' => 'SEO 메타 설명 (검색엔진/소셜 공유 표시 요약)',
'alt_text' => '이미지 대체 텍스트 (접근성/이미지 미표시 시 대체 문구)',
// 프로필/콘텐츠 공통 필드 (User/프로필/일반 리소스에서 의미 고정)
// 근거: User\{Create,Update}UserRequest, UpdateProfileRequest, Auth\RegisterRequest,
// Layout\* / Menu\* / Notification* / Schedule\* FormRequest
'name' => '대상의 이름/명칭',
'nickname' => '닉네임',
'description' => '설명',
'content' => '본문 내용',
'body' => '본문',
'subject' => '제목',
'title' => '제목',
'slug' => 'URL 친화 식별자 (slug)',
'label' => '표시용 라벨',
'phone' => '전화번호',
'mobile' => '휴대전화 번호',
'homepage' => '홈페이지 URL',
'bio' => '자기소개',
'signature' => '서명',
'country' => '국가 코드 (ISO 3166-1 alpha-2)',
'url' => 'URL',
'file' => '업로드 파일',
'files' => '업로드 파일 배열',
'collection' => '첨부 컬렉션 그룹명 (첨부를 용도별로 묶는 키, 미지정 시 default)',
'avatar' => '아바타 이미지',
'icon' => '아이콘',
'value' => '값',
'values' => '값 배열',
'username' => '사용자명 (로그인/인증 아이디)',
'path' => '경로',
'data' => '데이터 페이로드',
// 확장/버전 공통 (module/plugin/template/language-pack 설치·업데이트 계약)
// 근거: Module/Plugin/Template/LanguagePack Install·Update·Activate FormRequest,
// Extension\ChangelogRequest, Menu/Schedule/Notification* Request
'extension_type' => '확장 유형 (core/module/plugin/template)',
'extension_identifier' => '확장 식별자',
'from_version' => '시작 버전 (범위 하한)',
'to_version' => '대상 버전 (범위 상한)',
'github_url' => 'GitHub 저장소 URL',
'vendor' => '벤더명 (확장 제작자 식별자)',
'vendor_mode' => '벤더 설치 모드 (auto/composer/bundled)',
'checksum' => '무결성 검증 체크섬 (SHA-256)',
'target_identifier' => '대상 확장 식별자',
'source_identifier' => '출처 식별자',
'auto_activate' => '설치 후 자동 활성화 여부',
'cascade' => '연쇄 처리 여부 (의존 항목 함께 처리)',
'exclude_protected' => '보호 항목 제외 여부',
// 스케줄/작업 공통 (근거: Schedule\{Create,Update}ScheduleRequest, ScheduleListRequest)
'command' => '실행할 아티즌 커맨드',
'frequency' => '실행 주기',
'priority' => '우선순위 (작을수록 우선)',
'timeout' => '타임아웃 (초)',
'run_in_maintenance' => '점검 모드 중 실행 여부',
'without_overlapping' => '중복 실행 방지 여부',
'expected_lock_version' => '낙관적 잠금 버전 (동시 편집 충돌 감지)',
// 메일/드라이버 설정 (근거: Settings\SaveSettingsRequest,
// Settings\TestMailRequest, Settings\TestDriverConnectionRequest)
'mailer' => '메일 발송 드라이버 (smtp/mailgun/ses)',
'from_address' => '발신자 주소',
'from_name' => '발신자 이름',
'to_email' => '테스트 수신 주소',
'host' => '호스트 주소',
'port' => '포트 번호',
'encryption' => '전송 암호화 방식 (tls/ssl)',
'storage_driver' => '스토리지 드라이버 (local/s3)',
'cache_driver' => '캐시 드라이버 (file/redis/memcached)',
'session_driver' => '세션 드라이버 (file/database/redis)',
'queue_driver' => '큐 드라이버 (sync/database/redis)',
'redis_host' => 'Redis 호스트 주소',
'redis_port' => 'Redis 포트 번호',
'redis_password' => 'Redis 비밀번호',
'redis_database' => 'Redis 데이터베이스 번호',
'memcached_host' => 'Memcached 호스트 주소',
'memcached_port' => 'Memcached 포트 번호',
's3_bucket' => 'S3 버킷명',
's3_region' => 'S3 리전',
's3_access_key' => 'S3 액세스 키',
's3_secret_key' => 'S3 시크릿 키',
's3_url' => 'S3 엔드포인트 URL',
'ses_key' => 'SES 액세스 키',
'ses_secret' => 'SES 시크릿 키',
'ses_region' => 'SES 리전',
'mailgun_domain' => 'Mailgun 도메인',
'mailgun_secret' => 'Mailgun 시크릿 키',
'mailgun_endpoint' => 'Mailgun 엔드포인트',
'websocket_enabled' => 'WebSocket 사용 여부',
'websocket_host' => 'WebSocket 호스트 주소',
'websocket_port' => 'WebSocket 포트 번호',
'websocket_scheme' => 'WebSocket 스킴 (http/https)',
'websocket_app_key' => 'WebSocket 앱 키',
];
/**
* 파라미터 설명을 반환합니다. 없으면 null (호출자가 TODO 로 폴백).
*
* @param string $name 파라미터명
* @param string $location 위치 (path/query/body)
* @param string $type 타입 (integer/string/boolean/array...)
* @return string|null 설명 (없으면 null)
*/
public function describe(string $name, string $location = '', string $type = ''): ?string
{
// sort_order / order 는 타입에 따라 의미가 갈린다:
// - 문자열: 정렬 방향(asc/desc)
// - 정수: 표시 정렬 순서 값(작을수록 우선 — 컬럼 값)
if (in_array($name, ['sort_order', 'order'], true)) {
return match ($type) {
'integer', 'number' => '표시 정렬 순서 값 (작을수록 우선)',
'string' => '정렬 방향 (asc 오름차순 / desc 내림차순)',
default => null,
};
}
// status / type / category 는 query(목록 조회)에서만 필터 의미가 고정된다.
// body(생성/수정)에서는 설정할 도메인 값이므로 의미가 도메인마다 달라
// 사람 서술(TODO)로 남긴다.
if (in_array($name, ['status', 'type', 'category'], true)) {
if ($location !== 'query') {
return null;
}
$label = ['status' => '상태', 'type' => '유형', 'category' => '분류'][$name];
return "{$label} 필터 (해당 {$label}의 항목만 조회)";
}
if (isset(self::EXACT[$name])) {
return self::EXACT[$name];
}
// path 파라미터는 대부분 리소스 식별자 — 위치를 근거로 유추.
if ($location === 'path') {
return $this->describePathParam($name);
}
return $this->byPattern($name, $type);
}
/**
* path 파라미터(리소스 식별자)의 설명을 유추합니다.
*
* @param string $name path 파라미터명
* @return string|null 설명 (미매칭 시 null)
*/
private function describePathParam(string $name): ?string
{
// 순수 id / *_id / *Id: 대상 리소스의 식별자
if ($name === 'id') {
return '대상 리소스의 식별자';
}
if (Str::endsWith($name, '_id')) {
$base = $this->humanize(Str::beforeLast($name, '_id'));
return "대상 {$base}의 식별자";
}
if (Str::endsWith($name, 'Id') && $name !== 'Id') {
$base = $this->humanizeCamel(Str::beforeLast($name, 'Id'));
return "대상 {$base}의 식별자";
}
// slug / identifier / hash / uuid: 리소스 지시 키
if (in_array($name, ['slug', 'identifier', 'hash', 'uuid', 'code'], true)) {
$labels = [
'slug' => '대상 리소스의 slug (URL 친화 식별자)',
'identifier' => '대상 리소스의 식별자',
'hash' => '대상 리소스의 해시 식별자',
'uuid' => '대상 리소스의 UUID',
'code' => '대상 리소스의 코드',
];
return $labels[$name];
}
// *Name (templateName, pluginName, moduleName): 확장/리소스 이름 식별자
if (Str::endsWith($name, 'Name') && $name !== 'Name') {
$base = $this->humanizeCamel(Str::beforeLast($name, 'Name'));
return "대상 {$base}의 이름 (식별자)";
}
// *Identifier (templateIdentifier 등): 확장/리소스 식별자
if (Str::endsWith($name, 'Identifier') && $name !== 'Identifier') {
$base = $this->humanizeCamel(Str::beforeLast($name, 'Identifier'));
return "대상 {$base}의 식별자";
}
// bare 리소스명 path 파라미터: Laravel route-model binding 은
// `/{user}`, `/{role}`, `/{definition}` 처럼 대상 모델의 단수형(또는
// camelCase)을 그대로 세그먼트로 쓴다. 접미 패턴(_id/slug/*Id 등)에
// 걸리지 않은 path 파라미터는 이 바인딩 대상 리소스의 식별자로 본다.
// 예외: key/version 은 리소스가 아니라 설정 키/버전 값이므로 EXACT 폴백.
$bareExact = [
'key' => '대상 설정/항목의 키',
'version' => '대상 버전 (버전 문자열)',
];
if (isset($bareExact[$name])) {
return $bareExact[$name];
}
$base = str_contains($name, '_')
? $this->humanize($name)
: $this->humanizeCamel($name);
return "대상 {$base}의 식별자";
}
/**
* query/body 파라미터의 일관된 명명 규칙으로 설명을 유추합니다.
*
* @param string $name 파라미터명
* @param string $type 타입
* @return string|null 설명 (미매칭 시 null)
*/
private function byPattern(string $name, string $type): ?string
{
// identifier: 확장/리소스 지시 식별자 (query/body).
// path 위치는 describePathParam 이 먼저 처리하므로 여기 도달하지 않는다.
if ($name === 'identifier') {
return '대상 확장/리소스의 식별자';
}
// *_name: 확장/리소스 이름 식별자 (template_name/plugin_name/module_name/layout_name 등).
// EXACT 의 recipient_name/from_name 은 여기 도달 전에 이미 처리된다.
if (Str::endsWith($name, '_name')) {
$base = $this->humanize(Str::beforeLast($name, '_name'));
return "{$base} 이름 (식별자)";
}
// *_id: 연관 리소스 식별자 참조
if (Str::endsWith($name, '_id')) {
$base = $this->humanize(Str::beforeLast($name, '_id'));
return "{$base} 식별자";
}
// *_ids: 연관 리소스 식별자 배열
if (Str::endsWith($name, '_ids')) {
$base = $this->humanize(Str::beforeLast($name, '_ids'));
return "{$base} 식별자 배열";
}
// is_*/has_*: 불리언 토글
if ((Str::startsWith($name, 'is_') || Str::startsWith($name, 'has_')) && $type === 'boolean') {
$base = $this->humanize(Str::after($name, '_'));
return "{$base} 여부";
}
// *_date: 날짜 값
if (Str::endsWith($name, '_date')) {
$base = $this->humanize(Str::beforeLast($name, '_date'));
return "{$base} 날짜";
}
// *_at: 일시 값
if (Str::endsWith($name, '_at')) {
$base = $this->humanize(Str::beforeLast($name, '_at'));
return "{$base} 일시";
}
return null;
}
/**
* snake_case 를 사람이 읽는 문구로 변환합니다.
*
* @param string $token snake_case 토큰
* @return string 공백 구분 문구
*/
private function humanize(string $token): string
{
return str_replace('_', ' ', $token);
}
/**
* camelCase 를 사람이 읽는 문구로 변환합니다.
*
* @param string $token camelCase 토큰
* @return string 공백 구분 소문자 문구
*/
private function humanizeCamel(string $token): string
{
return Str::lower(trim(preg_replace('/([A-Z])/', ' $1', $token)));
}
}
@@ -0,0 +1,258 @@
<?php
namespace App\Support\ApiDoc;
use Illuminate\Support\Str;
/**
* 리소스 계약 필드 설명기
*
* 컬럼 주석이 없는 accessor/computed 필드(Resource 의 toArray() 가 파생하는 값)의
* 설명을 제공합니다. G7 전역에서 의미가 표준화된 필드(BaseApiResource 의 is_owner /
* abilities, Enum 파생 status_label / status_variant, User::isAdmin() 등)와, 일관된
* 파생 규칙(_label / _variant / _flag / _name / is_* / *_at 접미·접두)을 코드에서
* 확인된 의미 그대로 서술합니다.
*
* 우선순위: 이 계약 사전은 컬럼 주석보다 앞섭니다 — created_at 은 어느 테이블이든
* "생성 일시" 이고, status_label 은 컬럼이 아니라 Enum label() 산물이기 때문입니다.
*/
class ResourceFieldDescriber
{
/**
* @var array<string, string> 정확 필드명 => 설명 (BaseApiResource/공통 Resource 계약)
*/
private const EXACT = [
// BaseApiResource 표준 메타 (resourceMeta)
'is_owner' => '현재 인증 사용자가 이 리소스의 소유자인지 여부 (BaseApiResource 표준 메타)',
'abilities' => '현재 사용자가 이 리소스에 수행 가능한 작업 불리언 맵 (can_update, can_delete 등 — 권한 맵 기반)',
// 공통 식별/타임스탬프
'id' => '기본 키 (내부 식별자)',
'uuid' => '외부 노출용 UUID (URL/API 식별자, 내부 id 비노출)',
'created_at' => '생성 일시',
'updated_at' => '최종 수정 일시',
'deleted_at' => '소프트 삭제 일시 (미삭제 시 null)',
// 공통 콘텐츠/표시 필드 (도메인 무관하게 역할이 고정 — 요청 파라미터
// ParameterDescriber 의 name/title/content/description 대응물).
// 근거: 실측 시 board 게시글·category·brand·notification 등 전 도메인에서
// 동일 역할(명칭/제목/본문/설명)로 관측. 다국어(object)/문자열 무관.
'name' => '대상의 이름/명칭 (다국어 필드는 로케일별 값 객체)',
'title' => '제목',
'content' => '본문 내용',
'description' => '설명 (다국어 필드는 로케일별 값 객체)',
'slug' => 'URL 친화 식별자 (slug)',
'label' => '표시용 라벨',
'icon' => '아이콘 식별자 (아이콘 클래스/이름)',
'thumbnail' => '썸네일 이미지 URL/경로',
'ip_address' => '요청/행위가 발생한 IP 주소',
// User 계약 파생 필드 (UserResource)
'status_label' => '상태의 사람이 읽는 라벨 (상태 Enum label() 산물)',
'status_variant' => '상태 표시 색상/스타일 변형 키 (상태 Enum variant() 산물 — UI 배지용)',
'language_label' => '언어 코드의 현지화 라벨 (user.language.{code} 번역)',
'country_flag' => '국가 코드의 국기 이모지 (country 값에서 파생)',
'country_name' => '국가 코드의 현지화 국가명 (country 값에서 파생)',
'is_admin' => '관리자 역할 보유 여부 (User::isAdmin() — 역할 관계 기반 파생)',
// 확장 상태 계약 필드 (ModuleResource/PluginResource/TemplateResource)
'is_bundled' => '코어에 선탑재된 번들 확장인지 여부',
'is_pending' => '_pending 대기소에 있어 설치 대기 중인지 여부',
'update_available' => '최신 버전 대비 업데이트 가능 여부',
'update_source' => '업데이트 감지 출처 (github, bundled 등)',
'latest_version' => '감지된 최신 배포 버전',
'file_version' => '설치된 파일의 manifest 버전',
'incompatible_required_version' => '요구 코어 버전 미충족 시 필요한 버전 (호환되면 null)',
'status_variant_label' => '상태 표시용 라벨/변형',
'dependencies' => '의존하는 확장 맵 (manifest 파생 — {modules, plugins})',
'assets' => '프론트엔드 에셋 매니페스트 (manifest 파생 — js/css 진입점·로딩 전략)',
// 관계/연관 객체 (여러 Resource 에서 동일 계약)
'creator' => '생성자 정보 객체 (uuid/name/email — creator 관계 파생)',
'children' => '하위 항목 배열 (계층 트리 — children 관계 파생)',
'parent' => '상위 항목 객체 (parent 관계 파생)',
'permissions' => '연결된 권한 목록 (id/identifier/name — 역할 경유 권한 관계 파생)',
'recipient' => '수신자 사용자 객체 (uuid/name/email — recipientUser 관계 파생)',
'sender' => '발신자 사용자 객체 (uuid/name/email — senderUser 관계 파생)',
'author' => '작성자 사용자 객체 (uuid/name — author 관계 파생)',
'actor_name' => '행위를 수행한 주체(사용자/시스템)의 이름',
// 시스템/집계 공통 (DashboardService/UserRepository/SettingsService)
'total' => '전체 개수 (집계)',
'total_users' => '전체 사용자 수 (통계 객체는 count/추이 포함)',
'time' => '상대 시각 표시 (예: "24초 전" — diffForHumans() 산물)',
'server_time' => '서버 현재 시각 (Y-m-d H:i:s)',
'number' => '목록에서의 순번 (페이지네이션 반영 행 번호 — HasRowNumber 파생)',
// 로케일 (TemplateResource/LocaleController)
'locales' => '활성 로케일 코드 배열',
'locale_names' => '로케일 코드별 표시명 맵 (config app.locale_names)',
// 확장/버전 공통 (Module/Plugin/Template/LanguagePack Resource, 확장 Manager)
'extension_type' => '이 리소스를 소유한 확장의 타입 (core/module/plugin/template)',
'extension_identifier' => '이 리소스를 소유한 확장의 식별자',
'extension_name' => '이 리소스를 소유한 확장의 표시 이름 (manifest name)',
'github_url' => 'GitHub 저장소 URL (manifest 파생)',
'github_changelog_url' => 'GitHub 변경 이력(CHANGELOG) URL (manifest 파생)',
'changelog' => '변경 이력 텍스트 (원격/파일 CHANGELOG 본문)',
'current_core_version' => '현재 설치된 코어 버전',
'installed_modules' => '설치된 모듈 집계 객체 (total/active)',
'installed_templates' => '설치된 템플릿 집계 객체 (total/active)',
'active_plugins' => '활성 플러그인 집계 객체 (total/active)',
'bundled_identifier' => '대응하는 번들 확장 식별자 (번들 원본 매칭용)',
'origin' => '출처 (설치/등록 원천 구분 값)',
'target_name' => '대상 확장의 표시 이름 (scope+target_identifier 로 해석)',
'install_blocked_reason' => '설치가 차단된 사유 (차단 없으면 null)',
];
/**
* 필드명에 대한 설명을 반환합니다. 없으면 null (호출자가 컬럼 주석/TODO 로 폴백).
*
* @param string $field 필드명
* @param string $type 실측 타입 (boolean/integer/string/object/array...)
* @return string|null 설명 (없으면 null)
*/
public function describe(string $field, string $type = ''): ?string
{
// sort_order 는 응답에서 표시 정렬 순서 값(정수 컬럼)으로 고정된다.
// 문자열이면 정렬 방향일 수 있어 도메인 특이 → TODO 유지.
// (ParameterDescriber 의 sort_order 타입 분기와 동일 계약)
if ($field === 'sort_order') {
return in_array($type, ['integer', 'number'], true)
? '표시 정렬 순서 값 (작을수록 우선)'
: null;
}
if (isset(self::EXACT[$field])) {
return self::EXACT[$field];
}
return $this->byPattern($field, $type);
}
/**
* 일관된 파생 규칙(접미/접두 패턴)으로 설명을 유추합니다.
*
* @param string $field 필드명
* @param string $type 실측 타입
* @return string|null 설명 (패턴 미매칭 시 null)
*/
private function byPattern(string $field, string $type): ?string
{
// *_at: 타임스탬프 (UI 포맷 문자열 또는 ISO)
if (Str::endsWith($field, '_at')) {
$base = $this->humanize(Str::beforeLast($field, '_at'));
return "{$base} 일시";
}
// *_formatted: 원본 값을 사람이 읽는 문자열로 포맷한 표시용 파생 필드
// (근거: size_formatted accessor, formatCurrencyPrice/formatFileSize/
// formatCreatedAtFormat — 통화·용량·일시 등을 로케일/단위 포맷). 도메인
// 무관하게 "`base` 값의 표시용 포맷 문자열" 로 의미가 고정된다.
if (Str::endsWith($field, '_formatted')) {
$base = Str::beforeLast($field, '_formatted');
return "`{$base}` 값의 표시용 포맷 문자열 (통화/용량/일시 등 로케일·단위 포맷)";
}
// *_label: 원본 값의 현지화 라벨 (Enum label() 또는 번역)
if (Str::endsWith($field, '_label')) {
$base = Str::beforeLast($field, '_label');
return "`{$base}` 값의 사람이 읽는 라벨 (현지화/Enum 파생)";
}
// *_variant: UI 배지 색상/스타일 변형 키
if (Str::endsWith($field, '_variant')) {
$base = Str::beforeLast($field, '_variant');
return "`{$base}` 값의 표시 변형 키 (UI 배지 색상/스타일)";
}
// can_*: abilities 맵 내부 능력 불리언
if (Str::startsWith($field, 'can_')) {
$action = $this->humanize(Str::after($field, 'can_'));
return "{$action} 수행 가능 여부 (권한 기반)";
}
// is_*/has_*: 불리언 상태 플래그
if ((Str::startsWith($field, 'is_') || Str::startsWith($field, 'has_')) && $type === 'boolean') {
$base = $this->humanize(Str::after($field, '_'));
return "{$base} 여부";
}
// *_count: 집계 개수
if (Str::endsWith($field, '_count') && in_array($type, ['integer', 'number'], true)) {
$base = $this->humanize(Str::beforeLast($field, '_count'));
return "{$base} 개수 (집계)";
}
// *_raw: 다국어/현지화 이전 원본 값 (getValue 로 로케일 미해석 원본 반환)
// 예: name_raw = name 의 원본, description_raw = description 의 원본
if (Str::endsWith($field, '_raw')) {
$base = Str::beforeLast($field, '_raw');
return "`{$base}` 의 원본 값 (현재 로케일 미해석 원본 JSON/문자열)";
}
// localized_* / *_localized: 다국어 필드를 현재 로케일로 해석한 표시용 값
// (근거: getLocalizedName() / getLocalizedOptionName() 등 — 다국어 JSON 을
// 현재 로케일 문자열로 해석). 도메인 무관 파생 규칙.
if (Str::startsWith($field, 'localized_')) {
$base = $this->humanize(Str::after($field, 'localized_'));
return "`{$base}` 의 현재 로케일 해석 값 (다국어 필드를 표시용 문자열로 해석)";
}
if (Str::endsWith($field, '_localized')) {
$base = $this->humanize(Str::beforeLast($field, '_localized'));
return "`{$base}` 의 현재 로케일 해석 값 (다국어 필드를 표시용 문자열로 해석)";
}
// *_url: 리소스에 접근하는 URL (썸네일/다운로드/이미지 등)
// (근거: thumbnail_url => download_url / getThumbnailUrl()). 도메인 무관.
if (Str::endsWith($field, '_url')) {
$base = $this->humanize(Str::beforeLast($field, '_url'));
return "{$base} URL";
}
// *_id: 연관 리소스를 참조하는 정수/UUID 식별자 (parent_id/user_id/loggable_id 등).
// *_ids: 연관 리소스 식별자 배열.
// 예외: login_id 는 참조 식별자가 아니라 로그인 계정 아이디(문자열)이므로 제외
// (도메인 특이 → TODO 유지).
if (Str::endsWith($field, '_ids')) {
$base = $this->humanize(Str::beforeLast($field, '_ids'));
return "{$base} 식별자 배열 (연관 리소스 참조)";
}
if (Str::endsWith($field, '_id') && ! Str::endsWith($field, 'login_id')) {
$base = $this->humanize(Str::beforeLast($field, '_id'));
return "{$base} 식별자 (연관 리소스 참조)";
}
// depth: 계층 트리에서의 깊이 (0 = 최상위). children/parent 트리 파생 필드로
// 도메인 무관하게 의미가 고정된다 (근거: CommentResource/CategoryResource depth).
if ($field === 'depth' && in_array($type, ['integer', 'number'], true)) {
return '계층 트리에서의 깊이 (0 = 최상위, 하위로 갈수록 증가)';
}
return null;
}
/**
* snake_case 를 사람이 읽는 문구로 변환합니다.
*
* @param string $token snake_case 토큰
* @return string 공백 구분 문구
*/
private function humanize(string $token): string
{
return str_replace('_', ' ', $token);
}
}
@@ -0,0 +1,220 @@
<?php
namespace App\Support\ApiDoc;
/**
* 응답 스키마 추론기
*
* 실측한 응답 JSON(ResponseHelper envelope)에서 data 내부의 필드 스키마를
* 추론합니다. 각 필드의 타입과 샘플값을 문서용 메타데이터로 변환합니다.
*/
class ResponseSchemaInferrer
{
/**
* envelope 응답 body 에서 data 필드 스키마를 추론합니다.
*
* @param array<string, mixed> $body 실측 응답 body (envelope)
* @return array{envelope: array<int, string>, shape: string, fields: array<int, array<string, mixed>>, pagination: bool}
*/
public function infer(array $body): array
{
$envelope = array_keys($body);
$data = $body['data'] ?? null;
// 목록 응답: data.data 가 배열 (BaseApiCollection)
if (is_array($data) && isset($data['data']) && is_array($data['data'])) {
$rows = array_values(array_filter($data['data'], 'is_array'));
return [
'envelope' => $envelope,
'shape' => 'collection',
'fields' => $this->fieldsFromRows($rows),
'pagination' => isset($data['pagination']),
];
}
// 단건 응답: data 가 연관 배열
if (is_array($data) && $this->isAssoc($data)) {
return [
'envelope' => $envelope,
'shape' => 'object',
'fields' => $this->fieldsFromRow($data),
'pagination' => false,
];
}
// data 가 순수 배열(목록만)
if (is_array($data) && ! $this->isAssoc($data) && isset($data[0]) && is_array($data[0])) {
$rows = array_values(array_filter($data, 'is_array'));
return [
'envelope' => $envelope,
'shape' => 'array',
'fields' => $this->fieldsFromRows($rows),
'pagination' => false,
];
}
return [
'envelope' => $envelope,
'shape' => 'scalar',
'fields' => [],
'pagination' => false,
];
}
/**
* 한 행(row)에서 필드별 타입·샘플값을 추출합니다.
*
* @param array<string, mixed> $row 응답 데이터 한 행
* @return array<int, array<string, mixed>> 필드 메타데이터 목록
*/
private function fieldsFromRow(array $row): array
{
$fields = [];
foreach ($row as $key => $value) {
$fields[] = [
'name' => (string) $key,
'type' => $this->typeOf($value),
'sample' => $this->sampleOf($value),
];
}
return $fields;
}
/**
* 여러 행을 병합해 필드별로 non-null 대표 샘플과 실제 타입을 선택합니다.
*
* 첫 행이 우연히 비어있어(null) "항상 null" 처럼 보이는 문제를 방지하기 위해,
* 각 필드에서 값이 채워진 행을 우선 채택합니다.
*
* @param array<int, array<string, mixed>> $rows 응답 데이터 행 목록
* @return array<int, array<string, mixed>> 필드 메타데이터 목록
*/
private function fieldsFromRows(array $rows): array
{
if ($rows === []) {
return [];
}
// 첫 행의 키 순서를 기준으로 필드 목록 확정
$keys = array_keys($rows[0]);
$fields = [];
foreach ($keys as $key) {
$chosenValue = null;
$chosenType = 'null';
foreach ($rows as $row) {
if (! array_key_exists($key, $row)) {
continue;
}
$value = $row[$key];
$type = $this->typeOf($value);
// 값이 채워진(non-null) 첫 행을 대표로 채택하고 탐색 종료
if ($type !== 'null') {
$chosenValue = $value;
$chosenType = $type;
break;
}
// 아직 non-null 을 못 찾았으면 null 이라도 후보로 유지
$chosenValue = $value;
}
$fields[] = [
'name' => (string) $key,
'type' => $chosenType,
'sample' => $this->sampleOf($chosenValue),
];
}
return $fields;
}
/**
* 값의 JSON 타입을 판별합니다.
*
* @param mixed $value 값
* @return string 타입 문자열
*/
private function typeOf(mixed $value): string
{
return match (true) {
is_bool($value) => 'boolean',
is_int($value) => 'integer',
is_float($value) => 'number',
is_string($value) => 'string',
is_null($value) => 'null',
is_array($value) && $this->isAssoc($value) => 'object',
is_array($value) => 'array',
default => 'mixed',
};
}
/**
* 값의 샘플 표현을 반환합니다 (문서 표에 표시할 축약형).
*
* @param mixed $value 값
* @return string 샘플 표현 (마크다운 표 셀 안전)
*/
private function sampleOf(mixed $value): string
{
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
if (is_null($value)) {
return 'null';
}
if (is_array($value)) {
$encoded = json_encode($value, JSON_UNESCAPED_UNICODE);
$encoded = (string) $encoded;
if (mb_strlen($encoded) > 60) {
$encoded = mb_substr($encoded, 0, 57).'…';
}
return $this->escapeCell($encoded);
}
$str = (string) $value;
if (mb_strlen($str) > 40) {
$str = mb_substr($str, 0, 37).'…';
}
return $this->escapeCell($str);
}
/**
* 마크다운 표 셀 안에서 안전하도록 파이프/개행을 이스케이프합니다.
*
* @param string $text 원본 텍스트
* @return string 이스케이프된 텍스트
*/
private function escapeCell(string $text): string
{
return str_replace(['|', "\n", "\r"], ['\\|', ' ', ''], $text);
}
/**
* 배열이 연관 배열(맵)인지 판별합니다.
*
* @param array<mixed> $arr 배열
* @return bool 연관 배열 여부
*/
private function isAssoc(array $arr): bool
{
if ($arr === []) {
return false;
}
return array_keys($arr) !== range(0, count($arr) - 1);
}
}