feat(core,docs): 확장별 개발자 문서 생성기와 검사 하네스 구축

번들 확장 20개 중 에이전트·확장개발자가 읽을 수 있는 문서를 가진 확장이 0개였다.
`docs/api/**` 는 "엔드포인트가 무엇을 받고 무엇을 돌려주는가" 만 답하고, 확장을 고치려는
쪽이 실제로 묻는 것(왜 이렇게 설계됐는가 / 어디를 확장해야 하는가 / 무엇을 건드리면 안
되는가)은 어디에도 없었다. 그 결과 확장이 발행하는 훅은 확장점인데도 사실상 비공개였다.

이 커밋은 인프라만 담는다. 문서 집필은 확장별로 순차 진행한다.

- `php artisan ext:docgen` — 진입 클래스의 선언형 getter 를 실제로 호출하고 소스를 스캔해
 훅·라우트·권한·메뉴·설정·모델·레이아웃·핸들러·테스트 경로·의존 관계를 실측한다.
 `_bundled` 를 읽는다 (활성 디렉토리에 같은 FQCN 이 로드돼 있으면 eval-rename 으로 우회).
- 자동 생성 블록은 **안쪽만** 교체한다. 사람 서술이 소실될 경로를 만들지 않으려고 파괴적
 재생성 플래그를 두지 않았고, 문서에 없는 블록 키는 주입하지 않고 누락으로 보고한다.
- 필수 문서·섹션·블록 목록은 `ExtensionDocScaffolder::DOCUMENTS` 단일 SSoT 다. 검사
 스크립트는 이를 복제하지 않고 `--check --json` 을 소비하며, PHP 를 못 돌리면 "이상 0건"
 이 아니라 "점검 불가" 로 구분 보고한다.
- 두 audit 룰은 도입 시점 전수가 공허 통과하므로(대상 문서 0건) 픽스처 테스트가 판정식을
 잠근다. 스캐너·mermaid·검사 스크립트 축도 같은 이유로 픽스처를 함께 둔다.

동반 수정: 훅이 넘기는 `file_path` 는 항상 절대경로인데 `FILE_RULES` 다수가 루트로
앵커해 있어 그 규칙들이 조용히 죽어 있었다(추적 파일 440개가 절대경로에서 0건 매치).
`toRepoRelative` 로 정규화하고 세 경로 형태의 판정 일치를 테스트로 고정했다.
문서 인덱스 생성기의 CRLF 문서 제목·TL;DR 추출 누락도 같은 성격이라 함께 고쳤다.
This commit is contained in:
HeuJung committed 2026-08-31 07:58:44 +09:00
1 parent 266b723b9d
commit 11175d35d6
16 files changed
+6984 -3

No files matched your search

