feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)

공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다.

브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도
남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데
자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기
하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발
대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다.
런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다.

자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그
실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML
에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다.
편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다.

두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의
custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에
의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다.
확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을
고치면 그 변경을 감지해 재게시까지 예약된다.

FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접
넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로
나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린
스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과
분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠
화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를
함께 뒀다.

동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에
써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
This commit is contained in:
HeuJung committed 2026-08-27 16:47:14 +09:00
1 parent 72f2e94c1a
commit 3945b6f1b3
1042 files changed
+107435 -947

No files matched your search

@@ -0,0 +1,54 @@
<?php
namespace App\Extension\Helpers;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
/**
* 실패한 설치가 남긴 활성 디렉토리를 되돌리는 헬퍼
*
* 설치 흐름은 원본(`_pending`/`_bundled`)을 활성 디렉토리로 **먼저 복사한 뒤** 확장을
* 로드해 코어 버전·의존성·언어 경로 등을 검증한다. 검증에 로드된 확장 인스턴스가 필요해
* 순서를 뒤집을 수 없는데, 그 검증이 실패하면 방금 만든 활성 디렉토리가 그대로 남는다.
*
* 남은 디렉토리는 DB 행이 없어 목록에도 뜨지 않고 번들 병합에도 참여하지 않는다 — 즉
* 오류도 경고도 없이 디스크만 점유하는 고아가 된다. 더 나쁜 것은 다음 설치 시도가 그
* 디렉토리를 "이미 있는 설치본" 으로 보고 원본 복사를 건너뛸 수 있다는 점이다.
*
* 이 헬퍼는 **이번 호출이 만든 디렉토리만** 지운다. 이미 설치돼 있던 확장을 `--force` 로
* 다시 설치하다 실패한 경우에는 운영자의 기존 설치본이므로 손대지 않는다.
*/
final class ExtensionInstallRollbackHelper
{
/**
* 이번 설치가 만든 활성 디렉토리를 제거합니다.
*
* @param string $activePath 활성 디렉토리 절대경로
* @param bool $existedBefore 이번 설치 이전에 그 디렉토리가 있었는지
* @param string $identifier 확장 식별자 (로그용)
* @param string $type 확장 유형 (module|plugin|template, 로그용)
* @return bool 실제로 제거했으면 true
*/
public static function removeIfCreatedByThisInstall(
string $activePath,
bool $existedBefore,
string $identifier,
string $type,
): bool {
if ($existedBefore || ! File::isDirectory($activePath)) {
return false;
}
$removed = File::deleteDirectory($activePath);
Log::warning('설치 실패로 활성 디렉토리를 되돌렸습니다.', [
'type' => $type,
'identifier' => $identifier,
'path' => $activePath,
'removed' => $removed,
]);
return $removed;
}
}
@@ -21,6 +21,21 @@ class ExtensionPendingHelper
'node_modules',
];
/**
* 확장 교체 시 보존할 최상위 디렉토리명 목록
*
* `custom/` 은 운영자가 자기 CSS·JS·정적 파일을 두는 자리다. 확장이 소유한 것이
* 아니므로 새 배포본으로 덮어써서는 안 된다 — 덮어쓰면 업데이트할 때마다 운영자가
* 넣은 파일이 사라지고, 그 사실이 어디에도 남지 않는다(파일이 조용히 없어질 뿐이다).
*
* 보존은 **교체 경로 둘 다**에서 성립해야 한다: 디렉토리 rename 경로와, 하위 트리에
* 열린 핸들이 있을 때의 제자리 동기화 폴백. 한쪽만 고치면 Windows 잠금 상황에서만
* 조용히 사라진다.
*/
public const PRESERVED_DIRECTORIES = [
'custom',
];
/**
* _pending 또는 _bundled 디렉토리에서 확장 메타데이터를 로드합니다.
*
@@ -162,6 +177,9 @@ class ExtensionPendingHelper
try {
self::copyDirectoryWithProgress($sourcePath, $tempPath, $sourcePath, $onProgress);
// 운영자 소유 디렉토리를 새 트리로 옮겨 심는다 (교체 전에 해 둬야 원본이 살아 있다)
self::carryOverPreservedDirectories($targetPath, $tempPath, $onProgress);
} catch (\Exception $e) {
// 복사 실패 시 임시 디렉토리 정리 후 예외 전파
if (File::isDirectory($tempPath)) {
@@ -379,7 +397,7 @@ class ExtensionPendingHelper
}
$staleFailures = [];
self::removeStaleEntries($source, $dest, $staleFailures);
self::removeStaleEntries($source, $dest, $staleFailures, true);
if (! empty($staleFailures)) {
Log::warning('확장 제자리 교체: 일부 잔존 파일을 삭제하지 못했습니다 (다음 교체 시 재시도)', [
@@ -389,6 +407,40 @@ class ExtensionPendingHelper
}
}
/**
* 운영자 소유 디렉토리를 기존 활성 디렉토리에서 새 트리로 옮겨 심습니다.
*
* 새 배포본에 같은 이름의 디렉토리가 있으면 **그것을 치우고** 기존 것을 심는다 —
* `custom/` 은 확장이 소유하지 않는 자리이므로, 확장이 그 자리에 무언가를 담아
* 배포했더라도 운영자 파일이 우선한다(그런 배포 자체를 정적 검사가 막는다).
*
* @param string $existingPath 기존 활성 디렉토리
* @param string $stagingPath 새 배포본이 복사된 임시 디렉토리
* @param \Closure|null $onProgress 진행 콜백
*/
private static function carryOverPreservedDirectories(
string $existingPath,
string $stagingPath,
?\Closure $onProgress = null
): void {
foreach (self::PRESERVED_DIRECTORIES as $name) {
$from = $existingPath.DIRECTORY_SEPARATOR.$name;
if (! File::isDirectory($from)) {
continue;
}
$to = $stagingPath.DIRECTORY_SEPARATOR.$name;
if (File::isDirectory($to)) {
File::deleteDirectory($to);
}
$onProgress?->__invoke(null, "운영자 파일 보존: {$name}/");
self::copyDirectoryWithProgress($from, $to, $from, $onProgress);
}
}
/**
* 소스 디렉토리의 파일을 대상 디렉토리에 재귀적으로 덮어씁니다.
*
@@ -550,7 +602,7 @@ class ExtensionPendingHelper
* @param string $dest 활성 디렉토리
* @param array $failures 삭제 실패 경로 수집 (참조)
*/
private static function removeStaleEntries(string $source, string $dest, array &$failures): void
private static function removeStaleEntries(string $source, string $dest, array &$failures, bool $isRoot = false): void
{
if (! is_dir($dest)) {
return;
@@ -559,6 +611,11 @@ class ExtensionPendingHelper
$items = new \FilesystemIterator($dest, \FilesystemIterator::SKIP_DOTS);
foreach ($items as $item) {
// 운영자 소유 디렉토리는 소스에 없어도 정리 대상이 아니다 (확장 루트에서만 판정)
if ($isRoot && $item->isDir() && in_array($item->getBasename(), self::PRESERVED_DIRECTORIES, true)) {
continue;
}
$counterpart = $source.DIRECTORY_SEPARATOR.$item->getBasename();
if ($item->isDir()) {
@@ -627,14 +684,85 @@ class ExtensionPendingHelper
*
* @param string $basePath 확장 타입의 기본 경로
* @param string $identifier 확장 식별자
* @return array<int, array{directory: string, archive: string}> 보관된 운영자 디렉토리 목록
*/
public static function deleteExtensionDirectory(string $basePath, string $identifier): void
public static function deleteExtensionDirectory(string $basePath, string $identifier): array
{
$targetPath = $basePath.DIRECTORY_SEPARATOR.$identifier;
if (File::isDirectory($targetPath)) {
File::deleteDirectory($targetPath);
if (! File::isDirectory($targetPath)) {
return [];
}
$archived = self::archivePreservedDirectories($targetPath, $identifier);
File::deleteDirectory($targetPath);
return $archived;
}
/**
* 삭제 전에 운영자 소유 디렉토리를 보관합니다.
*
* 확장을 삭제하면 그 안의 `custom/` 도 함께 사라진다 — 운영자가 넣은 파일이므로
* 되돌릴 방법 없이 없어지면 안 된다. 교체(업데이트)는 보존이 답이지만 삭제는
* "확장을 없앤다" 는 명시적 의사이므로 막지 않고, 대신 사본을 남기고 그 사실을
* 기록한다.
*
* 보관 실패가 삭제를 막지는 않는다 — 삭제는 운영자가 요청한 동작이다.
*
* @param string $targetPath 삭제 대상 확장 디렉토리
* @param string $identifier 확장 식별자
* @return array<int, array{directory: string, archive: string}> 보관에 성공한 디렉토리 목록
*/
private static function archivePreservedDirectories(string $targetPath, string $identifier): array
{
$archived = [];
foreach (self::PRESERVED_DIRECTORIES as $name) {
$source = $targetPath.DIRECTORY_SEPARATOR.$name;
if (! File::isDirectory($source) || self::isEmptyDirectory($source)) {
continue;
}
$archivePath = storage_path(
'app'.DIRECTORY_SEPARATOR.'extension-custom-backups'
.DIRECTORY_SEPARATOR.$identifier.'-'.date('Ymd_His')
.DIRECTORY_SEPARATOR.$name
);
try {
self::copyDirectoryWithProgress($source, $archivePath, $source, null);
Log::info('확장 삭제: 운영자 파일을 보관했습니다', [
'identifier' => $identifier,
'directory' => $name,
'archive' => $archivePath,
]);
$archived[] = ['directory' => $name, 'archive' => $archivePath];
} catch (\Throwable $e) {
Log::warning('확장 삭제: 운영자 파일 보관에 실패했습니다 (삭제는 계속합니다)', [
'identifier' => $identifier,
'directory' => $name,
'error' => $e->getMessage(),
]);
}
}
return $archived;
}
/**
* 디렉토리가 비어 있는지 판정합니다.
*
* @param string $path 대상 디렉토리
* @return bool 비어 있으면 true
*/
private static function isEmptyDirectory(string $path): bool
{
return ! (new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS))->valid();
}
/**
+171 -144
View File
@@ -21,6 +21,7 @@ use App\Enums\PermissionType;
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
use App\Extension\Helpers\DependencyEnricher;
use App\Extension\Helpers\ExtensionBackupHelper;
use App\Extension\Helpers\ExtensionInstallRollbackHelper;
use App\Extension\Helpers\ExtensionMenuSyncHelper;
use App\Extension\Helpers\ExtensionPendingHelper;
use App\Extension\Helpers\ExtensionRoleSyncHelper;
@@ -372,168 +373,186 @@ class ModuleManager implements ModuleManagerInterface
// _pending 또는 _bundled에서 활성 디렉토리로 복사 (미설치 모듈 설치 시)
// force=true 시 활성 디렉토리가 있어도 원본으로 덮어씀 (불완전 설치 복구)
$rollbackActivePath = $this->modulesPath.DIRECTORY_SEPARATOR.$moduleName;
// 검증은 로드된 확장 인스턴스를 요구해 복사보다 뒤에 온다. 그래서 검증이 실패하면
// 방금 만든 활성 디렉토리가 고아로 남는다 — DB 행이 없어 목록에도 뜨지 않고 오류도
// 남지 않은 채 디스크만 점유한다. 이번 호출이 만든 것이면 되돌린다.
$rollbackDirExisted = File::isDirectory($rollbackActivePath);
$onProgress?->__invoke('copy', '파일 복사 중...');
$this->copyFromPendingOrBundled($moduleName, $onProgress, $force);
// 모듈이 활성 디렉토리에 있지 않으면 로드 시도
$module = $this->getModule($moduleName);
if (! $module) {
// 복사 후 재로드 시도
$this->reloadModule($moduleName);
$module = $this->getModule($moduleName);
}
if (! $module) {
throw new \Exception(__('modules.not_found', ['module' => $moduleName]));
}
// 그누보드7 코어 버전 호환성 검증
CoreVersionChecker::validateExtension(
$module->getRequiredCoreVersion(),
$module->getIdentifier(),
'module'
);
// 의존성 확인 (트랜잭션 외부에서 먼저 검증)
$onProgress?->__invoke('validate', '검증 중...');
$this->checkDependencies($module);
// 권한 구조 검증 (계층형 구조 필수)
$this->validatePermissionStructure($module, 'module');
// 언어 파일 경로 검증 (src/lang 경로 필수)
$this->validateTranslationPath($module, 'module');
// SEO 변수명 중복 검증
$this->validateSeoVariables($module, 'module');
// 모듈 설치 실행
$module->clearLifecycleFailureReason();
$result = $module->install();
if (! $result) {
$failureReason = $module->getLifecycleFailureReason() ?? __('modules.errors.unknown_error');
return false;
}
// Phase 1: 마이그레이션 실행 (DDL - 트랜잭션 외부)
// MySQL에서 CREATE TABLE 등 DDL 문은 암시적 커밋을 유발하므로 트랜잭션 외부에서 실행
$onProgress?->__invoke('migration', '마이그레이션 실행 중...');
$this->runMigrations($module);
// Phase 2: 데이터 작업 (DML - 트랜잭션 내부)
$onProgress?->__invoke('db', 'DB 등록 중...');
try {
DB::beginTransaction();
// 모듈이 활성 디렉토리에 있지 않으면 로드 시도
$module = $this->getModule($moduleName);
if (! $module) {
// 복사 후 재로드 시도
$this->reloadModule($moduleName);
$module = $this->getModule($moduleName);
}
// GitHub에서 최신 버전 정보 가져오기
$latestVersion = $this->fetchLatestVersion($module);
$updateAvailable = $latestVersion ? version_compare($latestVersion, $module->getVersion(), '>') : false;
if (! $module) {
throw new \Exception(__('modules.not_found', ['module' => $moduleName]));
}
// 다국어 name, description 처리 (역호환성 지원)
$name = $this->convertToMultilingual($module->getName());
$description = $this->convertToMultilingual($module->getDescription());
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
$manifest = HookManager::applyFilters(
"module.{$module->getIdentifier()}.manifest.translations",
['name' => $name, 'description' => $description]
);
$name = $manifest['name'] ?? $name;
$description = $manifest['description'] ?? $description;
// 데이터베이스에 모듈 정보 저장
$this->moduleRepository->updateOrCreate(
['identifier' => $module->getIdentifier()],
[
'vendor' => $module->getVendor(),
'name' => $name,
'version' => $module->getVersion(),
'latest_version' => $latestVersion,
'description' => $description,
'github_url' => $module->getGithubUrl(),
'github_changelog_url' => $this->buildChangelogUrl($module->getGithubUrl()),
'update_available' => $updateAvailable,
'metadata' => $module->getMetadata(),
'status' => ExtensionStatus::Inactive->value,
'vendor_mode' => $resolvedVendorMode->value,
'config' => $module->getConfig(),
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
'created_at' => now(),
'updated_at' => now(),
]
// 그누보드7 코어 버전 호환성 검증
CoreVersionChecker::validateExtension(
$module->getRequiredCoreVersion(),
$module->getIdentifier(),
'module'
);
// Role 자동 생성
$this->createModuleRoles($module);
// 의존성 확인 (트랜잭션 외부에서 먼저 검증)
$onProgress?->__invoke('validate', '검증 중...');
$this->checkDependencies($module);
// 권한 자동 생성
$this->createModulePermissions($module);
// 권한 구조 검증 (계층형 구조 필수)
$this->validatePermissionStructure($module, 'module');
// 권한-Role 연결
$this->assignPermissionsToRoles($module);
// 언어 파일 경로 검증 (src/lang 경로 필수)
$this->validateTranslationPath($module, 'module');
// 관리자 메뉴 자동 생성
$this->createModuleMenus($module);
// SEO 변수명 중복 검증
$this->validateSeoVariables($module, 'module');
// IDV 정책 자동 동기화 (identity_policies 테이블)
$this->syncModuleIdentityPolicies($module);
// 모듈 설치 실행
$module->clearLifecycleFailureReason();
$result = $module->install();
// IDV 메시지 정의/템플릿 자동 동기화 (identity_message_definitions / identity_message_templates)
$this->syncModuleIdentityMessages($module);
if (! $result) {
$failureReason = $module->getLifecycleFailureReason() ?? __('modules.errors.unknown_error');
// 알림 정의/템플릿 자동 동기화 (notification_definitions / notification_templates)
$this->syncModuleNotificationDefinitions($module);
return false;
}
DB::commit();
// Phase 1: 마이그레이션 실행 (DDL - 트랜잭션 외부)
// MySQL에서 CREATE TABLE 등 DDL 문은 암시적 커밋을 유발하므로 트랜잭션 외부에서 실행
$onProgress?->__invoke('migration', '마이그레이션 실행 중...');
$this->runMigrations($module);
// Phase 2: 데이터 작업 (DML - 트랜잭션 내부)
$onProgress?->__invoke('db', 'DB 등록 중...');
try {
DB::beginTransaction();
// GitHub에서 최신 버전 정보 가져오기
$latestVersion = $this->fetchLatestVersion($module);
$updateAvailable = $latestVersion ? version_compare($latestVersion, $module->getVersion(), '>') : false;
// 다국어 name, description 처리 (역호환성 지원)
$name = $this->convertToMultilingual($module->getName());
$description = $this->convertToMultilingual($module->getDescription());
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
$manifest = HookManager::applyFilters(
"module.{$module->getIdentifier()}.manifest.translations",
['name' => $name, 'description' => $description]
);
$name = $manifest['name'] ?? $name;
$description = $manifest['description'] ?? $description;
// 데이터베이스에 모듈 정보 저장
$this->moduleRepository->updateOrCreate(
['identifier' => $module->getIdentifier()],
[
'vendor' => $module->getVendor(),
'name' => $name,
'version' => $module->getVersion(),
'latest_version' => $latestVersion,
'description' => $description,
'github_url' => $module->getGithubUrl(),
'github_changelog_url' => $this->buildChangelogUrl($module->getGithubUrl()),
'update_available' => $updateAvailable,
'metadata' => $module->getMetadata(),
'status' => ExtensionStatus::Inactive->value,
'vendor_mode' => $resolvedVendorMode->value,
'config' => $module->getConfig(),
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
'created_at' => now(),
'updated_at' => now(),
]
);
// Role 자동 생성
$this->createModuleRoles($module);
// 권한 자동 생성
$this->createModulePermissions($module);
// 권한-Role 연결
$this->assignPermissionsToRoles($module);
// 관리자 메뉴 자동 생성
$this->createModuleMenus($module);
// IDV 정책 자동 동기화 (identity_policies 테이블)
$this->syncModuleIdentityPolicies($module);
// IDV 메시지 정의/템플릿 자동 동기화 (identity_message_definitions / identity_message_templates)
$this->syncModuleIdentityMessages($module);
// 알림 정의/템플릿 자동 동기화 (notification_definitions / notification_templates)
$this->syncModuleNotificationDefinitions($module);
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
// Phase 3: 시더 실행 (트랜잭션 외부)
// 시더 내부에서 별도 트랜잭션을 사용할 수 있으므로 외부에서 실행
$onProgress?->__invoke('seed', '시더 실행 중...');
$this->runModuleSeeders($module);
// Phase 4: 기본 설정 파일 생성
$onProgress?->__invoke('settings', '환경설정 초기화 중...');
$this->initializeModuleSettings($module);
// Phase 4.5: Composer 의존성 설치 (외부 패키지가 있는 경우에만)
// _pending에서 이미 설치한 경우 스킵 (vendor/가 활성 디렉토리에 복사됨)
if (! $composerDoneInPending) {
$onProgress?->__invoke('composer', 'Composer 의존성 설치 중...');
if (! app()->environment('testing')
&& $this->extensionManager->hasComposerDependencies('modules', $moduleName)) {
$composerResult = $this->extensionManager->runComposerInstall('modules', $moduleName);
if (! $composerResult) {
Log::warning('모듈 Composer 의존성 설치 실패', ['module' => $moduleName]);
}
}
}
// Phase 5: 오토로드 병합 실행 (트랜잭션 외부)
$onProgress?->__invoke('autoload', '오토로드 갱신 중...');
$this->extensionManager->updateComposerAutoload();
// 모듈 상태 캐시 무효화
self::invalidateModuleStatusCache();
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
$this->incrementExtensionCacheVersion();
RouteCacheHelper::rebuild();
// 확장 미들웨어 인덱스 무효화 — 새 모듈의 미들웨어 선언이 즉시 게이트에 반영.
ExtensionMiddlewareRegistry::flush();
// 훅 발행: 모듈 설치 완료
HookManager::doAction('core.modules.installed', $moduleName);
return true;
} catch (\Throwable $e) {
ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall(
$rollbackActivePath,
$rollbackDirExisted,
$moduleName,
'module',
);
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
// Phase 3: 시더 실행 (트랜잭션 외부)
// 시더 내부에서 별도 트랜잭션을 사용할 수 있으므로 외부에서 실행
$onProgress?->__invoke('seed', '시더 실행 중...');
$this->runModuleSeeders($module);
// Phase 4: 기본 설정 파일 생성
$onProgress?->__invoke('settings', '환경설정 초기화 중...');
$this->initializeModuleSettings($module);
// Phase 4.5: Composer 의존성 설치 (외부 패키지가 있는 경우에만)
// _pending에서 이미 설치한 경우 스킵 (vendor/가 활성 디렉토리에 복사됨)
if (! $composerDoneInPending) {
$onProgress?->__invoke('composer', 'Composer 의존성 설치 중...');
if (! app()->environment('testing')
&& $this->extensionManager->hasComposerDependencies('modules', $moduleName)) {
$composerResult = $this->extensionManager->runComposerInstall('modules', $moduleName);
if (! $composerResult) {
Log::warning('모듈 Composer 의존성 설치 실패', ['module' => $moduleName]);
}
}
}
// Phase 5: 오토로드 병합 실행 (트랜잭션 외부)
$onProgress?->__invoke('autoload', '오토로드 갱신 중...');
$this->extensionManager->updateComposerAutoload();
// 모듈 상태 캐시 무효화
self::invalidateModuleStatusCache();
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
$this->incrementExtensionCacheVersion();
RouteCacheHelper::rebuild();
// 확장 미들웨어 인덱스 무효화 — 새 모듈의 미들웨어 선언이 즉시 게이트에 반영.
ExtensionMiddlewareRegistry::flush();
// 훅 발행: 모듈 설치 완료
HookManager::doAction('core.modules.installed', $moduleName);
return true;
}
/**
@@ -905,6 +924,9 @@ class ModuleManager implements ModuleManagerInterface
* @param bool $deleteData 모듈 데이터(테이블) 삭제 여부
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
* @param string|null $failureReason 실패 시 사유가 담기는 out 파라미터 (성공 시 null)
* @param array<int, array{directory: string, archive: string}>|null $preservedBackups
* 삭제 전에 보관한 운영자 소유 디렉토리(`custom/`)의 사본 경로가 담기는 out 파라미터.
* 운영자에게 "지웠지만 사본은 여기 있다" 를 알리기 위한 것이므로 호출부가 노출해야 한다.
* @return bool 제거 성공 여부
*
* @throws \Exception 모듈을 찾을 수 없을 때
@@ -914,8 +936,10 @@ class ModuleManager implements ModuleManagerInterface
bool $deleteData = false,
?\Closure $onProgress = null,
?string &$failureReason = null,
?array &$preservedBackups = null,
): bool {
$failureReason = null;
$preservedBackups = [];
// 상태 가드: 진행 중 상태 체크
$existingRecord = $this->moduleRepository->findByIdentifier($moduleName);
@@ -1045,7 +1069,10 @@ class ModuleManager implements ModuleManagerInterface
// 활성 모듈 디렉토리 전체 삭제 (_pending/_bundled에 원본 보존되므로 재설치 가능)
$onProgress?->__invoke('files', '파일 삭제 중...');
ExtensionPendingHelper::deleteExtensionDirectory($this->modulesPath, $module->getIdentifier());
$preservedBackups = ExtensionPendingHelper::deleteExtensionDirectory(
$this->modulesPath,
$module->getIdentifier()
);
// 메모리에서 모듈 제거
unset($this->modules[$module->getIdentifier()]);
+169 -143
View File
@@ -21,6 +21,7 @@ use App\Exceptions\LayoutIncludeException;
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
use App\Extension\Helpers\DependencyEnricher;
use App\Extension\Helpers\ExtensionBackupHelper;
use App\Extension\Helpers\ExtensionInstallRollbackHelper;
use App\Extension\Helpers\ExtensionMenuSyncHelper;
use App\Extension\Helpers\ExtensionPendingHelper;
use App\Extension\Helpers\ExtensionRoleSyncHelper;
@@ -357,167 +358,184 @@ class PluginManager implements PluginManagerInterface
// _pending 또는 _bundled에서 활성 디렉토리로 복사 (미설치 플러그인 설치 시)
// force=true 시 활성 디렉토리가 있어도 원본으로 덮어씀 (불완전 설치 복구)
// 검증은 로드된 확장 인스턴스를 요구해 복사보다 뒤에 온다. 그래서 검증이 실패하면
// 방금 만든 활성 디렉토리가 고아로 남는다 — DB 행이 없어 목록에도 뜨지 않고 오류도
// 남지 않은 채 디스크만 점유한다. 이번 호출이 만든 것이면 되돌린다.
$rollbackDirExisted = File::isDirectory($activePath);
$onProgress?->__invoke('copy', '파일 복사 중...');
$this->copyFromPendingOrBundled($pluginName, $onProgress, $force);
// 플러그인이 활성 디렉토리에 있지 않으면 로드 시도
$plugin = $this->getPlugin($pluginName);
if (! $plugin) {
// 복사 후 재로드 시도
$this->reloadPlugin($pluginName);
$plugin = $this->getPlugin($pluginName);
}
if (! $plugin) {
throw new \Exception(__('plugins.not_found', ['plugin' => $pluginName]));
}
// 그누보드7 코어 버전 호환성 검증
CoreVersionChecker::validateExtension(
$plugin->getRequiredCoreVersion(),
$plugin->getIdentifier(),
'plugin'
);
// 의존성 확인 (트랜잭션 외부에서 먼저 검증)
$this->checkDependencies($plugin);
// 언어 파일 경로 검증 (lang 경로 필수)
$this->validateTranslationPath($plugin, 'plugin');
// SEO 변수명 중복 검증
$this->validateSeoVariables($plugin, 'plugin');
// 플러그인 설치 실행
$onProgress?->__invoke('validate', '검증 중...');
$plugin->clearLifecycleFailureReason();
$result = $plugin->install();
if (! $result) {
$failureReason = $plugin->getLifecycleFailureReason() ?? __('plugins.errors.unknown_error');
}
if (! $result) {
return false;
}
// Phase 1: 마이그레이션 실행 (DDL - 트랜잭션 외부)
// MySQL에서 CREATE TABLE 등 DDL 문은 암시적 커밋을 유발하므로 트랜잭션 외부에서 실행
$onProgress?->__invoke('migration', '마이그레이션 실행 중...');
$this->runMigrations($plugin);
// Phase 2: 데이터 작업 (DML - 트랜잭션 내부)
$onProgress?->__invoke('db', 'DB 등록 중...');
try {
DB::beginTransaction();
// 플러그인이 활성 디렉토리에 있지 않으면 로드 시도
$plugin = $this->getPlugin($pluginName);
if (! $plugin) {
// 복사 후 재로드 시도
$this->reloadPlugin($pluginName);
$plugin = $this->getPlugin($pluginName);
}
// GitHub에서 최신 버전 정보 가져오기
$latestVersion = $this->fetchLatestVersion($plugin);
$updateAvailable = $latestVersion ? version_compare($latestVersion, $plugin->getVersion(), '>') : false;
if (! $plugin) {
throw new \Exception(__('plugins.not_found', ['plugin' => $pluginName]));
}
// 다국어 name, description 처리 (역호환성 지원)
$name = $this->convertToMultilingual($plugin->getName());
$description = $this->convertToMultilingual($plugin->getDescription());
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
$manifest = HookManager::applyFilters(
"plugin.{$plugin->getIdentifier()}.manifest.translations",
['name' => $name, 'description' => $description]
);
$name = $manifest['name'] ?? $name;
$description = $manifest['description'] ?? $description;
// 데이터베이스에 플러그인 정보 저장
$this->pluginRepository->updateOrCreate(
['identifier' => $plugin->getIdentifier()],
[
'vendor' => $plugin->getVendor(),
'name' => $name,
'version' => $plugin->getVersion(),
'latest_version' => $latestVersion,
'description' => $description,
'github_url' => $plugin->getGithubUrl(),
'github_changelog_url' => $this->buildChangelogUrl($plugin->getGithubUrl()),
'update_available' => $updateAvailable,
'metadata' => $plugin->getMetadata(),
'status' => ExtensionStatus::Inactive->value,
'vendor_mode' => $resolvedVendorMode->value,
'hooks' => $this->normalizeHooksToArray($plugin->getHooks()),
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
'created_at' => now(),
'updated_at' => now(),
]
// 그누보드7 코어 버전 호환성 검증
CoreVersionChecker::validateExtension(
$plugin->getRequiredCoreVersion(),
$plugin->getIdentifier(),
'plugin'
);
// Role 자동 생성
$this->createPluginRoles($plugin);
// 의존성 확인 (트랜잭션 외부에서 먼저 검증)
$this->checkDependencies($plugin);
// 권한 자동 생성
$this->createPluginPermissions($plugin);
// 언어 파일 경로 검증 (lang 경로 필수)
$this->validateTranslationPath($plugin, 'plugin');
// 권한-Role 연결
$this->assignPermissionsToRoles($plugin);
// SEO 변수명 중복 검증
$this->validateSeoVariables($plugin, 'plugin');
// 관리자 메뉴 자동 생성 (모듈 installModule 과 동일 순서)
$this->createPluginMenus($plugin);
// 플러그인 설치 실행
$onProgress?->__invoke('validate', '검증 중...');
$plugin->clearLifecycleFailureReason();
$result = $plugin->install();
// IDV 정책 자동 동기화 (identity_policies 테이블)
$this->syncPluginIdentityPolicies($plugin);
if (! $result) {
$failureReason = $plugin->getLifecycleFailureReason() ?? __('plugins.errors.unknown_error');
}
// IDV 메시지 정의/템플릿 자동 동기화
$this->syncPluginIdentityMessages($plugin);
if (! $result) {
return false;
}
// 알림 정의/템플릿 자동 동기화 (notification_definitions / notification_templates)
$this->syncPluginNotificationDefinitions($plugin);
// Phase 1: 마이그레이션 실행 (DDL - 트랜잭션 외부)
// MySQL에서 CREATE TABLE 등 DDL 문은 암시적 커밋을 유발하므로 트랜잭션 외부에서 실행
$onProgress?->__invoke('migration', '마이그레이션 실행 중...');
$this->runMigrations($plugin);
DB::commit();
// Phase 2: 데이터 작업 (DML - 트랜잭션 내부)
$onProgress?->__invoke('db', 'DB 등록 중...');
try {
DB::beginTransaction();
// GitHub에서 최신 버전 정보 가져오기
$latestVersion = $this->fetchLatestVersion($plugin);
$updateAvailable = $latestVersion ? version_compare($latestVersion, $plugin->getVersion(), '>') : false;
// 다국어 name, description 처리 (역호환성 지원)
$name = $this->convertToMultilingual($plugin->getName());
$description = $this->convertToMultilingual($plugin->getDescription());
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
$manifest = HookManager::applyFilters(
"plugin.{$plugin->getIdentifier()}.manifest.translations",
['name' => $name, 'description' => $description]
);
$name = $manifest['name'] ?? $name;
$description = $manifest['description'] ?? $description;
// 데이터베이스에 플러그인 정보 저장
$this->pluginRepository->updateOrCreate(
['identifier' => $plugin->getIdentifier()],
[
'vendor' => $plugin->getVendor(),
'name' => $name,
'version' => $plugin->getVersion(),
'latest_version' => $latestVersion,
'description' => $description,
'github_url' => $plugin->getGithubUrl(),
'github_changelog_url' => $this->buildChangelogUrl($plugin->getGithubUrl()),
'update_available' => $updateAvailable,
'metadata' => $plugin->getMetadata(),
'status' => ExtensionStatus::Inactive->value,
'vendor_mode' => $resolvedVendorMode->value,
'hooks' => $this->normalizeHooksToArray($plugin->getHooks()),
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
'created_at' => now(),
'updated_at' => now(),
]
);
// Role 자동 생성
$this->createPluginRoles($plugin);
// 권한 자동 생성
$this->createPluginPermissions($plugin);
// 권한-Role 연결
$this->assignPermissionsToRoles($plugin);
// 관리자 메뉴 자동 생성 (모듈 installModule 과 동일 순서)
$this->createPluginMenus($plugin);
// IDV 정책 자동 동기화 (identity_policies 테이블)
$this->syncPluginIdentityPolicies($plugin);
// IDV 메시지 정의/템플릿 자동 동기화
$this->syncPluginIdentityMessages($plugin);
// 알림 정의/템플릿 자동 동기화 (notification_definitions / notification_templates)
$this->syncPluginNotificationDefinitions($plugin);
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
// Phase 3: 시더 실행 (트랜잭션 외부)
// 시더 내부에서 별도 트랜잭션을 사용할 수 있으므로 외부에서 실행
$onProgress?->__invoke('seed', '시더 실행 중...');
$this->runPluginSeeders($plugin);
// Phase 4: 기본 설정 파일 생성
$onProgress?->__invoke('settings', '설정 초기화 중...');
$this->initializePluginSettings($plugin);
// Phase 4.5: Composer 의존성 설치 (외부 패키지가 있는 경우에만)
// _pending에서 이미 설치한 경우 스킵 (vendor/가 활성 디렉토리에 복사됨)
if (! $composerDoneInPending) {
$onProgress?->__invoke('composer', 'Composer 의존성 설치 중...');
if (! app()->environment('testing')
&& $this->extensionManager->hasComposerDependencies('plugins', $pluginName)) {
$composerResult = $this->extensionManager->runComposerInstall('plugins', $pluginName);
if (! $composerResult) {
Log::warning('플러그인 Composer 의존성 설치 실패', ['plugin' => $pluginName]);
}
}
}
// Phase 5: 오토로드 병합 실행 (트랜잭션 외부)
$onProgress?->__invoke('autoload', '오토로드 갱신 중...');
$this->extensionManager->updateComposerAutoload();
// Phase 6: 플러그인 상태 캐시 무효화
self::invalidatePluginStatusCache();
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
$this->incrementExtensionCacheVersion();
RouteCacheHelper::rebuild();
// 확장 미들웨어 인덱스 무효화 — 새 플러그인의 미들웨어 선언이 즉시 게이트에 반영.
ExtensionMiddlewareRegistry::flush();
// 훅 발행: 플러그인 설치 완료
HookManager::doAction('core.plugins.installed', $pluginName);
return true;
} catch (\Throwable $e) {
ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall(
$activePath,
$rollbackDirExisted,
$pluginName,
'plugin',
);
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
// Phase 3: 시더 실행 (트랜잭션 외부)
// 시더 내부에서 별도 트랜잭션을 사용할 수 있으므로 외부에서 실행
$onProgress?->__invoke('seed', '시더 실행 중...');
$this->runPluginSeeders($plugin);
// Phase 4: 기본 설정 파일 생성
$onProgress?->__invoke('settings', '설정 초기화 중...');
$this->initializePluginSettings($plugin);
// Phase 4.5: Composer 의존성 설치 (외부 패키지가 있는 경우에만)
// _pending에서 이미 설치한 경우 스킵 (vendor/가 활성 디렉토리에 복사됨)
if (! $composerDoneInPending) {
$onProgress?->__invoke('composer', 'Composer 의존성 설치 중...');
if (! app()->environment('testing')
&& $this->extensionManager->hasComposerDependencies('plugins', $pluginName)) {
$composerResult = $this->extensionManager->runComposerInstall('plugins', $pluginName);
if (! $composerResult) {
Log::warning('플러그인 Composer 의존성 설치 실패', ['plugin' => $pluginName]);
}
}
}
// Phase 5: 오토로드 병합 실행 (트랜잭션 외부)
$onProgress?->__invoke('autoload', '오토로드 갱신 중...');
$this->extensionManager->updateComposerAutoload();
// Phase 6: 플러그인 상태 캐시 무효화
self::invalidatePluginStatusCache();
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
$this->incrementExtensionCacheVersion();
RouteCacheHelper::rebuild();
// 확장 미들웨어 인덱스 무효화 — 새 플러그인의 미들웨어 선언이 즉시 게이트에 반영.
ExtensionMiddlewareRegistry::flush();
// 훅 발행: 플러그인 설치 완료
HookManager::doAction('core.plugins.installed', $pluginName);
return true;
}
/**
@@ -932,6 +950,9 @@ class PluginManager implements PluginManagerInterface
* @param bool $deleteData 플러그인 데이터(테이블) 삭제 여부
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
* @param string|null $failureReason 실패 시 사유가 담기는 out 파라미터 (성공 시 null)
* @param array<int, array{directory: string, archive: string}>|null $preservedBackups
* 삭제 전에 보관한 운영자 소유 디렉토리(`custom/`)의 사본 경로가 담기는 out 파라미터.
* 운영자에게 "지웠지만 사본은 여기 있다" 를 알리기 위한 것이므로 호출부가 노출해야 한다.
* @return bool 제거 성공 여부
*
* @throws \Exception 플러그인을 찾을 수 없을 때
@@ -941,8 +962,10 @@ class PluginManager implements PluginManagerInterface
bool $deleteData = false,
?\Closure $onProgress = null,
?string &$failureReason = null,
?array &$preservedBackups = null,
): bool {
$failureReason = null;
$preservedBackups = [];
// 상태 가드: 진행 중 상태 체크
$existingRecord = $this->pluginRepository->findByIdentifier($pluginName);
@@ -1075,7 +1098,10 @@ class PluginManager implements PluginManagerInterface
// 활성 플러그인 디렉토리 전체 삭제 (_pending/_bundled에 원본 보존되므로 재설치 가능)
$onProgress?->__invoke('files', '파일 삭제 중...');
ExtensionPendingHelper::deleteExtensionDirectory($this->pluginsPath, $plugin->getIdentifier());
$preservedBackups = ExtensionPendingHelper::deleteExtensionDirectory(
$this->pluginsPath,
$plugin->getIdentifier()
);
// 메모리에서 플러그인 제거
unset($this->plugins[$plugin->getIdentifier()]);
+96 -67
View File
@@ -13,6 +13,7 @@ use App\Enums\ExtensionStatus;
use App\Enums\LayoutSourceType;
use App\Extension\Cache\CoreCacheDriver;
use App\Extension\Helpers\ExtensionBackupHelper;
use App\Extension\Helpers\ExtensionInstallRollbackHelper;
use App\Extension\Helpers\ExtensionPendingHelper;
use App\Extension\Helpers\ExtensionStatusGuard;
use App\Extension\Helpers\GithubHelper;
@@ -425,6 +426,12 @@ class TemplateManager implements TemplateManagerInterface
);
}
// 검증(2단계)은 복사된 활성 디렉토리를 읽어야 해서 복사보다 뒤에 온다. 그래서 검증이
// 실패하면 방금 만든 활성 디렉토리가 고아로 남는다 — DB 행이 없어 목록에도 뜨지 않고
// 오류도 남지 않은 채 디스크만 점유한다. 이번 호출이 만든 것이면 되돌린다.
$rollbackActivePath = $this->templatesPath.DIRECTORY_SEPARATOR.$templateName;
$rollbackDirExisted = File::isDirectory($rollbackActivePath);
// 1. _pending/_bundled에서 활성 디렉토리로 복사 (활성 디렉토리에 없는 경우)
// force=true 시 활성 디렉토리가 있어도 원본으로 덮어씀 (불완전 설치 복구)
$onProgress?->__invoke('copy', '파일 복사 중...');
@@ -435,79 +442,90 @@ class TemplateManager implements TemplateManagerInterface
// 2. 검증
$onProgress?->__invoke('validate', '검증 중...');
return DB::transaction(function () use ($templateName, $onProgress) {
$template = $this->getTemplate($templateName);
if (! $template) {
throw new \Exception(__('templates.errors.not_found', ['template' => $templateName]));
}
try {
return DB::transaction(function () use ($templateName, $onProgress) {
$template = $this->getTemplate($templateName);
if (! $template) {
throw new \Exception(__('templates.errors.not_found', ['template' => $templateName]));
}
// 의존성 확인
$this->checkDependencies($template);
// 의존성 확인
$this->checkDependencies($template);
// SEO 설정 검증 (설치 전 seo-config.json 유효성 검사)
$this->validateSeoConfig($templateName);
// SEO 설정 검증 (설치 전 seo-config.json 유효성 검사)
$this->validateSeoConfig($templateName);
// 레이아웃 검증 (설치 전 모든 레이아웃 파일 유효성 검사)
$this->validateLayouts($templateName);
// 레이아웃 검증 (설치 전 모든 레이아웃 파일 유효성 검사)
$this->validateLayouts($templateName);
// name과 description 다국어 변환 (역호환성)
$name = $this->convertToMultilingual($template['name']);
$description = $this->convertToMultilingual($template['description'] ?? '');
// name과 description 다국어 변환 (역호환성)
$name = $this->convertToMultilingual($template['name']);
$description = $this->convertToMultilingual($template['description'] ?? '');
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
$manifest = HookManager::applyFilters(
"template.{$templateName}.manifest.translations",
['name' => $name, 'description' => $description]
);
$name = $manifest['name'] ?? $name;
$description = $manifest['description'] ?? $description;
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
$manifest = HookManager::applyFilters(
"template.{$templateName}.manifest.translations",
['name' => $name, 'description' => $description]
);
$name = $manifest['name'] ?? $name;
$description = $manifest['description'] ?? $description;
// 3. DB 등록
$onProgress?->__invoke('db', 'DB 등록 중...');
// 3. DB 등록
$onProgress?->__invoke('db', 'DB 등록 중...');
// 템플릿 레코드 생성 또는 업데이트
$templateRecord = $this->templateRepository->updateOrCreate(
['identifier' => $templateName],
[
'vendor' => $template['vendor'],
'name' => $name,
'version' => $template['version'],
'type' => $template['type'],
'description' => $description,
'github_url' => $template['github_url'] ?? null,
'metadata' => $template['metadata'] ?? null,
'status' => ExtensionStatus::Inactive->value,
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
]
// 템플릿 레코드 생성 또는 업데이트
$templateRecord = $this->templateRepository->updateOrCreate(
['identifier' => $templateName],
[
'vendor' => $template['vendor'],
'name' => $name,
'version' => $template['version'],
'type' => $template['type'],
'description' => $description,
'github_url' => $template['github_url'] ?? null,
'metadata' => $template['metadata'] ?? null,
'status' => ExtensionStatus::Inactive->value,
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
]
);
// 4. 레이아웃 등록
$onProgress?->__invoke('layout', '레이아웃 등록 중...');
// 레이아웃 JSON 파일 일괄 등록
$this->registerLayouts($templateName, $templateRecord->id);
// 모듈 레이아웃 오버라이드 등록
$this->registerLayoutOverrides($templateName, $templateRecord->id);
// Extension 오버라이드 등록 (모듈/플러그인 Extension 커스터마이징)
$this->registerExtensionOverrides($templateName, $templateRecord->id);
// 에러 레이아웃 검증 (레이아웃 등록 후 수행)
$this->validateErrorLayouts($templateName, $template);
// 템플릿 상태 캐시 무효화
self::invalidateTemplateStatusCache();
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
$this->incrementExtensionCacheVersion();
// 훅 발행: 템플릿 설치 완료
HookManager::doAction('core.templates.installed', $templateName);
return true;
});
} catch (\Throwable $e) {
ExtensionInstallRollbackHelper::removeIfCreatedByThisInstall(
$rollbackActivePath,
$rollbackDirExisted,
$templateName,
'template',
);
// 4. 레이아웃 등록
$onProgress?->__invoke('layout', '레이아웃 등록 중...');
// 레이아웃 JSON 파일 일괄 등록
$this->registerLayouts($templateName, $templateRecord->id);
// 모듈 레이아웃 오버라이드 등록
$this->registerLayoutOverrides($templateName, $templateRecord->id);
// Extension 오버라이드 등록 (모듈/플러그인 Extension 커스터마이징)
$this->registerExtensionOverrides($templateName, $templateRecord->id);
// 에러 레이아웃 검증 (레이아웃 등록 후 수행)
$this->validateErrorLayouts($templateName, $template);
// 템플릿 상태 캐시 무효화
self::invalidateTemplateStatusCache();
// 확장 캐시 버전 증가 (프론트엔드가 새로운 캐시로 요청하도록)
$this->incrementExtensionCacheVersion();
// 훅 발행: 템플릿 설치 완료
HookManager::doAction('core.templates.installed', $templateName);
return true;
});
throw $e;
}
}
/**
@@ -731,12 +749,20 @@ class TemplateManager implements TemplateManagerInterface
*
* @param string $templateName 제거할 템플릿명 (identifier)
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
* @param array<int, array{directory: string, archive: string}>|null $preservedBackups
* 삭제 전에 보관한 운영자 소유 디렉토리(`custom/`)의 사본 경로가 담기는 out 파라미터.
* 운영자에게 "지웠지만 사본은 여기 있다" 를 알리기 위한 것이므로 호출부가 노출해야 한다.
* @return bool 제거 성공 여부
*
* @throws \Exception 템플릿을 찾을 수 없을 때
*/
public function uninstallTemplate(string $templateName, ?\Closure $onProgress = null): bool
{
public function uninstallTemplate(
string $templateName,
?\Closure $onProgress = null,
?array &$preservedBackups = null,
): bool {
$preservedBackups = [];
// 1. 캐시 삭제
$onProgress?->__invoke('cache', '캐시 삭제 중...');
@@ -782,7 +808,10 @@ class TemplateManager implements TemplateManagerInterface
$onProgress?->__invoke('files', '파일 삭제 중...');
// 활성 템플릿 디렉토리 전체 삭제 (_pending/_bundled에 원본 보존되므로 재설치 가능)
ExtensionPendingHelper::deleteExtensionDirectory($this->templatesPath, $templateName);
$preservedBackups = ExtensionPendingHelper::deleteExtensionDirectory(
$this->templatesPath,
$templateName
);
// 메모리에서 템플릿 제거
unset($this->templates[$templateName]);