@@ -0,0 +1,332 @@
<?php
namespace App\Support\ExtensionDoc;
use Illuminate\Support\Facades\File;
/**
* 확장 데이터 모델 수집기
*
* 모델·Enum·마이그레이션·Repository 계약을 `_bundled` 소스에서 수집합니다.
* 모델 클래스를 로드하지 않고 소스를 파싱하므로 DB 연결이나 확장 활성화 상태와 무관하게
* 동작합니다 (문서 생성은 설치되지 않은 확장에도 수행되어야 합니다).
*/
class DataModelCollector
{
/**
* Eloquent 관계 정의 메서드.
*
* @var array<int, string>
*/
private const RELATION_METHODS = [
'hasOne', 'hasMany', 'belongsTo', 'belongsToMany',
'hasOneThrough', 'hasManyThrough',
'morphOne', 'morphMany', 'morphTo', 'morphToMany', 'morphedByMany',
];
/**
* 확장의 데이터 모델 표면을 수집합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @return array{models: array<int, array<string, mixed>>, enums: array<int, array<string, mixed>>, migrations: array<int, array<string, mixed>>, tables: array<int, string>, repositories: array<int, array<string, mixed>>}
*/
public function collect(array $record): array
{
$models = $this->collectModels($record);
$migrations = $this->collectMigrations($record);
$tables = [];
foreach ($migrations as $migration) {
foreach ($migration['creates'] as $table) {
$tables[$table] = true;
}
}
foreach ($models as $model) {
if ($model['table'] !== null) {
$tables[$model['table']] = true;
}
}
$tables = array_keys($tables);
sort($tables);
return [
'models' => $models,
'enums' => $this->collectEnums($record),
'migrations' => $migrations,
'tables' => $tables,
'repositories' => $this->collectRepositories($record),
];
}
/**
* `src/Models/**` 의 모델을 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array<string, mixed>> 모델 목록
*/
private function collectModels(array $record): array
{
$models = [];
foreach ($this->filesIn($record, 'src/Models') as $file) {
$content = (string) file_get_contents($file);
$short = basename($file, '.php');
$models[] = [
'class' => $short,
'relFile' => $this->relative($record, $file),
'table' => $this->stringProperty($content, 'table'),
'fillable' => $this->arrayPropertyCount($content, 'fillable'),
'softDeletes' => (bool) preg_match('/\buse\s+[^;]*\bSoftDeletes\b/', $content),
'userOverrides' => str_contains($content, 'HasUserOverrides'),
'searchable' => str_contains($content, 'FulltextSearchable') || str_contains($content, 'Laravel\Scout\Searchable'),
'relations' => $this->collectRelations($content),
'summary' => $this->classDocSummary($content),
];
}
usort($models, static fn (array $a, array $b): int => $a['class'] <=> $b['class']);
return $models;
}
/**
* 모델 소스에서 관계 정의를 수집합니다.
*
* @param string $content 모델 소스
* @return array<int, array{method: string, type: string, target: string|null}> 관계 목록
*/
private function collectRelations(string $content): array
{
$relations = [];
$alternation = implode('|', self::RELATION_METHODS);
$pattern = '/public\s+function\s+(\w+)\s*\([^)]*\)[^{]*\{(?:[^{}]|\{[^{}]*\})*?\$this->('
.$alternation
.')\s*\(\s*(?:([A-Za-z_\\\\]+)::class)?/s';
if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
foreach ($matches as $m) {
$relations[] = [
'method' => $m[1],
'type' => $m[2],
'target' => ($m[3] ?? '') !== '' ? $this->shortName($m[3]) : null,
];
}
}
return $relations;
}
/**
* `src/Enums/**` 의 Enum 을 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array<string, mixed>> Enum 목록
*/
private function collectEnums(array $record): array
{
$enums = [];
foreach ($this->filesIn($record, 'src/Enums') as $file) {
$content = (string) file_get_contents($file);
$backing = null;
if (preg_match('/^\s*enum\s+\w+\s*:\s*(\w+)/m', $content, $bm)) {
$backing = $bm[1];
}
$cases = [];
if (preg_match_all("/^\s*case\s+(\w+)\s*(?:=\s*'([^']*)')?/m", $content, $cm, PREG_SET_ORDER)) {
foreach ($cm as $c) {
$cases[] = ['name' => $c[1], 'value' => $c[2] ?? null];
}
}
$enums[] = [
'class' => basename($file, '.php'),
'relFile' => $this->relative($record, $file),
'backing' => $backing,
'cases' => $cases,
'summary' => $this->classDocSummary($content),
];
}
usort($enums, static fn (array $a, array $b): int => $a['class'] <=> $b['class']);
return $enums;
}
/**
* `database/migrations/**` 을 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array<string, mixed>> 마이그레이션 목록 (파일명 정렬)
*/
private function collectMigrations(array $record): array
{
$migrations = [];
foreach ($this->filesIn($record, 'database/migrations') as $file) {
$content = (string) file_get_contents($file);
$creates = [];
if (preg_match_all("/Schema::(?:connection\([^)]*\)->)?create\s*\(\s*'([^']+)'/", $content, $m)) {
$creates = array_values(array_unique($m[1]));
}
$alters = [];
if (preg_match_all("/Schema::(?:connection\([^)]*\)->)?table\s*\(\s*'([^']+)'/", $content, $m)) {
$alters = array_values(array_unique($m[1]));
}
$migrations[] = [
'file' => basename($file),
'relFile' => $this->relative($record, $file),
'creates' => $creates,
'alters' => $alters,
'hasDown' => (bool) preg_match('/function\s+down\s*\(/', $content),
];
}
usort($migrations, static fn (array $a, array $b): int => $a['file'] <=> $b['file']);
return $migrations;
}
/**
* Repository 계약과 구현을 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array<string, mixed>> Repository 목록
*/
private function collectRepositories(array $record): array
{
$repositories = [];
foreach (['src/Repositories', 'src/Contracts/Repositories'] as $sub) {
foreach ($this->filesIn($record, $sub) as $file) {
$content = (string) file_get_contents($file);
$repositories[] = [
'class' => basename($file, '.php'),
'relFile' => $this->relative($record, $file),
'isInterface' => (bool) preg_match('/^\s*interface\s+\w+/m', $content),
'summary' => $this->classDocSummary($content),
];
}
}
usort($repositories, static fn (array $a, array $b): int => $a['class'] <=> $b['class']);
return $repositories;
}
/**
* `protected $x = '...'` 형태의 문자열 프로퍼티 값을 읽습니다.
*
* @param string $content 소스
* @param string $name 프로퍼티명
* @return string|null 값 (없으면 null)
*/
private function stringProperty(string $content, string $name): ?string
{
if (preg_match('/\$'.preg_quote($name, '/')."\s*=\s*'([^']*)'/", $content, $m)) {
return $m[1];
}
return null;
}
/**
* `protected $x = [...]` 형태의 배열 프로퍼티 원소 수를 셉니다.
*
* 근사치입니다 — 문서의 규모 감을 주기 위한 값이며 계약 판정에 쓰지 않습니다.
*
* @param string $content 소스
* @param string $name 프로퍼티명
* @return int|null 원소 수 (프로퍼티 없으면 null)
*/
private function arrayPropertyCount(string $content, string $name): ?int
{
if (! preg_match('/\$'.preg_quote($name, '/').'\s*=\s*\[(.*?)\];/s', $content, $m)) {
return null;
}
return preg_match_all("/'[^']*'/", $m[1]);
}
/**
* 클래스 docblock 의 첫 문장을 요약으로 뽑습니다.
*
* @param string $content 소스
* @return string|null 요약 (없으면 null)
*/
private function classDocSummary(string $content): ?string
{
if (! preg_match('#/\*\*(.*?)\*/\s*(?:final\s+|abstract\s+|readonly\s+)*(?:class|enum|interface|trait)\s+\w+#s', $content, $m)) {
return null;
}
foreach (explode("\n", $m[1]) as $line) {
$line = trim(preg_replace('/^\s*\*\s?/', '', $line) ?? '');
if ($line !== '' && ! str_starts_with($line, '@')) {
return $line;
}
}
return null;
}
/**
* FQCN 에서 클래스 짧은 이름을 뽑습니다.
*
* @param string $fqcn 클래스명
* @return string 짧은 이름
*/
private function shortName(string $fqcn): string
{
$parts = explode('\\', trim($fqcn, '\\'));
return end($parts) ?: $fqcn;
}
/**
* 확장 하위 디렉토리의 PHP 파일을 열거합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param string $sub 확장 루트 기준 하위 경로
* @return array<int, string> PHP 파일 절대 경로
*/
private function filesIn(array $record, string $sub): array
{
$dir = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $sub);
if (! is_dir($dir)) {
return [];
}
$files = [];
foreach (File::allFiles($dir) as $file) {
if ($file->getExtension() === 'php') {
$files[] = $file->getPathname();
}
}
return $files;
}
/**
* 확장 루트 기준 상대 경로로 변환합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param string $absolute 절대 경로
* @return string 상대 경로 (POSIX 구분자)
*/
private function relative(array $record, string $absolute): string
{
$base = rtrim((string) $record['path'], '/\\').DIRECTORY_SEPARATOR;
$rel = str_starts_with($absolute, $base) ? substr($absolute, strlen($base)) : $absolute;
return str_replace('\\', '/', $rel);
}
}
@@ -0,0 +1,364 @@
<?php
namespace App\Support\ExtensionDoc;
use App\Extension\AbstractModule;
use App\Extension\AbstractPlugin;
use ReflectionClass;
use Throwable;
/**
* 확장 선언형 표면 수집기
*
* `AbstractModule` / `AbstractPlugin` 이 이미 갖고 있는 선언형 getter 를 실제로 호출해
* 라우트·권한·메뉴·훅·설정·스케줄 등의 표면을 읽습니다. 정규식으로 소스를 긁는 방식과 달리
* 상속 기본값(`getRoutes()` 가 파일 존재 여부로 계산하는 값 등)까지 정확히 반영됩니다.
*
* 읽기 대상은 항상 `_bundled` 소스입니다. 활성 디렉토리에 같은 FQCN 이 이미 로드되어 있으면
* PHP 는 클래스를 재정의할 수 없으므로, `ModuleManager::evalFreshModule()` 과 같은 방식으로
* 진입 클래스명만 바꿔 메모리에 다시 로드합니다 (namespace 유지 → use/extends 정상 동작).
*
* 확장 getter 는 DB·파일시스템·다른 확장에 의존할 수 있으므로 개별 호출을 각각 격리합니다.
* 한 getter 의 실패가 나머지 수집을 중단시키지 않으며, 실패 사유는 `errors` 로 올라가
* 문서에 "수집 실패" 로 드러납니다 (조용한 누락 금지).
*/
class DeclarativeSurfaceCollector
{
/**
* 수집 대상 getter 와 문서상 라벨.
*
* 확장 유형에 없는 getter 는 `method_exists` 로 건너뜁니다 (모듈 전용 · 플러그인 전용 혼재).
*
* @var array<string, string>
*/
public const GETTERS = [
// 라우트·마이그레이션·뷰
'getRoutes' => '라우트 파일',
'getMigrations' => '마이그레이션 경로',
'getViews' => '뷰 경로',
'getSeeders' => '시더',
'getDynamicTables' => '동적 테이블',
// 권한·역할·메뉴
'getPermissions' => '권한 정의',
'getDynamicPermissionIdentifiers' => '동적 권한 식별자',
'getRoles' => '역할 정의',
'getDynamicRoleIdentifiers' => '동적 역할 식별자',
'getAdminMenus' => '관리자 메뉴',
'getCustomMenus' => '사용자 메뉴',
'getDynamicMenuSlugs' => '동적 메뉴 slug',
// 확장점
'getHooks' => '발행 훅 선언',
'getHookListeners' => '훅 리스너',
'getChannels' => '브로드캐스트 채널',
'getSchedules' => '스케줄',
'getMiddleware' => '미들웨어',
'getLayoutExtensions' => '레이아웃 확장',
'getNotificationDefinitions' => '알림 정의',
'getBenchmarkProfiles' => '성능 계측 프로파일',
// 본인인증
'getIdentityPolicies' => 'IDV 정책',
'getIdentityPurposes' => 'IDV 목적',
'getIdentityMessages' => 'IDV 메시지',
// 설정
'getConfig' => 'config 파일',
'getConfigValues' => 'config 값',
'getSettingsSchema' => '설정 스키마',
'getSettingsDefaultsPath' => '설정 기본값 경로',
'getSettingsLayout' => '설정 레이아웃',
'getSettingsRoute' => '설정 라우트',
'getSeoConfigPath' => 'SEO 설정 경로',
// 에셋
'getAssets' => '프론트 에셋',
'getAssetLoadingConfig' => '에셋 로딩 설정',
'getBuiltAssetPaths' => '빌드 산출물 경로',
'getTrustedScriptHosts' => '신뢰 스크립트 호스트',
'getStorageDisk' => '스토리지 디스크',
'getCacheStore' => '캐시 스토어',
// 메타
'getDependencies' => '의존 확장',
'getRequiredCoreVersion' => '코어 최소 버전',
'getLicense' => '라이선스',
'getGithubUrl' => 'GitHub URL',
];
/**
* 확장의 선언형 표면을 수집합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @return array{available: bool, reason: string|null, values: array<string, mixed>, errors: array<string, string>, endpoints: int}
* available=false 이면 values 는 비고 reason 에 사유가 담깁니다.
*/
public function collect(array $record): array
{
$empty = ['available' => false, 'reason' => null, 'values' => [], 'errors' => [], 'endpoints' => 0];
// 확장마다 초기화한다 — 남겨 두면 앞 확장의 실패가 다음 확장의 사유로 새어 나간다.
$this->pathInjectionError = null;
if (($record['entryFile'] ?? null) === null || ($record['entryClass'] ?? null) === null) {
$empty['reason'] = '진입 클래스 없음 (템플릿은 선언형 표면을 갖지 않습니다)';
return $empty;
}
$restore = $this->registerBundledAutoloader($record);
try {
$instance = $this->instantiate($record);
} catch (Throwable $e) {
$restore();
$empty['reason'] = '진입 클래스 로드 실패: '.$e->getMessage();
return $empty;
}
if ($instance === null) {
$restore();
$empty['reason'] = '진입 클래스 인스턴스화 실패: '.$record['entryClass'];
return $empty;
}
$values = [];
$errors = [];
if ($this->pathInjectionError !== null) {
$errors['__path_injection'] = $this->pathInjectionError;
}
try {
foreach (array_keys(self::GETTERS) as $getter) {
if (! method_exists($instance, $getter)) {
continue;
}
try {
$values[$getter] = $instance->{$getter}();
} catch (Throwable $e) {
$errors[$getter] = $e->getMessage();
}
}
} finally {
$restore();
}
return [
'available' => true,
'reason' => null,
'values' => $values,
'errors' => $errors,
'endpoints' => $this->countEndpoints($values['getRoutes'] ?? []),
];
}
/**
* 선언된 라우트 파일에 등록된 엔드포인트 수를 셉니다.
*
* 집계 배지가 말하는 "라우트 수" 는 **주소(엔드포인트) 개수**입니다 — 라우트 파일 개수가
* 아닙니다. 확장 대부분이 파일 1~2개에 수십 개의 주소를 담으므로 파일 수는 규모를 전혀
* 알려주지 않습니다. 이 값은 `docs/api/README.md` 목차의 엔드포인트 수와 같은 것을 세므로
* 두 표가 서로 다른 숫자를 말하지 않습니다.
*
* `Route::match(['GET','POST'], ...)` 는 한 번 등록되지만 주소는 메서드 수만큼이므로
* 배열 길이로 셉니다 (API 문서 생성기와 같은 기준).
*
* @param mixed $routes `getRoutes()` 반환값 (종류 => 파일 경로)
* @return int 엔드포인트 수 (셀 수 없으면 0)
*/
private function countEndpoints(mixed $routes): int
{
if (! is_array($routes)) {
return 0;
}
$verbs = 'get|post|put|patch|delete|options|any|dualSuffix|dualSuffixSegment|dualAsset';
$total = 0;
foreach ($routes as $path) {
if (! is_string($path) || ! is_file($path)) {
continue;
}
$source = (string) file_get_contents($path);
$total += preg_match_all('/Route::(?:'.$verbs.')\s*\(/', $source);
// match 는 메서드 배열의 길이만큼 주소를 만든다.
if (preg_match_all('/Route::match\s*\(\s*\[([^\]]*)\]/', $source, $m) > 0) {
foreach ($m[1] as $methods) {
$total += max(1, preg_match_all('/[\'"]/', $methods) / 2);
}
}
}
return (int) $total;
}
/**
* 진입 클래스를 인스턴스화합니다.
*
* 같은 FQCN 이 이미 로드되어 있으면(활성 디렉토리 확장이 부팅된 경우) 클래스명을 바꿔
* eval 로 다시 로드합니다. 그렇지 않으면 `_bundled` 파일을 직접 include 합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return object|null 확장 인스턴스 (실패 시 null)
*/
/**
* 직전 인스턴스화에서 발생한 경로 주입 실패 사유 (없으면 null).
*/
private ?string $pathInjectionError = null;
private function instantiate(array $record): ?object
{
$fqcn = (string) $record['entryClass'];
$entryFile = (string) $record['entryFile'];
if (! class_exists($fqcn, false)) {
require_once $entryFile;
return class_exists($fqcn, false) ? new $fqcn : null;
}
return $this->evalFreshEntry($record);
}
/**
* 이미 로드된 FQCN 을 피해 `_bundled` 진입 클래스를 새 이름으로 다시 로드합니다.
*
* PHP 는 동일 프로세스에서 클래스를 재정의할 수 없으므로 클래스명만 치환합니다.
* namespace 는 유지하므로 use/extends/implements 가 그대로 동작합니다.
* eval 로 만든 클래스는 `ReflectionClass::getFileName()` 이 비정상이라
* 경로 프로퍼티를 리플렉션으로 직접 주입합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return object|null 확장 인스턴스 (실패 시 null)
*/
private function evalFreshEntry(array $record): ?object
{
$content = @file_get_contents((string) $record['entryFile']);
if ($content === false) {
return null;
}
$short = (string) $record['entryClassShort'];
$uid = '_extdoc_'.bin2hex(random_bytes(6));
$renamed = preg_replace('/\bclass\s+'.preg_quote($short, '/').'\b/', 'class '.$short.$uid, $content, 1);
if (! is_string($renamed)) {
return null;
}
$renamed = preg_replace('/^<\?php\s*/', '', $renamed);
if (! is_string($renamed)) {
return null;
}
eval($renamed);
$freshClass = $record['namespace'].'\\'.$short.$uid;
if (! class_exists($freshClass, false)) {
return null;
}
$instance = new $freshClass;
$this->pathInjectionError = $this->injectExtensionPath($instance, (string) $record['path']);
return $instance;
}
/**
* eval 로 로드한 인스턴스에 확장 디렉토리 경로를 주입합니다.
*
* @param object $instance 확장 인스턴스
* @param string $path 확장 디렉토리 절대 경로
*/
private function injectExtensionPath(object $instance, string $path): ?string
{
$targets = [
AbstractModule::class => 'modulePath',
AbstractPlugin::class => 'pluginPath',
];
foreach ($targets as $class => $property) {
if (! $instance instanceof $class) {
continue;
}
try {
$ref = new ReflectionClass($class);
if (! $ref->hasProperty($property)) {
continue;
}
$prop = $ref->getProperty($property);
$prop->setAccessible(true);
$prop->setValue($instance, $path);
} catch (Throwable $e) {
// 경로 주입 실패는 예외를 던지지 않는다. 그런데 경로 기반 getter(`getRoutes`
// `getMigrations` 등)는 그 상태에서 **예외 없이 빈 값**을 돌려주므로 getter 별
// try/catch 에도 걸리지 않는다 — "없음" 으로 굳는 침묵 경로다. 사유를 올린다.
return $property.' 주입 실패: '.$e->getMessage();
}
}
return null;
}
/**
* `_bundled` composer.json 의 PSR-4 매핑을 임시 오토로더로 등록합니다.
*
* 아직 로드되지 않은 확장 내부 클래스(Listener·Model 등)가 활성 디렉토리가 아니라
* `_bundled` 소스에서 해석되도록 합니다. 수집이 끝나면 반드시 해제해야 하므로
* 해제 클로저를 돌려줍니다 (프로세스 잔류 시 이후 코드가 `_bundled` 를 보게 됨).
*
* @param array<string, mixed> $record 확장 레코드
* @return \Closure 해제 클로저
*/
private function registerBundledAutoloader(array $record): \Closure
{
$composerPath = $record['path'].DIRECTORY_SEPARATOR.'composer.json';
$psr4 = [];
if (is_file($composerPath)) {
$composer = json_decode((string) file_get_contents($composerPath), true);
$declared = $composer['autoload']['psr-4'] ?? null;
if (is_array($declared)) {
foreach ($declared as $prefix => $dir) {
$dirs = is_array($dir) ? $dir : [$dir];
foreach ($dirs as $one) {
$psr4[(string) $prefix][] = rtrim($record['path'].DIRECTORY_SEPARATOR.trim((string) $one, '/\\'), '/\\');
}
}
}
}
if ($psr4 === []) {
return static function (): void {};
}
$loader = static function (string $class) use ($psr4): void {
foreach ($psr4 as $prefix => $dirs) {
if (! str_starts_with($class, $prefix)) {
continue;
}
$relative = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen($prefix))).'.php';
foreach ($dirs as $dir) {
$file = $dir.DIRECTORY_SEPARATOR.$relative;
if (is_file($file)) {
require_once $file;
return;
}
}
}
};
spl_autoload_register($loader, true, true);
return static function () use ($loader): void {
spl_autoload_unregister($loader);
};
}
}
@@ -0,0 +1,194 @@
<?php
namespace App\Support\ExtensionDoc;
/**
* 확장 의존 관계 수집기
*
* manifest 의 `dependencies` 선언을 정방향(내가 의존하는 확장)과 역방향(나에게 의존하는
* 확장) 양쪽으로 해석합니다.
*
* 역방향이 이 수집기의 존재 이유입니다 — 운영자가 "이 확장을 끄면 무엇이 같이 죽는가" 를
* 알아야 하는데, 그 정보는 어느 한 manifest 에도 없고 번들 전수를 교차 스캔해야만 나옵니다.
* 확장명을 하드코딩하지 않고 인벤토리 스캔 결과에서 도출하므로 신규 확장이 자동 편입됩니다.
*/
class DependencyGraphCollector
{
/**
* @var array<int, array<string, mixed>>|null 전수 인벤토리 캐시
*/
private ?array $universe = null;
/**
* @param ExtensionInventory $inventory 번들 확장 인벤토리
*/
public function __construct(private readonly ExtensionInventory $inventory) {}
/**
* 확장의 의존 관계를 수집합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @return array{requires: array<int, array{type: string, id: string, constraint: string, bundled: bool}>, requiredBy: array<int, array{type: string, id: string, constraint: string}>, coreVersion: string|null}
*/
public function collect(array $record): array
{
return [
'requires' => $this->requires($record),
'requiredBy' => $this->requiredBy($record),
'coreVersion' => $this->coreConstraint($record),
];
}
/**
* 이 확장이 의존하는 확장 목록을 반환합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array{type: string, id: string, constraint: string, bundled: bool}>
*/
private function requires(array $record): array
{
$requires = [];
foreach ($this->declaredDependencies($record) as $type => $entries) {
foreach ($entries as $id => $constraint) {
$requires[] = [
'type' => $type,
'id' => (string) $id,
'constraint' => (string) $constraint,
'bundled' => $this->isBundled($type, (string) $id),
];
}
}
usort($requires, static fn (array $a, array $b): int => [$a['type'], $a['id']] <=> [$b['type'], $b['id']]);
return $requires;
}
/**
* 이 확장에 의존하는 확장 목록을 반환합니다 (번들 전수 교차 스캔).
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array{type: string, id: string, constraint: string}>
*/
private function requiredBy(array $record): array
{
$selfType = $this->pluralize((string) $record['type']);
$selfId = (string) $record['id'];
$dependents = [];
foreach ($this->allExtensions() as $other) {
if ($other['id'] === $selfId && $other['type'] === $record['type']) {
continue;
}
$declared = $this->declaredDependencies($other);
$constraint = $declared[$selfType][$selfId] ?? null;
if ($constraint === null) {
continue;
}
$dependents[] = [
'type' => (string) $other['type'],
'id' => (string) $other['id'],
'constraint' => (string) $constraint,
];
}
usort($dependents, static fn (array $a, array $b): int => [$a['type'], $a['id']] <=> [$b['type'], $b['id']]);
return $dependents;
}
/**
* manifest 의 코어 버전 제약을 읽습니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return string|null 코어 버전 제약 (없으면 null)
*/
private function coreConstraint(array $record): ?string
{
$value = $record['manifest']['g7_version'] ?? ($record['manifest']['requires']['g7_version'] ?? null);
return is_string($value) && $value !== '' ? $value : null;
}
/**
* manifest 의 dependencies 선언을 정규화합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array{modules: array<string, string>, plugins: array<string, string>}
*/
private function declaredDependencies(array $record): array
{
$declared = $record['manifest']['dependencies'] ?? [];
// templates 도 정규화한다 — pluralize() 가 'templates' 를 만드는데 여기에 그 키가
// 없으면 템플릿의 역방향 의존(`requiredBy`)이 구조적으로 항상 빈 배열이 된다.
$normalized = ['modules' => [], 'plugins' => [], 'templates' => []];
if (! is_array($declared)) {
return $normalized;
}
foreach (['modules', 'plugins', 'templates'] as $key) {
$entries = $declared[$key] ?? [];
if (! is_array($entries)) {
continue;
}
foreach ($entries as $id => $constraint) {
if (is_string($constraint)) {
$normalized[$key][(string) $id] = $constraint;
}
}
}
return $normalized;
}
/**
* 유형 단수형을 manifest dependencies 의 복수 키로 바꿉니다.
*
* @param string $type 확장 유형
* @return string 복수 키 (`modules` | `plugins` | `templates`)
*/
private function pluralize(string $type): string
{
return $type.'s';
}
/**
* 대상이 번들 확장인지 확인합니다.
*
* @param string $pluralType 복수 키
* @param string $id 확장 식별자
* @return bool 번들 여부
*/
private function isBundled(string $pluralType, string $id): bool
{
$singular = rtrim($pluralType, 's');
foreach ($this->allExtensions() as $ext) {
if ($ext['type'] === $singular && $ext['id'] === $id) {
return true;
}
}
return false;
}
/**
* 번들 확장 전수를 반환합니다 (1회 스캔 후 캐시).
*
* @return array<int, array<string, mixed>> 확장 레코드 목록
*/
private function allExtensions(): array
{
if ($this->universe === null) {
$this->universe = $this->inventory->collect('all');
}
return $this->universe;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,322 @@
<?php
namespace App\Support\ExtensionDoc;
use App\Extension\ExtensionManager;
use Illuminate\Support\Facades\File;
use InvalidArgumentException;
/**
* 번들 확장 인벤토리
*
* `{modules,plugins,templates}/_bundled/*` 를 패턴 스캔해 확장 목록과 manifest 를
* 로드합니다. 확장명을 하드코딩하지 않으므로 신규 확장이 추가되면 자동으로 편입됩니다
* (동적 로딩 원칙).
*
* 문서 생성 대상은 `_bundled` 뿐입니다. 활성 디렉토리는 update 커맨드의 산출물이며
* 비번들 제3자 확장이 섞여 있어 집필 대상이 아닙니다.
*/
class ExtensionInventory
{
/**
* @var string 모듈 유형
*/
public const TYPE_MODULE = 'module';
/**
* @var string 플러그인 유형
*/
public const TYPE_PLUGIN = 'plugin';
/**
* @var string 템플릿 유형
*/
public const TYPE_TEMPLATE = 'template';
/**
* 유형 → 저장소 최상위 디렉토리 / manifest 파일명 / 진입 클래스 파일명 매핑
*
* @var array<string, array{dir: string, manifest: string, entryFile: string|null, entryClass: string|null, rootNamespace: string|null}>
*/
private const TYPE_MAP = [
self::TYPE_MODULE => [
'dir' => 'modules',
'manifest' => 'module.json',
'entryFile' => 'module.php',
'entryClass' => 'Module',
'rootNamespace' => 'Modules',
],
self::TYPE_PLUGIN => [
'dir' => 'plugins',
'manifest' => 'plugin.json',
'entryFile' => 'plugin.php',
'entryClass' => 'Plugin',
'rootNamespace' => 'Plugins',
],
self::TYPE_TEMPLATE => [
'dir' => 'templates',
'manifest' => 'template.json',
'entryFile' => null,
'entryClass' => null,
'rootNamespace' => null,
],
];
/**
* 지원 유형 목록을 반환합니다.
*
* @return array<int, string> 유형 목록
*/
public static function types(): array
{
return array_keys(self::TYPE_MAP);
}
/**
* 유형에 대응하는 저장소 디렉토리명을 반환합니다.
*
* @param string $type 확장 유형
* @return string|null 디렉토리명 (미지원 유형이면 null)
*/
public static function directoryFor(string $type): ?string
{
return self::TYPE_MAP[$type]['dir'] ?? null;
}
/**
* scope 문자열을 파싱합니다.
*
* @param string $scope `all` | `module:{id}` | `plugin:{id}` | `template:{id}`
* @return array{type: string|null, id: string|null} 파싱 결과 (all 이면 둘 다 null)
*/
public static function parseScope(string $scope): array
{
$scope = trim($scope);
if ($scope === '' || $scope === 'all') {
return ['type' => null, 'id' => null];
}
// 해석 실패를 "전체" 로 되돌리지 않는다. `--scope=modules:board`(복수형 오타)나
// `--scope=modul:board` 가 조용히 번들 20개 전 문서를 기록하게 되기 때문이다.
// 반면 `--scope=module:없는id` 는 이미 명확한 실패로 처리되므로, 두 오타가 정반대로
// 다뤄지는 비대칭을 없앤다.
if (! str_contains($scope, ':')) {
throw new InvalidArgumentException(
"scope 형식이 올바르지 않습니다: '{$scope}'. all | module:{id} | plugin:{id} | template:{id} 중 하나여야 합니다."
);
}
[$type, $id] = explode(':', $scope, 2);
$type = trim($type);
$id = trim($id);
if (! isset(self::TYPE_MAP[$type])) {
throw new InvalidArgumentException(
"알 수 없는 확장 유형입니다: '{$type}'. ".implode(' | ', array_keys(self::TYPE_MAP)).' 중 하나여야 합니다.'
);
}
if ($id === '') {
throw new InvalidArgumentException("scope 에 확장 식별자가 없습니다: '{$scope}'.");
}
return ['type' => $type, 'id' => $id];
}
/**
* scope 에 해당하는 번들 확장 목록을 수집합니다.
*
* @param string $scope 범위 (`all` | `{type}:{id}`)
* @return array<int, array<string, mixed>> 확장 레코드 목록 (유형 → 식별자 정렬)
*/
public function collect(string $scope = 'all'): array
{
$parsed = self::parseScope($scope);
$records = [];
$this->malformed = [];
foreach (self::TYPE_MAP as $type => $meta) {
if ($parsed['type'] !== null && $parsed['type'] !== $type) {
continue;
}
$bundledRoot = base_path($meta['dir'].'/_bundled');
if (! is_dir($bundledRoot)) {
continue;
}
foreach (File::directories($bundledRoot) as $dirPath) {
$id = basename($dirPath);
if ($parsed['id'] !== null && $parsed['id'] !== $id) {
continue;
}
$record = $this->buildRecord($type, $id, $dirPath);
if ($record !== null) {
$records[] = $record;
}
}
}
usort($records, function (array $a, array $b): int {
return [$a['type'], $a['id']] <=> [$b['type'], $b['id']];
});
return $records;
}
/**
* 단일 확장 레코드를 조회합니다.
*
* @param string $type 확장 유형
* @param string $id 확장 식별자
* @return array<string, mixed>|null 확장 레코드 (없으면 null)
*/
public function find(string $type, string $id): ?array
{
$records = $this->collect("{$type}:{$id}");
return $records[0] ?? null;
}
/**
* @var array<int, array{type: string, id: string, manifest: string, reason: string}> manifest 를 읽지 못한 디렉토리
*/
private array $malformed = [];
/**
* 직전 `collect()` 에서 manifest 파싱에 실패한 디렉토리 목록을 반환합니다.
*
* 호출자가 이 목록을 보고해야 "확장이 없다" 와 "읽지 못했다" 가 구분됩니다.
*
* @return array<int, array{type: string, id: string, manifest: string, reason: string}> 실패 목록
*/
public function malformed(): array
{
return $this->malformed;
}
/**
* 확장 레코드를 조립합니다.
*
* manifest 가 없거나 JSON 파싱에 실패한 디렉토리는 확장이 아니므로 제외합니다
* (`_backup_*` · 업데이트 중 임시 디렉토리 등).
*
* @param string $type 확장 유형
* @param string $id 확장 식별자
* @param string $dirPath 확장 절대 경로
* @return array<string, mixed>|null 확장 레코드 (manifest 부재 시 null)
*/
private function buildRecord(string $type, string $id, string $dirPath): ?array
{
$meta = self::TYPE_MAP[$type];
$manifestPath = $dirPath.DIRECTORY_SEPARATOR.$meta['manifest'];
if (! is_file($manifestPath)) {
return null;
}
$manifest = json_decode((string) file_get_contents($manifestPath), true);
if (! is_array($manifest)) {
// manifest 가 있는데 못 읽은 것은 "확장이 아님"(`_backup_*` 등) 과 다르다.
// 조용히 탈락시키면 그 확장이 문서 체계에서 통째로 사라지고, 검사 대상 수
// 자체가 줄어 "20개 중 5개 보유" 분모까지 함께 줄어 회귀로 보이지 않는다.
$this->malformed[] = [
'type' => $type,
'id' => $id,
'manifest' => $meta['manifest'],
'reason' => json_last_error_msg(),
];
return null;
}
$namespace = $meta['rootNamespace'] !== null
? $meta['rootNamespace'].'\\'.ExtensionManager::directoryToNamespace($id)
: null;
$entryFile = $meta['entryFile'] !== null
? $dirPath.DIRECTORY_SEPARATOR.$meta['entryFile']
: null;
return [
'type' => $type,
'id' => $id,
'label' => self::typeLabel($type),
'path' => $dirPath,
'relPath' => $meta['dir'].'/_bundled/'.$id,
'manifest' => $manifest,
'manifestFile' => $meta['manifest'],
'manifestPath' => $manifestPath,
'namespace' => $namespace,
'entryFile' => ($entryFile !== null && is_file($entryFile)) ? $entryFile : null,
'entryClass' => $namespace !== null ? $namespace.'\\'.$meta['entryClass'] : null,
'entryClassShort' => $meta['entryClass'],
'docsPath' => $dirPath.DIRECTORY_SEPARATOR.'docs',
'version' => (string) ($manifest['version'] ?? ''),
'name' => self::localizedName($manifest, $id),
'description' => self::localized($manifest['description'] ?? ''),
];
}
/**
* 유형의 한국어 라벨을 반환합니다.
*
* @param string $type 확장 유형
* @return string 한국어 라벨
*/
public static function typeLabel(string $type): string
{
return match ($type) {
self::TYPE_MODULE => '모듈',
self::TYPE_PLUGIN => '플러그인',
self::TYPE_TEMPLATE => '템플릿',
default => $type,
};
}
/**
* manifest 의 name 을 한국어 우선으로 해석합니다.
*
* @param array<string, mixed> $manifest manifest 배열
* @param string $fallback 이름이 없을 때 사용할 값
* @return string 확장명
*/
public static function localizedName(array $manifest, string $fallback): string
{
$name = self::localized($manifest['name'] ?? '');
return $name !== '' ? $name : $fallback;
}
/**
* 다국어 값(문자열 또는 로케일 배열)을 한국어 우선으로 해석합니다.
*
* @param mixed $value manifest 값
* @return string 해석된 문자열 (해석 불가 시 빈 문자열)
*/
public static function localized(mixed $value): string
{
if (is_string($value)) {
return $value;
}
if (is_array($value)) {
foreach (['ko', 'en'] as $locale) {
if (isset($value[$locale]) && is_string($value[$locale])) {
return $value[$locale];
}
}
foreach ($value as $item) {
if (is_string($item)) {
return $item;
}
}
}
return '';
}
}
@@ -0,0 +1,531 @@
<?php
namespace App\Support\ExtensionDoc;
use Illuminate\Support\Facades\File;
/**
* 확장 프론트엔드 진입점 수집기
*
* 레이아웃 JSON · 액션 핸들러 · 전역 재등록 진입점 · 컴포넌트 · 빌드 산출물을 수집합니다.
*
* 레이아웃 경로는 유형마다 다릅니다 — 모듈/플러그인은 `resources/layouts/`, 템플릿은
* `layouts/` 가 루트입니다. 유형별 분기를 이 수집기 한 곳에 두어, 소비자(스캐폴더·검사
* 스크립트)가 경로 규약을 각자 알 필요가 없게 합니다.
*/
class FrontendInventory
{
/**
* 확장의 프론트엔드 표면을 수집합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @return array<string, mixed> 프론트 인벤토리
*/
public function collect(array $record): array
{
$layouts = $this->collectLayouts($record);
return [
'layoutRoot' => $this->layoutRoot($record),
'layouts' => $layouts,
'layoutGroups' => $this->groupLayouts($layouts),
'layoutExtensions' => $this->collectJsonFiles($record, $this->layoutExtensionRoot($record)),
'handlers' => $this->collectHandlers($record),
'entryPoints' => $this->collectEntryPoints($record),
'components' => $this->collectComponents($record),
'builtAssets' => $this->collectBuiltAssets($record),
'vendoredAssets' => $this->collectVendoredAssets($record),
'customDir' => is_dir($record['path'].DIRECTORY_SEPARATOR.'custom'),
'editorSpec' => $this->collectEditorSpec($record),
'routesJson' => is_file($record['path'].DIRECTORY_SEPARATOR.'routes.json') ? 'routes.json' : null,
'routeCount' => $this->countDeclaredRoutes($record),
];
}
/**
* `routes.json` 에 선언된 주소 수를 셉니다 (셀 수 없으면 null).
*
* 템플릿은 선언형 표면(`getRoutes()`)을 갖지 않으므로 집계 배지의 "라우트 수" 가
* 구조적으로 항상 0 이 됩니다 — 주소를 `routes.json` 에 적기 때문입니다. 0 은 사실이
* 아닌데 템플릿에는 "확인하지 못함" 안내도 붙지 않아(선언형 표면 부재가 정상이라)
* 단서 없이 사실처럼 읽힙니다. 실측은 `sirsoft-basic` 40 · `sirsoft-admin_basic` 29.
*
* "라우트 수 = 주소 개수" 규율은 모듈·플러그인과 같습니다.
*
* 읽지 못한 것과 없는 것은 구분합니다 — 파일이 없으면 `null`, 파일이 깨졌어도 `null`
* 입니다. 0 을 돌려주면 "주소가 없다" 는 사실 주장이 됩니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return int|null 주소 수, 셀 수 없으면 null
*/
private function countDeclaredRoutes(array $record): ?int
{
$path = $record['path'].DIRECTORY_SEPARATOR.'routes.json';
if (! is_file($path)) {
return null;
}
$data = json_decode((string) @file_get_contents($path), true);
if (! is_array($data) || ! isset($data['routes']) || ! is_array($data['routes'])) {
return null;
}
return count(array_filter(
$data['routes'],
static fn (mixed $row): bool => is_array($row) && isset($row['path']),
));
}
/**
* 유형별 레이아웃 루트(확장 루트 기준 상대 경로)를 반환합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return string 레이아웃 루트
*/
private function layoutRoot(array $record): string
{
return $record['type'] === ExtensionInventory::TYPE_TEMPLATE ? 'layouts' : 'resources/layouts';
}
/**
* 유형별 레이아웃 확장 조각 루트(확장 루트 기준 상대 경로)를 반환합니다.
*
* 레이아웃과 같은 규율이다 — 템플릿은 확장 루트 직속, 모듈·플러그인은 `resources/`
* 아래. 형제인 `layoutRoot()` 만 유형을 갈랐던 탓에 템플릿의 조각이 항상 빈 목록으로
* 수집돼(`sirsoft-basic` 실측 1건) 문서에 "없음" 으로 실렸다.
*
* @param array<string, mixed> $record 확장 레코드
* @return string 레이아웃 확장 루트
*/
private function layoutExtensionRoot(array $record): string
{
return $record['type'] === ExtensionInventory::TYPE_TEMPLATE ? 'extensions' : 'resources/extensions';
}
/**
* 레이아웃 JSON 을 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array<string, mixed>> 레이아웃 목록
*/
private function collectLayouts(array $record): array
{
$layouts = [];
foreach ($this->collectJsonFiles($record, $this->layoutRoot($record)) as $rel) {
$abs = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $rel);
$root = $this->layoutRoot($record).'/';
$inner = str_starts_with($rel, $root) ? substr($rel, strlen($root)) : $rel;
$segments = explode('/', $inner);
$layouts[] = [
'relFile' => $rel,
'name' => basename($inner, '.json'),
'group' => count($segments) > 1 ? $segments[0] : '(root)',
'partial' => str_starts_with(basename($inner), '_'),
'extends' => $this->readJsonString($abs, 'extends'),
];
}
return $layouts;
}
/**
* 레이아웃을 그룹(admin/user 등)별로 집계합니다.
*
* @param array<int, array<string, mixed>> $layouts 레이아웃 목록
* @return array<string, int> 그룹 => 개수
*/
private function groupLayouts(array $layouts): array
{
$groups = [];
foreach ($layouts as $layout) {
$groups[$layout['group']] = ($groups[$layout['group']] ?? 0) + 1;
}
ksort($groups);
return $groups;
}
/**
* 액션 핸들러 이름을 수집합니다.
*
* `handlerMap` 객체의 최상위 키가 핸들러 이름이며, 엔트리포인트가
* `{identifier}.{name}` 으로 네임스페이스를 붙여 등록합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array{namespace: string|null, names: array<int, string>, source: string|null}
*/
private function collectHandlers(array $record): array
{
$candidates = [
'resources/js/handlers/index.ts',
'src/handlers/index.ts',
'resources/js/index.ts',
'src/index.ts',
];
foreach ($candidates as $rel) {
$abs = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $rel);
if (! is_file($abs)) {
continue;
}
$content = (string) file_get_contents($abs);
$names = [];
// 핸들러 맵 이름은 확장마다 다르다 (`handlerMap` / `handlers` + alias 재수출).
// 앞선 후보가 alias 대입(`handlerMap = handlers;`)이면 객체 리터럴이 아니므로 비고,
// 다음 후보에서 실제 리터럴을 찾는다.
foreach (['handlerMap', 'handlers'] as $objectName) {
$names = $this->objectKeys($content, $objectName);
if ($names !== []) {
break;
}
}
if ($names === []) {
$names = $this->literalHandlerNames($content);
}
if ($names !== []) {
return [
'namespace' => $record['type'] === ExtensionInventory::TYPE_TEMPLATE ? null : $record['id'],
'names' => $names,
'source' => $rel,
];
}
}
return ['namespace' => null, 'names' => [], 'source' => null];
}
/**
* 전역 재등록 진입점(`window.__[Name]`)과 초기화 함수를 수집합니다.
*
* 로케일 전환 후 액션이 무반응이 되는 결함을 막는 계약이므로, 노출 여부 자체가
* 문서에 드러나야 합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array{global: string|null, initFunction: string|null, source: string|null}
*/
private function collectEntryPoints(array $record): array
{
$candidates = ['resources/js/index.ts', 'src/index.ts', 'src/index.tsx'];
foreach ($candidates as $rel) {
$abs = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $rel);
if (! is_file($abs)) {
continue;
}
$content = (string) file_get_contents($abs);
$global = null;
if (preg_match('/window[^;\n]*\)\.\s*(__\w+)\s*=/', $content, $m)) {
$global = $m[1];
}
$init = null;
foreach (['initModule', 'initPlugin', 'initTemplate'] as $fn) {
if (preg_match('/function\s+'.$fn.'\s*\(/', $content)) {
$init = $fn;
break;
}
}
if ($global !== null || $init !== null) {
return ['global' => $global, 'initFunction' => $init, 'source' => $rel];
}
}
return ['global' => null, 'initFunction' => null, 'source' => null];
}
/**
* 템플릿이 제공하는 컴포넌트를 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array{total: int, byCategory: array<string, int>, root: string|null}
*/
private function collectComponents(array $record): array
{
$root = 'src/components';
$dir = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $root);
if (! is_dir($dir)) {
return ['total' => 0, 'byCategory' => [], 'root' => null];
}
$byCategory = [];
$total = 0;
foreach (File::allFiles($dir) as $file) {
if ($file->getExtension() !== 'tsx') {
continue;
}
if (str_contains(str_replace('\\', '/', $file->getPathname()), '/__tests__/')) {
continue;
}
$relative = str_replace('\\', '/', $file->getRelativePath());
$category = $relative === '' ? '(root)' : explode('/', $relative)[0];
$byCategory[$category] = ($byCategory[$category] ?? 0) + 1;
$total++;
}
ksort($byCategory);
return ['total' => $total, 'byCategory' => $byCategory, 'root' => $root];
}
/**
* 커밋된 빌드 산출물을 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, string> 산출물 상대 경로
*/
private function collectBuiltAssets(array $record): array
{
$dir = $record['path'].DIRECTORY_SEPARATOR.'dist';
if (! is_dir($dir)) {
return [];
}
$files = [];
foreach (File::allFiles($dir) as $file) {
if (! in_array($file->getExtension(), ['js', 'css'], true)) {
continue;
}
$rel = $this->relative($record, $file->getPathname());
if (str_starts_with($rel, 'dist/vendor/')) {
continue;
}
$files[] = $rel;
}
sort($files);
return $files;
}
/**
* 동봉(self-hosted) 제3자 자산을 수집합니다.
*
* 외부 CDN 대신 확장이 자기 서버에서 제공하는 구동 자산이며, 버전이 디렉토리명에
* 드러나므로 문서에 그대로 노출합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, string> `{라이브러리}/{버전}` 목록
*/
private function collectVendoredAssets(array $record): array
{
$dir = $record['path'].DIRECTORY_SEPARATOR.'dist'.DIRECTORY_SEPARATOR.'vendor';
if (! is_dir($dir)) {
return [];
}
$entries = [];
foreach (File::directories($dir) as $libPath) {
$lib = basename($libPath);
$versions = array_map('basename', File::directories($libPath));
if ($versions === []) {
$entries[] = $lib;
continue;
}
foreach ($versions as $version) {
$entries[] = $lib.'/'.$version;
}
}
sort($entries);
return $entries;
}
/**
* 편집기 스펙(단일 파일 / 분할) 보유 형태를 판정합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array{manifest: bool, split: int}
*/
private function collectEditorSpec(array $record): array
{
$manifest = is_file($record['path'].DIRECTORY_SEPARATOR.'editor-spec.json');
$splitDir = $record['path'].DIRECTORY_SEPARATOR.'editor-spec';
$split = 0;
if (is_dir($splitDir)) {
foreach (File::allFiles($splitDir) as $file) {
if ($file->getExtension() === 'json') {
$split++;
}
}
}
return ['manifest' => $manifest, 'split' => $split];
}
/**
* 하위 디렉토리의 JSON 파일 상대 경로를 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param string $sub 확장 루트 기준 하위 경로
* @return array<int, string> 상대 경로 목록 (정렬)
*/
private function collectJsonFiles(array $record, string $sub): array
{
$dir = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $sub);
if (! is_dir($dir)) {
return [];
}
$files = [];
foreach (File::allFiles($dir) as $file) {
if ($file->getExtension() === 'json') {
$files[] = $this->relative($record, $file->getPathname());
}
}
sort($files);
return $files;
}
/**
* JSON 파일에서 최상위 문자열 키 값을 읽습니다.
*
* @param string $absolute 파일 절대 경로
* @param string $key 키
* @return string|null 값 (없거나 문자열이 아니면 null)
*/
private function readJsonString(string $absolute, string $key): ?string
{
$data = json_decode((string) @file_get_contents($absolute), true);
return is_array($data) && isset($data[$key]) && is_string($data[$key]) ? $data[$key] : null;
}
/**
* `export const {name} = { ... }` 객체의 최상위 키를 뽑습니다.
*
* @param string $content TS 소스
* @param string $name 객체 변수명
* @return array<int, string> 키 목록
*/
private function objectKeys(string $content, string $name): array
{
// 타입 주석이 붙은 선언(`handlerMap: Record<string, (...a) => unknown> = {`)까지 잡되,
// alias 대입(`handlerMap = handlers;`)은 잡지 않는다. `[^;{]*` 가 문(statement) 경계를
// 넘지 못하게 하고, `=\s*\{` 로 객체 리터럴 대입만 받는다.
if (! preg_match('/\b'.preg_quote($name, '/').'\b[^;{]*=\s*\{/', $content, $m, PREG_OFFSET_CAPTURE)) {
return [];
}
$open = strpos($content, '{', (int) $m[0][1]);
if ($open === false) {
return [];
}
$depth = 0;
$len = strlen($content);
$close = null;
for ($i = $open; $i < $len; $i++) {
$ch = $content[$i];
if ($ch === '{') {
$depth++;
} elseif ($ch === '}') {
$depth--;
if ($depth === 0) {
$close = $i;
break;
}
}
}
if ($close === null) {
return [];
}
$body = substr($content, $open + 1, $close - $open - 1);
$keys = [];
foreach (explode("\n", $body) as $line) {
$line = trim($line);
if ($line === '' || str_starts_with($line, '//') || str_starts_with($line, '*') || str_starts_with($line, '/*')) {
continue;
}
if (preg_match('/^([A-Za-z_$][\w$]*)\s*[,:]/', $line, $km)) {
$keys[] = $km[1];
}
}
return array_values(array_unique($keys));
}
/**
* `registerHandler(...)` 인자에서 핸들러 이름을 뽑습니다.
*
* 두 형태를 모두 봅니다 — 리터럴(`'name'`)과 식별자 보간 템플릿 리터럴
* (`` `${PLUGIN_IDENTIFIER}.name` ``). 후자를 놓치면 핸들러 맵을 쓰지 않고 개별
* 등록하는 확장(gdpr 등)이 "핸들러 0개" 로 잘못 집계됩니다.
*
* @param string $content TS 소스
* @return array<int, string> 핸들러 이름 목록
*/
private function literalHandlerNames(string $content): array
{
$names = [];
if (preg_match_all("/registerHandler\s*\(\s*'([^']+)'/", $content, $m)) {
foreach ($m[1] as $name) {
$names[] = $this->stripIdentifierPrefix($name);
}
}
if (preg_match_all('/registerHandler\s*\(\s*`\$\{[^}]+\}\.([A-Za-z_$][\w$]*)`/', $content, $m)) {
$names = array_merge($names, $m[1]);
}
return array_values(array_unique($names));
}
/**
* `{identifier}.{handler}` 형태의 이름에서 확장 식별자 접두를 떼어냅니다.
*
* 등록 코드는 네임스페이스를 붙인 전체 이름을 쓰지만, 표는 핸들러 이름과 호출 이름을
* 각각 보여주므로 접두를 벗긴 이름이 필요합니다.
*
* @param string $name 등록된 이름
* @return string 접두를 뗀 핸들러 이름
*/
private function stripIdentifierPrefix(string $name): string
{
$pos = strrpos($name, '.');
return $pos === false ? $name : substr($name, $pos + 1);
}
/**
* 확장 루트 기준 상대 경로로 변환합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param string $absolute 절대 경로
* @return string 상대 경로 (POSIX 구분자)
*/
private function relative(array $record, string $absolute): string
{
$base = rtrim((string) $record['path'], '/\\').DIRECTORY_SEPARATOR;
$rel = str_starts_with($absolute, $base) ? substr($absolute, strlen($base)) : $absolute;
return str_replace('\\', '/', $rel);
}
}
+527
View File
@@ -0,0 +1,527 @@
<?php
namespace App\Support\ExtensionDoc;
use Illuminate\Support\Facades\File;
/**
* 확장 훅 인벤토리
*
* 확장이 **발행하는 훅**과 **구독하는 훅**(리스너의 `getSubscribedHooks()`)을 수집합니다.
*
* 발행 훅의 1차 출처는 확장이 `getHooks()` 로 **선언한 목록**입니다. 소스 스캔은 그 선언을
* 보강할 뿐입니다 — 훅 이름을 `self::PLUGIN_ID.'.consent.granted'` 처럼 조립하는 확장이
* 실재하고, 그런 호출은 리터럴 스캔이 원리상 읽을 수 없기 때문입니다. 스캔만 믿으면 훅을
* 12곳에서 발행하는 확장이 "훅을 발행하지 않습니다" 로 문서화됩니다(실제 `sirsoft-gdpr`).
* 선언은 유형과 ko/en 설명까지 갖고 있어 스캔이 만들 수 없는 정보를 준다는 이점도 있습니다.
*
* 구독 훅은 `_bundled` 소스 파일을 직접 파싱합니다. 리스너 클래스를 로드해 static 메서드를
* 호출하면 활성 디렉토리에 이미 로드된 동일 FQCN 이 우선하므로, `_bundled` 를 고쳐도 그
* 변경이 문서에 반영되지 않습니다. 문서 SSoT 는 `_bundled` 소스이므로 파싱으로 읽습니다.
*/
class HookInventory
{
/**
* 훅 발행 호출 형태 → 훅 유형.
*
* @var array<string, string>
*/
private const EMIT_FORMS = [
'doAction' => 'action',
'applyFilters' => 'filter',
'broadcast' => 'broadcast',
];
/**
* 훅 이름 리터럴을 갖는 발행 호출을 찾는 패턴.
*
* 첫 인자가 리터럴이 아닌(변수/보간) 호출은 이름을 정적으로 알 수 없으므로 별도 집계한다.
*/
private const EMIT_LITERAL = "/HookManager::(doAction|applyFilters|broadcast)\s*\(\s*'([^']+)'/";
/**
* 발행 호출 전수(리터럴 여부 무관)를 세는 패턴.
*/
private const EMIT_ANY = '/HookManager::(doAction|applyFilters|broadcast)\s*\(/';
/**
* 확장의 훅 표면을 수집합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @param array<int, mixed> $declared 확장이 `getHooks()` 로 선언한 발행 훅 목록
* @return array{published: array<int, array<string, mixed>>, publishedSites: int, publishedDynamic: int, publishedUndeclared: int, subscribed: array<int, array<string, mixed>>, listeners: array<int, array<string, mixed>>}
*/
public function collect(array $record, array $declared = []): array
{
$published = $this->collectPublished($record, $declared);
$listeners = $this->collectListeners($record);
$subscribed = [];
foreach ($listeners as $listener) {
foreach ($listener['hooks'] as $hook) {
$subscribed[] = $hook + ['listener' => $listener['class'], 'listenerFile' => $listener['relFile']];
}
}
usort($subscribed, static fn (array $a, array $b): int => [$a['name'], $a['listener']] <=> [$b['name'], $b['listener']]);
return [
'published' => $published['hooks'],
'publishedSites' => $published['sites'],
'publishedDynamic' => $published['dynamic'],
'publishedUndeclared' => $published['undeclared'],
'subscribed' => $subscribed,
'listeners' => $listeners,
];
}
/**
* 확장이 발행하는 훅을 수집합니다.
*
* 선언(`getHooks()`)이 1차 출처이고 소스 스캔이 보강합니다. 선언에만 있는 훅은 호출
* 지점 없이 표에 남고(이름·유형·설명은 선언이 준다), 스캔에만 있는 훅은 `declared`
* 를 false 로 실어 "선언되지 않음" 을 문서가 드러낼 수 있게 합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param array<int, mixed> $declared `getHooks()` 선언 목록
* @return array{hooks: array<int, array<string, mixed>>, sites: int, dynamic: int, undeclared: int}
* sites 는 리터럴/동적을 합한 전체 호출 지점 수
*/
private function collectPublished(array $record, array $declared = []): array
{
$byName = $this->declaredHooks($declared);
$sites = 0;
$literalSites = 0;
foreach ($this->phpFiles($record) as $file) {
$content = (string) file_get_contents($file);
if (! str_contains($content, 'HookManager::')) {
continue;
}
$sites += preg_match_all(self::EMIT_ANY, $content);
if (! preg_match_all(self::EMIT_LITERAL, $content, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
continue;
}
foreach ($matches as $m) {
$literalSites++;
$form = $m[1][0];
$name = $m[2][0];
$line = substr_count(substr($content, 0, (int) $m[0][1]), "\n") + 1;
$rel = $this->relative($record, $file);
if (! isset($byName[$name])) {
$byName[$name] = [
'name' => $name,
'type' => self::EMIT_FORMS[$form] ?? $form,
'description' => null,
'parameters' => [],
'declared' => false,
'sites' => [],
];
}
$scannedType = self::EMIT_FORMS[$form] ?? $form;
if (($byName[$name]['typeDeclared'] ?? true) === false
&& $byName[$name]['type'] !== $scannedType) {
// 선언이 유형을 말하지 않았고 소스가 다른 유형으로 발행한다 —
// 기본값이 사실을 덮은 자리이므로 실측을 따르고 표에 사유를 남긴다.
$byName[$name]['type'] = $scannedType;
$byName[$name]['typeInferred'] = true;
}
$byName[$name]['sites'][] = ['file' => $rel, 'line' => $line];
}
}
ksort($byName);
$undeclared = 0;
foreach ($byName as $hook) {
if ($hook['declared'] === false) {
$undeclared++;
}
}
return [
'hooks' => array_values($byName),
'sites' => $sites,
'dynamic' => max(0, $sites - $literalSites),
'undeclared' => $undeclared,
];
}
/**
* `getHooks()` 선언을 훅 이름 색인으로 정규화합니다.
*
* 선언 형식이 어긋난 항목(이름 없음 등)은 조용히 버리지 않고 건너뛰되, 이름만 있으면
* 유형·설명이 없어도 표에 남깁니다 — 발행 사실 자체가 확장점 공개의 핵심입니다.
*
* @param array<int, mixed> $declared 선언 목록
* @return array<string, array<string, mixed>> 훅 이름 → 항목
*/
private function declaredHooks(array $declared): array
{
$byName = [];
foreach ($declared as $hook) {
if (! is_array($hook)) {
continue;
}
$name = $hook['name'] ?? null;
if (! is_string($name) || $name === '') {
continue;
}
$description = $hook['description'] ?? null;
if (is_array($description)) {
// ko 우선 — 확장 문서는 한국어다. ko 가 없으면 첫 값을 쓴다.
$description = $description['ko'] ?? (reset($description) ?: null);
}
$byName[$name] = [
'name' => $name,
// 유형 미기재를 조용히 `action` 으로 굳히면, 실제로 filter 인 훅이
// action 으로 문서화되어 구독하는 쪽이 반환값 계약을 잘못 읽는다.
// 미기재 사실을 남겨 스캔 결과와 어긋날 때 드러나게 한다.
'type' => is_string($hook['type'] ?? null) ? $hook['type'] : 'action',
'typeDeclared' => is_string($hook['type'] ?? null),
'description' => is_string($description) && $description !== '' ? $description : null,
'parameters' => is_array($hook['parameters'] ?? null) ? $hook['parameters'] : [],
'declared' => true,
'sites' => [],
];
}
return $byName;
}
/**
* 확장의 훅 리스너와 각 리스너가 구독하는 훅을 수집합니다.
*
* `src/Listeners/` 를 스캔해 리스너와 그 구독 훅을 모읍니다. 명시 등록(`getHookListeners()`)
* 여부는 여기서 판정하지 않습니다 — 스캐폴더가 선언형 표면의 `getHookListeners` 값과
* 대조해 표기합니다. 이 배열에는 `registered` 키가 없습니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, array<string, mixed>> 리스너 목록
*/
private function collectListeners(array $record): array
{
$listenerDir = $record['path'].DIRECTORY_SEPARATOR.'src'.DIRECTORY_SEPARATOR.'Listeners';
$listeners = [];
if (! is_dir($listenerDir)) {
return $listeners;
}
foreach (File::allFiles($listenerDir) as $file) {
if ($file->getExtension() !== 'php') {
continue;
}
$path = $file->getPathname();
$content = (string) file_get_contents($path);
$class = $this->fqcnOf($content);
$listeners[] = [
'class' => $class ?? $file->getFilenameWithoutExtension(),
'shortClass' => $file->getFilenameWithoutExtension(),
'relFile' => $this->relative($record, $path),
'implementsContract' => str_contains($content, 'HookListenerInterface'),
'hooks' => $this->parseSubscribedHooks($content),
];
}
usort($listeners, static fn (array $a, array $b): int => $a['shortClass'] <=> $b['shortClass']);
return $listeners;
}
/**
* `getSubscribedHooks()` 메서드 본문에서 구독 훅 선언을 파싱합니다.
*
* 반환 배열의 최상위 항목만 봅니다 — `'훅이름' => [ ... ]` 형태의 키가 훅 이름이고,
* 값 슬라이스에서 method/priority/type 을 읽습니다. `type` 미선언은 action 으로 간주하되
* 그 사실을 `typeDeclared` 로 남깁니다 (filter 훅의 type 마커 누락은 별도 룰이 검사).
*
* @param string $content 리스너 소스
* @return array<int, array<string, mixed>> 구독 훅 목록
*/
private function parseSubscribedHooks(string $content): array
{
$body = $this->extractReturnArray($content, 'getSubscribedHooks');
if ($body === null) {
return [];
}
$hooks = [];
foreach ($this->splitTopLevel($body) as $item) {
if (! preg_match("/^\s*'([^']+)'\s*=>\s*(.*)$/s", $item, $m)) {
continue;
}
$value = $m[2];
$type = null;
if (preg_match("/'type'\s*=>\s*'([^']+)'/", $value, $tm)) {
$type = $tm[1];
}
$method = null;
if (preg_match("/'method'\s*=>\s*'([^']+)'/", $value, $mm)) {
$method = $mm[1];
} elseif (preg_match("/^\s*'([^']+)'\s*$/", $value, $sm)) {
$method = $sm[1];
}
$priority = null;
if (preg_match("/'priority'\s*=>\s*(-?\d+)/", $value, $pm)) {
$priority = (int) $pm[1];
}
$hooks[] = [
'name' => $m[1],
'method' => $method,
'priority' => $priority,
'type' => $type ?? 'action',
'typeDeclared' => $type !== null,
];
}
return $hooks;
}
/**
* 지정 메서드의 `return [...]` 배열 본문을 대괄호 균형으로 잘라냅니다.
*
* 정규식 하나로 배열을 잡으려 하면 중첩 배열에서 끊기므로, 여는 대괄호부터
* 문자열·주석을 건너뛰며 깊이를 세어 대응하는 닫는 위치를 찾습니다.
*
* @param string $content 소스
* @param string $method 메서드명
* @return string|null 배열 본문 (대괄호 제외, 없으면 null)
*/
private function extractReturnArray(string $content, string $method): ?string
{
if (! preg_match('/function\s+'.preg_quote($method, '/').'\s*\(/', $content, $m, PREG_OFFSET_CAPTURE)) {
return null;
}
$from = (int) $m[0][1];
$returnPos = strpos($content, 'return [', $from);
if ($returnPos === false) {
return null;
}
$open = $returnPos + strlen('return ');
$close = $this->matchBracket($content, $open);
return $close === null ? null : substr($content, $open + 1, $close - $open - 1);
}
/**
* 여는 대괄호 위치에 대응하는 닫는 대괄호 위치를 찾습니다.
*
* @param string $s 소스
* @param int $open 여는 대괄호 인덱스
* @return int|null 닫는 대괄호 인덱스 (불균형이면 null)
*/
private function matchBracket(string $s, int $open): ?int
{
$depth = 0;
$len = strlen($s);
for ($i = $open; $i < $len; $i++) {
$ch = $s[$i];
if ($ch === "'" || $ch === '"') {
$i = $this->skipString($s, $i);
continue;
}
if ($ch === '/' && $i + 1 < $len && ($s[$i + 1] === '/' || $s[$i + 1] === '*')) {
$i = $this->skipComment($s, $i);
continue;
}
if ($ch === '[') {
$depth++;
} elseif ($ch === ']') {
$depth--;
if ($depth === 0) {
return $i;
}
}
}
return null;
}
/**
* 배열 본문을 최상위 쉼표 기준으로 분할합니다.
*
* @param string $body 배열 본문
* @return array<int, string> 항목 목록 (빈 항목 제외)
*/
private function splitTopLevel(string $body): array
{
$items = [];
$buf = '';
$depth = 0;
$len = strlen($body);
for ($i = 0; $i < $len; $i++) {
$ch = $body[$i];
if ($ch === "'" || $ch === '"') {
$end = $this->skipString($body, $i);
$buf .= substr($body, $i, $end - $i + 1);
$i = $end;
continue;
}
if ($ch === '/' && $i + 1 < $len && ($body[$i + 1] === '/' || $body[$i + 1] === '*')) {
$i = $this->skipComment($body, $i);
continue;
}
if ($ch === '[' || $ch === '(') {
$depth++;
} elseif ($ch === ']' || $ch === ')') {
$depth--;
}
if ($ch === ',' && $depth === 0) {
if (trim($buf) !== '') {
$items[] = $buf;
}
$buf = '';
continue;
}
$buf .= $ch;
}
if (trim($buf) !== '') {
$items[] = $buf;
}
return $items;
}
/**
* 문자열 리터럴의 끝 인덱스를 찾습니다 (이스케이프 인지).
*
* @param string $s 소스
* @param int $start 따옴표 인덱스
* @return int 닫는 따옴표 인덱스 (미종료 시 문자열 끝)
*/
private function skipString(string $s, int $start): int
{
$quote = $s[$start];
$len = strlen($s);
for ($i = $start + 1; $i < $len; $i++) {
if ($s[$i] === '\\') {
$i++;
continue;
}
if ($s[$i] === $quote) {
return $i;
}
}
return $len - 1;
}
/**
* 주석의 끝 인덱스를 찾습니다.
*
* @param string $s 소스
* @param int $start `/` 인덱스
* @return int 주석 마지막 문자 인덱스
*/
private function skipComment(string $s, int $start): int
{
if ($s[$start + 1] === '/') {
$end = strpos($s, "\n", $start);
return $end === false ? strlen($s) - 1 : $end;
}
$end = strpos($s, '*/', $start);
return $end === false ? strlen($s) - 1 : $end + 1;
}
/**
* 소스에서 FQCN 을 추출합니다.
*
* @param string $content 소스
* @return string|null FQCN (없으면 null)
*/
private function fqcnOf(string $content): ?string
{
if (! preg_match('/^\s*namespace\s+([^;]+);/m', $content, $nm)) {
return null;
}
if (! preg_match('/^\s*(?:final\s+|abstract\s+)?class\s+(\w+)/m', $content, $cm)) {
return null;
}
return trim($nm[1]).'\\'.$cm[1];
}
/**
* 훅 발행 스캔 대상 PHP 파일을 열거합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return \Generator<string> PHP 파일 절대 경로
*/
private function phpFiles(array $record): \Generator
{
foreach (['src', 'database', 'upgrades', 'resources', 'config'] as $sub) {
$dir = $record['path'].DIRECTORY_SEPARATOR.$sub;
if (! is_dir($dir)) {
continue;
}
foreach (File::allFiles($dir) as $file) {
if ($file->getExtension() === 'php') {
yield $file->getPathname();
}
}
}
if ($record['entryFile'] !== null) {
yield $record['entryFile'];
}
}
/**
* 확장 루트 기준 상대 경로로 변환합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param string $absolute 절대 경로
* @return string 상대 경로 (POSIX 구분자)
*/
private function relative(array $record, string $absolute): string
{
$base = rtrim((string) $record['path'], '/\\').DIRECTORY_SEPARATOR;
$rel = str_starts_with($absolute, $base) ? substr($absolute, strlen($base)) : $absolute;
return str_replace('\\', '/', $rel);
}
}
@@ -0,0 +1,241 @@
<?php
namespace App\Support\ExtensionDoc;
use Illuminate\Support\Facades\File;
/**
* 확장 테스트 경로 수집기
*
* 확장이 보유한 PHPUnit · Vitest · Playwright 테스트와 시나리오 매니페스트를 수집하고,
* 실행 명령을 규정에 맞는 형태로 조립합니다.
*
* 실행 명령은 문서의 핵심 산출물입니다 — 확장 테스트는 무필터 전체 실행이 금지되어 있고
* 프론트/백엔드가 서로 다른 셸 규약을 요구하므로, 그 형태를 문서가 직접 제시하지 않으면
* 읽는 쪽이 매번 규정을 되짚어야 합니다.
*/
class TestPathCollector
{
/**
* 확장의 테스트 표면을 수집합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @return array<string, mixed> 테스트 인벤토리
*/
public function collect(array $record): array
{
$phpunit = $this->countFiles($record, 'tests', 'php', ['Playwright']);
$vitestRoots = $this->vitestRoots($record);
$playwright = $this->countFiles($record, 'tests/Playwright', 'ts');
$scenarios = $this->scenarioManifests($record);
return [
'phpunit' => $phpunit,
'vitest' => $vitestRoots,
'playwright' => $playwright,
'scenarios' => $scenarios,
'commands' => $this->buildCommands($record, $phpunit, $vitestRoots, $playwright),
'testCaseBase' => $this->testCaseBase($record),
];
}
/**
* 확장 테스트의 기저 TestCase 클래스를 찾습니다.
*
* 모듈/플러그인 테스트는 `Tests\TestCase` 직접 상속이 금지되고 확장 전용 기저 클래스를
* 상속해야 하므로, 그 클래스명이 문서에 드러나야 합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return string|null 기저 클래스 파일명 (없으면 null)
*/
private function testCaseBase(array $record): ?string
{
foreach (['ModuleTestCase.php', 'PluginTestCase.php', 'TemplateTestCase.php'] as $name) {
if (is_file($record['path'].DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.$name)) {
return 'tests/'.$name;
}
}
return null;
}
/**
* Vitest 대상 디렉토리를 찾습니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array{config: string|null, dirs: array<int, string>, files: int}
*/
private function vitestRoots(array $record): array
{
$config = null;
foreach (['vitest.config.ts', 'vitest.config.js'] as $name) {
if (is_file($record['path'].DIRECTORY_SEPARATOR.$name)) {
$config = $name;
break;
}
}
$dirs = [];
$files = 0;
foreach (['resources/js', 'src', '__tests__'] as $sub) {
$dir = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $sub);
if (! is_dir($dir)) {
continue;
}
$found = 0;
foreach (File::allFiles($dir) as $file) {
$rel = str_replace('\\', '/', $file->getPathname());
if (! preg_match('/\.(test|spec)\.(ts|tsx)$/', $rel)) {
continue;
}
$found++;
}
if ($found > 0) {
$dirs[] = $sub;
$files += $found;
}
}
return ['config' => $config, 'dirs' => $dirs, 'files' => $files];
}
/**
* 시나리오 매니페스트를 수집합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @return array<int, string> 매니페스트 상대 경로
*/
private function scenarioManifests(array $record): array
{
$dir = $record['path'].DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'scenarios';
if (! is_dir($dir)) {
return [];
}
$files = [];
foreach (File::allFiles($dir) as $file) {
if (in_array($file->getExtension(), ['yaml', 'yml'], true)) {
$files[] = 'tests/scenarios/'.$file->getFilename();
}
}
sort($files);
return $files;
}
/**
* 테스트 실행 명령을 조립합니다.
*
* 무필터 전체 실행은 규정상 차단되므로 PHPUnit 명령에는 `--filter` 자리를 남깁니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param array{count: int, dirs: array<int, string>} $phpunit PHPUnit 집계
* @param array{config: string|null, dirs: array<int, string>, files: int} $vitest Vitest 집계
* @param array{count: int, dirs: array<int, string>} $playwright Playwright 집계
* @return array<int, array{label: string, command: string, shell: string}> 실행 명령 목록
*/
private function buildCommands(array $record, array $phpunit, array $vitest, array $playwright): array
{
$commands = [];
$rel = $record['relPath'];
if ($phpunit['count'] > 0) {
$commands[] = [
'label' => 'PHPUnit (변경 범위만)',
'command' => "php vendor/bin/phpunit {$rel}/tests --filter='<대상클래스>'",
'shell' => 'Bash',
];
}
if ($vitest['files'] > 0) {
$commands[] = [
'label' => 'Vitest (확장 디렉토리에서)',
'command' => "cd {$rel} && powershell -Command \"npm run test:run -- <대상>\"",
'shell' => 'PowerShell',
];
}
if ($playwright['count'] > 0) {
$commands[] = [
'label' => 'Playwright E2E',
'command' => "npx playwright test {$rel}/tests/Playwright/specs/<대상>.spec.ts",
'shell' => 'Bash',
];
}
return $commands;
}
/**
* 그 확장자에서 "테스트 파일" 로 셀 파일명인지 판정합니다.
*
* 계수 모집단은 문서의 "테스트 N건" 과 AGENTS `## 7. 테스트 실행` 표에 그대로 실리므로,
* 설정 파일·픽스처를 함께 세면 공개 문서가 틀린 수치를 싣는다.
*
* @param string $extension 파일 확장자
* @param string $filename 파일명
* @return bool 테스트 파일이면 true
*/
private static function isTestFilename(string $extension, string $filename): bool
{
return match ($extension) {
'php' => (bool) preg_match('/Test\.php$/', $filename),
'ts', 'tsx' => (bool) preg_match('/\.(test|spec)\.tsx?$/', $filename),
default => true,
};
}
/**
* 하위 디렉토리의 파일 수와 1단계 하위 디렉토리를 집계합니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param string $sub 확장 루트 기준 하위 경로
* @param string $extension 대상 확장자
* @param array<int, string> $excludeDirs 제외할 1단계 하위 디렉토리명
* @return array{count: int, dirs: array<int, string>, root: string|null}
*/
private function countFiles(array $record, string $sub, string $extension, array $excludeDirs = []): array
{
$dir = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $sub);
if (! is_dir($dir)) {
return ['count' => 0, 'dirs' => [], 'root' => null];
}
$count = 0;
$dirs = [];
foreach (File::allFiles($dir) as $file) {
if ($file->getExtension() !== $extension) {
continue;
}
// 테스트 파일이 아닌 것이 같은 디렉토리에 산다 — 세면 "테스트 N건" 이 실제
// 테스트 수보다 커진다. PHP 는 기저 TestCase·헬퍼(board 실측: 157 중 2건),
// Playwright 는 `playwright.config.ts` 와 픽스처(gdpr 실측: 5 중 3건)다.
// 두 축이 같은 규율을 갖도록 확장자별 파일명 규칙을 한자리에서 적용한다.
if (! self::isTestFilename($extension, $file->getFilename())) {
continue;
}
$relative = str_replace('\\', '/', $file->getRelativePath());
$first = $relative === '' ? '(root)' : explode('/', $relative)[0];
if (in_array($first, $excludeDirs, true)) {
continue;
}
$count++;
if (! in_array($first, $dirs, true)) {
$dirs[] = $first;
}
}
sort($dirs);
return ['count' => $count, 'dirs' => $dirs, 'root' => $sub];
}
}