v7.0.0-beta.1 release
This commit is contained in:
commit
6595fd0eb5
3967 files changed
+1875383
No files matched your search
@@ -0,0 +1,810 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\Storage\ModuleStorageDriver;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* 모듈 추상 클래스
|
||||
*
|
||||
* 모듈 개발자는 이 클래스를 상속받아 module.json만 작성하면 됩니다.
|
||||
* getIdentifier(), getVendor()는 디렉토리명에서 자동 추론됩니다.
|
||||
* getName(), getVersion(), getDescription()은 module.json에서 자동 파싱됩니다.
|
||||
*/
|
||||
abstract class AbstractModule implements ModuleInterface
|
||||
{
|
||||
/**
|
||||
* 모듈 디렉토리 경로 (캐시)
|
||||
*/
|
||||
private ?string $modulePath = null;
|
||||
|
||||
/**
|
||||
* 모듈 식별자 (캐시)
|
||||
*/
|
||||
private ?string $identifier = null;
|
||||
|
||||
/**
|
||||
* 스토리지 드라이버 인스턴스 (캐시)
|
||||
*/
|
||||
private ?StorageInterface $storage = null;
|
||||
|
||||
/**
|
||||
* manifest JSON 캐시
|
||||
*/
|
||||
private ?array $manifest = null;
|
||||
|
||||
/**
|
||||
* module.json 매니페스트를 파싱하여 캐싱합니다.
|
||||
*
|
||||
* @return array 매니페스트 배열 (파일 미존재 시 빈 배열)
|
||||
*/
|
||||
protected function loadManifest(): array
|
||||
{
|
||||
if ($this->manifest === null) {
|
||||
$manifestPath = $this->getModulePath().'/module.json';
|
||||
|
||||
if (file_exists($manifestPath)) {
|
||||
$this->manifest = json_decode(file_get_contents($manifestPath), true) ?? [];
|
||||
} else {
|
||||
$this->manifest = [];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈명 반환 (다국어 지원)
|
||||
*
|
||||
* module.json의 name 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getName(): string|array
|
||||
{
|
||||
return $this->loadManifest()['name'] ?? $this->getIdentifier();
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 버전 반환
|
||||
*
|
||||
* module.json의 version 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string 모듈 버전
|
||||
*/
|
||||
public function getVersion(): string
|
||||
{
|
||||
return $this->loadManifest()['version'] ?? '0.0.0';
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설명 반환 (다국어 지원)
|
||||
*
|
||||
* module.json의 description 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getDescription(): string|array
|
||||
{
|
||||
return $this->loadManifest()['description'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 디렉토리 경로 반환
|
||||
*/
|
||||
protected function getModulePath(): string
|
||||
{
|
||||
if ($this->modulePath === null) {
|
||||
$reflection = new ReflectionClass($this);
|
||||
$this->modulePath = dirname($reflection->getFileName());
|
||||
}
|
||||
|
||||
return $this->modulePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 식별자 반환 (디렉토리명에서 자동 추론)
|
||||
*
|
||||
* 디렉토리명이 'sirsoft-sample'이면 식별자도 'sirsoft-sample'
|
||||
*/
|
||||
final public function getIdentifier(): string
|
||||
{
|
||||
if ($this->identifier === null) {
|
||||
$this->identifier = basename($this->getModulePath());
|
||||
}
|
||||
|
||||
return $this->identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 벤더명 반환 (디렉토리명에서 자동 추론)
|
||||
*
|
||||
* 디렉토리명이 'sirsoft-sample'이면 벤더명은 'sirsoft'
|
||||
*/
|
||||
final public function getVendor(): string
|
||||
{
|
||||
$identifier = $this->getIdentifier();
|
||||
$parts = explode('-', $identifier);
|
||||
|
||||
return $parts[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설치
|
||||
*
|
||||
* 모듈 개발자가 설치 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function install(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 제거
|
||||
*
|
||||
* 모듈 개발자가 제거 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function uninstall(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈이 런타임에 동적으로 생성한 테이블 목록을 반환합니다.
|
||||
*
|
||||
* 반환된 테이블들은 ModuleManager가 일괄 삭제합니다.
|
||||
* 마이그레이션 롤백 전에 호출되므로 메타 테이블이 아직 존재합니다.
|
||||
*
|
||||
* 모듈 개발자가 동적 테이블이 있는 경우 오버라이드하세요.
|
||||
*
|
||||
* @return array<string> 삭제할 테이블명 배열
|
||||
*/
|
||||
public function getDynamicTables(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 활성화
|
||||
*
|
||||
* 모듈 개발자가 활성화 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function activate(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 비활성화
|
||||
*
|
||||
* 모듈 개발자가 비활성화 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function deactivate(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전별 업그레이드 스텝 반환
|
||||
*
|
||||
* 기본 구현: upgrades/ 디렉토리를 자동 스캔하여 UpgradeStepInterface 구현체를 수집합니다.
|
||||
* 모듈 개발자가 인라인 클로저를 사용하려면 오버라이드하세요.
|
||||
*
|
||||
* @return array<string, callable|UpgradeStepInterface> 버전 => 스텝 매핑
|
||||
*/
|
||||
public function upgrades(): array
|
||||
{
|
||||
return $this->discoverUpgradeSteps();
|
||||
}
|
||||
|
||||
/**
|
||||
* upgrades/ 디렉토리에서 업그레이드 스텝을 자동 발견합니다.
|
||||
*
|
||||
* 파일명 규칙: Upgrade_1_1_0.php → 버전 '1.1.0'
|
||||
* 클래스는 UpgradeStepInterface를 구현해야 합니다.
|
||||
*
|
||||
* @return array<string, UpgradeStepInterface> 버전 => 스텝 매핑
|
||||
*/
|
||||
protected function discoverUpgradeSteps(): array
|
||||
{
|
||||
$upgradesPath = $this->getModulePath().'/upgrades';
|
||||
|
||||
if (! is_dir($upgradesPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$steps = [];
|
||||
$files = glob($upgradesPath.'/Upgrade_*.php');
|
||||
|
||||
if (! $files) {
|
||||
return [];
|
||||
}
|
||||
|
||||
foreach ($files as $file) {
|
||||
$filename = pathinfo($file, PATHINFO_FILENAME);
|
||||
|
||||
// Upgrade_1_1_0 → 1.1.0, Upgrade_1_0_0_beta_1 → 1.0.0-beta.1
|
||||
if (! preg_match('/^Upgrade_(\d+)_(\d+)_(\d+)(?:_([a-zA-Z]\w*(?:_\d+)*))?$/', $filename, $matches)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$version = "{$matches[1]}.{$matches[2]}.{$matches[3]}";
|
||||
|
||||
if (! empty($matches[4])) {
|
||||
$version .= '-'.str_replace('_', '.', $matches[4]);
|
||||
}
|
||||
|
||||
require_once $file;
|
||||
|
||||
// 네임스페이스 추론: 모듈 네임스페이스 + Upgrades\ClassName
|
||||
$namespacePart = ExtensionManager::directoryToNamespace($this->getIdentifier());
|
||||
$namespace = 'Modules\\'.$namespacePart.'\\Upgrades\\'.$filename;
|
||||
|
||||
if (class_exists($namespace) && is_subclass_of($namespace, UpgradeStepInterface::class)) {
|
||||
$steps[$version] = new $namespace;
|
||||
}
|
||||
}
|
||||
|
||||
ksort($steps, SORT_NATURAL);
|
||||
|
||||
return $steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 라우트 파일 경로 목록 반환
|
||||
*
|
||||
* 기본적으로 src/routes/api.php, src/routes/web.php를 반환
|
||||
* 파일이 존재하는 경우에만 포함
|
||||
*/
|
||||
public function getRoutes(): array
|
||||
{
|
||||
$routes = [];
|
||||
$basePath = $this->getModulePath();
|
||||
|
||||
$apiRoute = $basePath.'/src/routes/api.php';
|
||||
$webRoute = $basePath.'/src/routes/web.php';
|
||||
|
||||
if (file_exists($apiRoute)) {
|
||||
$routes['api'] = $apiRoute;
|
||||
}
|
||||
|
||||
if (file_exists($webRoute)) {
|
||||
$routes['web'] = $webRoute;
|
||||
}
|
||||
|
||||
return $routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 마이그레이션 경로 반환
|
||||
*
|
||||
* 기본적으로 database/migrations 디렉토리를 반환
|
||||
* 디렉토리가 존재하는 경우에만 포함
|
||||
*/
|
||||
public function getMigrations(): array
|
||||
{
|
||||
$migrationsPath = $this->getModulePath().'/database/migrations';
|
||||
|
||||
if (is_dir($migrationsPath)) {
|
||||
return [$migrationsPath];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 뷰 파일 목록 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 뷰가 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getViews(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 역할 목록 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 역할이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 역할 정의 배열
|
||||
* [
|
||||
* [
|
||||
* 'identifier' => 'vendor-module.role-name',
|
||||
* 'name' => ['ko' => '...', 'en' => '...'],
|
||||
* 'description' => ['ko' => '...', 'en' => '...'],
|
||||
* ],
|
||||
* ]
|
||||
*/
|
||||
public function getRoles(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 권한 목록 반환 (계층형 구조, 다국어 지원)
|
||||
*
|
||||
* 구조: 모듈(1레벨) → 카테고리(2레벨) → 개별 권한(3레벨)
|
||||
* identifier는 자동 생성됨: {module}.{category}.{action}
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 권한이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 권한 정의 배열
|
||||
* [
|
||||
* 'name' => ['ko' => '...', 'en' => '...'],
|
||||
* 'description' => ['ko' => '...', 'en' => '...'],
|
||||
* 'categories' => [
|
||||
* [
|
||||
* 'identifier' => 'products',
|
||||
* 'name' => ['ko' => '...', 'en' => '...'],
|
||||
* 'permissions' => [
|
||||
* [
|
||||
* 'action' => 'read',
|
||||
* 'name' => ['ko' => '...', 'en' => '...'],
|
||||
* 'type' => 'admin', // admin 또는 user (기본값: admin)
|
||||
* 'roles' => ['admin', 'manager'],
|
||||
* ],
|
||||
* ],
|
||||
* ],
|
||||
* ],
|
||||
* ]
|
||||
*/
|
||||
public function getPermissions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설정 정보 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 설정이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getConfig(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 메뉴 목록 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 관리자 메뉴가 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getAdminMenus(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 커스텀 메뉴 목록 반환
|
||||
*
|
||||
* 모듈이 제공하는 관리자 사이드바 메뉴 정의
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 커스텀 메뉴가 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 메뉴 정의 배열
|
||||
* [
|
||||
* [
|
||||
* 'code' => 'menu_code', // 메뉴 고유 코드
|
||||
* 'name' => ['ko' => '...', 'en' => '...'], // 다국어 메뉴명
|
||||
* 'url' => '/admin/path', // 메뉴 URL
|
||||
* 'icon' => 'icon-name', // 아이콘 이름
|
||||
* 'sort_order' => 10, // 정렬 순서 (낮을수록 상위)
|
||||
* 'permission' => 'vendor-module.permission', // 필요 권한 (선택)
|
||||
* 'children' => [...], // 하위 메뉴 배열 (선택)
|
||||
* ],
|
||||
* ]
|
||||
*/
|
||||
public function getCustomMenus(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 훅 리스너 목록 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 훅 리스너가 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getHookListeners(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 스케줄 작업 목록 반환
|
||||
*
|
||||
* 모듈에서 등록하는 스케줄 작업 목록입니다.
|
||||
* 코어에서 이 메서드를 호출하여 모듈 스케줄러를 등록합니다.
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 스케줄 작업이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 스케줄 작업 배열
|
||||
* [
|
||||
* [
|
||||
* 'command' => 'artisan:command',
|
||||
* 'schedule' => 'daily' | 'hourly' | 'everyMinute' | 'weekly' | cron expression,
|
||||
* 'description' => '작업 설명 (선택)',
|
||||
* 'enabled_config' => 'setting.key' (선택, module_setting()으로 조회하여 활성화 여부 결정),
|
||||
* ],
|
||||
* ]
|
||||
*
|
||||
* enabled_config 형식:
|
||||
* - 'order_settings.auto_cancel_expired' → module_setting($identifier, 'order_settings.auto_cancel_expired')
|
||||
* - 'sirsoft-ecommerce.order_settings.auto_cancel_expired' → identifier 접두사 자동 제거 후 동일하게 조회
|
||||
*/
|
||||
public function getSchedules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설치 시 실행할 시더 클래스 목록 반환
|
||||
*
|
||||
* 빈 배열 반환 시 database/seeders/ 디렉토리의 모든 시더를 자동 검색합니다. (역호환)
|
||||
* 오버라이드하여 실행할 시더와 순서를 명시적으로 정의하세요.
|
||||
*
|
||||
* @return array<class-string<\Illuminate\Database\Seeder>> 시더 클래스명 배열 (FQCN)
|
||||
*/
|
||||
public function getSeeders(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 의존성 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 의존성이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설정 기본값 파일 경로 반환
|
||||
*
|
||||
* 기본적으로 config/settings/defaults.json 파일 경로 반환
|
||||
* 모듈 개발자가 다른 경로를 사용하는 경우 오버라이드
|
||||
*
|
||||
* @return string|null defaults.json 파일의 절대 경로, 없으면 null
|
||||
*/
|
||||
public function getSettingsDefaultsPath(): ?string
|
||||
{
|
||||
$path = $this->getModulePath().'/config/settings/defaults.json';
|
||||
|
||||
return file_exists($path) ? $path : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈에 환경설정이 있는지 확인
|
||||
*
|
||||
* @return bool 환경설정 존재 여부
|
||||
*/
|
||||
public function hasSettings(): bool
|
||||
{
|
||||
return $this->getSettingsDefaultsPath() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설정 저장 경로 반환
|
||||
*
|
||||
* @deprecated 향후 제거 예정. getStorage()->getBasePath('settings') 사용 권장
|
||||
*
|
||||
* @return string 설정 파일 저장 디렉토리 경로
|
||||
*/
|
||||
public function getSettingsStoragePath(): string
|
||||
{
|
||||
return $this->getStorage()->getBasePath('settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설정 기본값 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 기본 설정값이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 설정 기본값 배열
|
||||
*/
|
||||
public function getConfigValues(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설정 스키마 반환
|
||||
*
|
||||
* 민감한 필드(sensitive: true) 정보 등을 포함합니다.
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 민감한 필드가 있는 경우 오버라이드
|
||||
*
|
||||
* @return array 설정 스키마 배열
|
||||
*/
|
||||
public function getSettingsSchema(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub URL 반환
|
||||
*
|
||||
* module.json의 github_url 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|null GitHub URL 또는 null
|
||||
*/
|
||||
public function getGithubUrl(): ?string
|
||||
{
|
||||
return $this->loadManifest()['github_url'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 라이선스 반환
|
||||
*
|
||||
* module.json의 license 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|null 라이선스 또는 null
|
||||
*/
|
||||
public function getLicense(): ?string
|
||||
{
|
||||
return $this->loadManifest()['license'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 메타데이터 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 모듈 개발자가 메타데이터가 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getMetadata(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 경로 반환
|
||||
*
|
||||
* @return string extensions 디렉토리 경로
|
||||
*/
|
||||
public function getExtensionsPath(): string
|
||||
{
|
||||
return $this->getModulePath().'/resources/extensions';
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 목록 반환
|
||||
*
|
||||
* @return array<string> JSON 파일 경로 목록
|
||||
*/
|
||||
public function getLayoutExtensions(): array
|
||||
{
|
||||
$path = $this->getExtensionsPath();
|
||||
|
||||
if (! is_dir($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return glob($path.'/*.json') ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* SEO config 파일 경로를 반환합니다.
|
||||
*
|
||||
* @return string seo-config.json 파일 경로
|
||||
*/
|
||||
public function getSeoConfigPath(): string
|
||||
{
|
||||
return $this->getModulePath().'/resources/seo-config.json';
|
||||
}
|
||||
|
||||
/**
|
||||
* SEO config를 로드하여 반환합니다.
|
||||
*
|
||||
* @return array SEO 설정 배열 (파일 미존재 시 빈 배열)
|
||||
*/
|
||||
public function getSeoConfig(): array
|
||||
{
|
||||
$path = $this->getSeoConfigPath();
|
||||
|
||||
if (! file_exists($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$config = json_decode(file_get_contents($path), true);
|
||||
|
||||
return is_array($config) ? $config : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 그누보드7 코어 요구 버전 제약 반환
|
||||
*
|
||||
* module.json의 g7_version 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
* null 반환 시 버전 검증 건너뜀 (역호환성)
|
||||
*
|
||||
* @return string|null 버전 제약 문자열 또는 null
|
||||
*/
|
||||
public function getRequiredCoreVersion(): ?string
|
||||
{
|
||||
return $this->loadManifest()['g7_version'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 프론트엔드 에셋 정보 반환
|
||||
*
|
||||
* module.json의 assets 섹션에서 정보를 읽어 반환합니다.
|
||||
* 빌드된 JS/CSS 파일 경로와 외부 스크립트 정보를 포함합니다.
|
||||
*
|
||||
* @return array 에셋 정보 배열
|
||||
* [
|
||||
* 'js' => ['entry' => 'resources/js/index.ts', 'output' => 'dist/js/module.iife.js'],
|
||||
* 'css' => ['entry' => 'resources/css/main.css', 'output' => 'dist/css/module.css'],
|
||||
* 'handlers' => true,
|
||||
* 'static' => 'resources/assets/',
|
||||
* 'external' => [...],
|
||||
* ]
|
||||
*/
|
||||
public function getAssets(): array
|
||||
{
|
||||
return $this->loadManifest()['assets'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 에셋 로딩 설정 반환
|
||||
*
|
||||
* module.json의 loading 섹션에서 정보를 읽어 반환합니다.
|
||||
*
|
||||
* @return array 로딩 설정 배열
|
||||
* [
|
||||
* 'strategy' => 'global' | 'layout' | 'lazy',
|
||||
* 'priority' => 100,
|
||||
* 'dependencies' => [],
|
||||
* ]
|
||||
*/
|
||||
public function getAssetLoadingConfig(): array
|
||||
{
|
||||
$loading = $this->loadManifest()['loading'] ?? [];
|
||||
|
||||
return [
|
||||
'strategy' => $loading['strategy'] ?? 'global',
|
||||
'priority' => $loading['priority'] ?? 100,
|
||||
'dependencies' => $loading['dependencies'] ?? [],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 프론트엔드 에셋 빌드가 가능한지 확인합니다.
|
||||
*
|
||||
* hasAssets()와 달리 빌드 결과물이 아닌 소스 엔트리포인트 정의 여부로 판단합니다.
|
||||
* 빌드 커맨드에서 빌드 대상 필터링에 사용됩니다.
|
||||
*
|
||||
* @return bool 빌드 가능 여부
|
||||
*/
|
||||
public function canBuild(): bool
|
||||
{
|
||||
$assets = $this->getAssets();
|
||||
|
||||
return ! empty($assets['js']['entry']) || ! empty($assets['css']['entry']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈에 프론트엔드 에셋이 있는지 확인
|
||||
*
|
||||
* @return bool 에셋 존재 여부
|
||||
*/
|
||||
public function hasAssets(): bool
|
||||
{
|
||||
$assets = $this->getAssets();
|
||||
|
||||
// js 또는 css output이 정의되어 있고 파일이 존재하는지 확인
|
||||
if (! empty($assets['js']['output'])) {
|
||||
$jsPath = $this->getModulePath().'/'.$assets['js']['output'];
|
||||
if (file_exists($jsPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($assets['css']['output'])) {
|
||||
$cssPath = $this->getModulePath().'/'.$assets['css']['output'];
|
||||
if (file_exists($cssPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드된 에셋 파일 경로 반환
|
||||
*
|
||||
* @return array 빌드된 에셋 경로 배열 ['js' => '...', 'css' => '...']
|
||||
*/
|
||||
public function getBuiltAssetPaths(): array
|
||||
{
|
||||
$assets = $this->getAssets();
|
||||
$result = [];
|
||||
|
||||
if (! empty($assets['js']['output'])) {
|
||||
$jsPath = $this->getModulePath().'/'.$assets['js']['output'];
|
||||
if (file_exists($jsPath)) {
|
||||
$result['js'] = $assets['js']['output'];
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($assets['css']['output'])) {
|
||||
$cssPath = $this->getModulePath().'/'.$assets['css']['output'];
|
||||
if (file_exists($cssPath)) {
|
||||
$result['css'] = $assets['css']['output'];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 스토리지 드라이버 인스턴스 반환
|
||||
*
|
||||
* 모듈별로 격리된 파일 저장소를 제공합니다.
|
||||
* 카테고리별로 파일을 분리하여 저장합니다 (settings, attachments, images, cache, temp).
|
||||
*
|
||||
* @return StorageInterface 스토리지 드라이버 인스턴스
|
||||
*/
|
||||
public function getStorage(): StorageInterface
|
||||
{
|
||||
if ($this->storage === null) {
|
||||
$this->storage = new ModuleStorageDriver(
|
||||
$this->getIdentifier(),
|
||||
$this->getStorageDisk()
|
||||
);
|
||||
}
|
||||
|
||||
return $this->storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈에서 사용할 스토리지 디스크 이름 반환
|
||||
*
|
||||
* 기본값은 'modules'이며, 모듈 개발자가 다른 디스크를 사용하려면 오버라이드합니다.
|
||||
* 예: config('module-name.disk', 'modules')
|
||||
*
|
||||
* @return string 디스크 이름 (modules, public, s3 등)
|
||||
*/
|
||||
public function getStorageDisk(): string
|
||||
{
|
||||
return 'modules';
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리별 스토리지 기본 경로 반환
|
||||
*
|
||||
* @param string $category 카테고리 (settings, attachments, images, cache, temp)
|
||||
* @return string 전체 파일 시스템 경로
|
||||
*/
|
||||
public function getStorageBasePath(string $category): string
|
||||
{
|
||||
return $this->getStorage()->getBasePath($category);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일의 공개 URL 반환
|
||||
*
|
||||
* public disk인 경우 직접 URL을 반환하고,
|
||||
* private disk인 경우 null을 반환합니다 (별도 API 엔드포인트 사용).
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @return string|null 파일 URL (private disk인 경우 null)
|
||||
*/
|
||||
public function getStorageUrl(string $category, string $path): ?string
|
||||
{
|
||||
return $this->getStorage()->url($category, $path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,801 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Extension\Storage\PluginStorageDriver;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* 플러그인 추상 클래스
|
||||
*
|
||||
* 플러그인 개발자는 이 클래스를 상속받아 plugin.json만 작성하면 됩니다.
|
||||
* getIdentifier(), getVendor()는 디렉토리명에서 자동 추론됩니다.
|
||||
* getName(), getVersion(), getDescription()은 plugin.json에서 자동 파싱됩니다.
|
||||
*
|
||||
* 참고: 플러그인은 모듈과 달리 관리자 메뉴(getAdminMenus)를 추가할 수 없습니다.
|
||||
*/
|
||||
abstract class AbstractPlugin implements PluginInterface
|
||||
{
|
||||
/**
|
||||
* 플러그인 디렉토리 경로 (캐시)
|
||||
*/
|
||||
private ?string $pluginPath = null;
|
||||
|
||||
/**
|
||||
* 플러그인 식별자 (캐시)
|
||||
*/
|
||||
private ?string $identifier = null;
|
||||
|
||||
/**
|
||||
* 스토리지 드라이버 인스턴스 (캐시)
|
||||
*/
|
||||
private ?StorageInterface $storage = null;
|
||||
|
||||
/**
|
||||
* manifest JSON 캐시
|
||||
*/
|
||||
private ?array $manifest = null;
|
||||
|
||||
/**
|
||||
* plugin.json 매니페스트를 파싱하여 캐싱합니다.
|
||||
*
|
||||
* @return array 매니페스트 배열 (파일 미존재 시 빈 배열)
|
||||
*/
|
||||
protected function loadManifest(): array
|
||||
{
|
||||
if ($this->manifest === null) {
|
||||
$manifestPath = $this->getPluginPath().'/plugin.json';
|
||||
|
||||
if (file_exists($manifestPath)) {
|
||||
$this->manifest = json_decode(file_get_contents($manifestPath), true) ?? [];
|
||||
} else {
|
||||
$this->manifest = [];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인명 반환 (다국어 지원)
|
||||
*
|
||||
* plugin.json의 name 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getName(): string|array
|
||||
{
|
||||
return $this->loadManifest()['name'] ?? $this->getIdentifier();
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 버전 반환
|
||||
*
|
||||
* plugin.json의 version 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string 플러그인 버전
|
||||
*/
|
||||
public function getVersion(): string
|
||||
{
|
||||
return $this->loadManifest()['version'] ?? '0.0.0';
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설명 반환 (다국어 지원)
|
||||
*
|
||||
* plugin.json의 description 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getDescription(): string|array
|
||||
{
|
||||
return $this->loadManifest()['description'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 디렉토리 경로 반환
|
||||
*/
|
||||
protected function getPluginPath(): string
|
||||
{
|
||||
if ($this->pluginPath === null) {
|
||||
$reflection = new ReflectionClass($this);
|
||||
$this->pluginPath = dirname($reflection->getFileName());
|
||||
}
|
||||
|
||||
return $this->pluginPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 식별자 반환 (디렉토리명에서 자동 추론)
|
||||
*
|
||||
* 디렉토리명이 'sirsoft-sample'이면 식별자도 'sirsoft-sample'
|
||||
*/
|
||||
final public function getIdentifier(): string
|
||||
{
|
||||
if ($this->identifier === null) {
|
||||
$this->identifier = basename($this->getPluginPath());
|
||||
}
|
||||
|
||||
return $this->identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 벤더명 반환 (디렉토리명에서 자동 추론)
|
||||
*
|
||||
* 디렉토리명이 'sirsoft-sample'이면 벤더명은 'sirsoft'
|
||||
*/
|
||||
final public function getVendor(): string
|
||||
{
|
||||
$identifier = $this->getIdentifier();
|
||||
$parts = explode('-', $identifier);
|
||||
|
||||
return $parts[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설치
|
||||
*
|
||||
* 플러그인 개발자가 설치 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function install(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 제거
|
||||
*
|
||||
* 플러그인 개발자가 제거 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function uninstall(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인이 런타임에 동적으로 생성한 테이블 목록을 반환합니다.
|
||||
*
|
||||
* 반환된 테이블들은 PluginManager가 일괄 삭제합니다.
|
||||
* 마이그레이션 롤백 전에 호출되므로 메타 테이블이 아직 존재합니다.
|
||||
*
|
||||
* 플러그인 개발자가 동적 테이블이 있는 경우 오버라이드하세요.
|
||||
*
|
||||
* @return array<string> 삭제할 테이블명 배열
|
||||
*/
|
||||
public function getDynamicTables(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 활성화
|
||||
*
|
||||
* 플러그인 개발자가 활성화 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function activate(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 비활성화
|
||||
*
|
||||
* 플러그인 개발자가 비활성화 시 추가 작업이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function deactivate(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전별 업그레이드 스텝 반환
|
||||
*
|
||||
* 기본 구현: upgrades/ 디렉토리를 자동 스캔하여 UpgradeStepInterface 구현체를 수집합니다.
|
||||
* 플러그인 개발자가 인라인 클로저를 사용하려면 오버라이드하세요.
|
||||
*
|
||||
* @return array<string, callable|UpgradeStepInterface> 버전 => 스텝 매핑
|
||||
*/
|
||||
public function upgrades(): array
|
||||
{
|
||||
return $this->discoverUpgradeSteps();
|
||||
}
|
||||
|
||||
/**
|
||||
* upgrades/ 디렉토리에서 업그레이드 스텝을 자동 발견합니다.
|
||||
*
|
||||
* 파일명 규칙: Upgrade_1_1_0.php → 버전 '1.1.0'
|
||||
* 클래스는 UpgradeStepInterface를 구현해야 합니다.
|
||||
*
|
||||
* @return array<string, UpgradeStepInterface> 버전 => 스텝 매핑
|
||||
*/
|
||||
protected function discoverUpgradeSteps(): array
|
||||
{
|
||||
$upgradesPath = $this->getPluginPath().'/upgrades';
|
||||
|
||||
if (! is_dir($upgradesPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$steps = [];
|
||||
$files = glob($upgradesPath.'/Upgrade_*.php');
|
||||
|
||||
if (! $files) {
|
||||
return [];
|
||||
}
|
||||
|
||||
foreach ($files as $file) {
|
||||
$filename = pathinfo($file, PATHINFO_FILENAME);
|
||||
|
||||
// Upgrade_1_1_0 → 1.1.0, Upgrade_1_0_0_beta_1 → 1.0.0-beta.1
|
||||
if (! preg_match('/^Upgrade_(\d+)_(\d+)_(\d+)(?:_([a-zA-Z]\w*(?:_\d+)*))?$/', $filename, $matches)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$version = "{$matches[1]}.{$matches[2]}.{$matches[3]}";
|
||||
|
||||
if (! empty($matches[4])) {
|
||||
$version .= '-'.str_replace('_', '.', $matches[4]);
|
||||
}
|
||||
|
||||
require_once $file;
|
||||
|
||||
// 네임스페이스 추론: 플러그인 네임스페이스 + Upgrades\ClassName
|
||||
$namespacePart = ExtensionManager::directoryToNamespace($this->getIdentifier());
|
||||
$namespace = 'Plugins\\'.$namespacePart.'\\Upgrades\\'.$filename;
|
||||
|
||||
if (class_exists($namespace) && is_subclass_of($namespace, UpgradeStepInterface::class)) {
|
||||
$steps[$version] = new $namespace;
|
||||
}
|
||||
}
|
||||
|
||||
ksort($steps, SORT_NATURAL);
|
||||
|
||||
return $steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 라우트 파일 경로 목록 반환
|
||||
*
|
||||
* 기본적으로 src/routes/api.php, src/routes/web.php를 반환
|
||||
* 파일이 존재하는 경우에만 포함
|
||||
*/
|
||||
public function getRoutes(): array
|
||||
{
|
||||
$routes = [];
|
||||
$basePath = $this->getPluginPath();
|
||||
|
||||
$apiRoute = $basePath.'/src/routes/api.php';
|
||||
$webRoute = $basePath.'/src/routes/web.php';
|
||||
|
||||
if (file_exists($apiRoute)) {
|
||||
$routes['api'] = $apiRoute;
|
||||
}
|
||||
|
||||
if (file_exists($webRoute)) {
|
||||
$routes['web'] = $webRoute;
|
||||
}
|
||||
|
||||
return $routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 마이그레이션 경로 반환
|
||||
*
|
||||
* 기본적으로 database/migrations 디렉토리를 반환
|
||||
* 디렉토리가 존재하는 경우에만 포함
|
||||
*/
|
||||
public function getMigrations(): array
|
||||
{
|
||||
$migrationsPath = $this->getPluginPath().'/database/migrations';
|
||||
|
||||
if (is_dir($migrationsPath)) {
|
||||
return [$migrationsPath];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 뷰 파일 목록 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 뷰가 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getViews(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 역할 목록 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 역할이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 역할 정의 배열
|
||||
* [
|
||||
* [
|
||||
* 'identifier' => 'vendor-plugin.role-name',
|
||||
* 'name' => ['ko' => '...', 'en' => '...'],
|
||||
* 'description' => ['ko' => '...', 'en' => '...'],
|
||||
* ],
|
||||
* ]
|
||||
*/
|
||||
public function getRoles(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 권한 목록 반환 (단일 레벨 구조)
|
||||
*
|
||||
* 플러그인은 모듈과 달리 단일 레벨 권한 구조를 사용합니다.
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 권한이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 권한 정의 배열
|
||||
* [
|
||||
* [
|
||||
* 'identifier' => 'vendor-plugin.entity.action',
|
||||
* 'name' => ['ko' => '...', 'en' => '...'],
|
||||
* 'description' => ['ko' => '...', 'en' => '...'],
|
||||
* 'type' => 'admin', // admin 또는 user (기본값: admin)
|
||||
* 'roles' => ['admin', 'vendor-plugin.manager'],
|
||||
* ],
|
||||
* ]
|
||||
*/
|
||||
public function getPermissions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정 파일 경로 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 설정 파일이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array ['config_key' => '/path/to/config.php'] 형식
|
||||
*/
|
||||
public function getConfig(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정 값 반환 (상세 정보 조회용)
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 설정 값이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 설정 값 배열
|
||||
*/
|
||||
public function getConfigValues(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인이 제공하는 훅 정보 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 훅이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getHooks(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 훅 리스너 목록 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 훅 리스너가 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getHookListeners(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 스케줄 작업 목록 반환
|
||||
*
|
||||
* 플러그인에서 등록하는 스케줄 작업 목록입니다.
|
||||
* 코어에서 이 메서드를 호출하여 플러그인 스케줄러를 등록합니다.
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 스케줄 작업이 필요한 경우 오버라이드
|
||||
*
|
||||
* @return array 스케줄 작업 배열
|
||||
* [
|
||||
* [
|
||||
* 'command' => 'artisan:command',
|
||||
* 'schedule' => 'daily' | 'hourly' | 'everyMinute' | 'weekly' | cron expression,
|
||||
* 'description' => '작업 설명 (선택)',
|
||||
* 'enabled_config' => 'setting.key' (선택, plugin_setting()으로 조회하여 활성화 여부 결정),
|
||||
* ],
|
||||
* ]
|
||||
*
|
||||
* enabled_config 형식:
|
||||
* - 'payment.auto_capture' → plugin_setting($identifier, 'payment.auto_capture')
|
||||
* - 'sirsoft-payment.payment.auto_capture' → identifier 접두사 자동 제거 후 동일하게 조회
|
||||
*/
|
||||
public function getSchedules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설치 시 실행할 시더 클래스 목록 반환
|
||||
*
|
||||
* 빈 배열 반환 시 database/seeders/ 디렉토리의 모든 시더를 자동 검색합니다. (역호환)
|
||||
* 오버라이드하여 실행할 시더와 순서를 명시적으로 정의하세요.
|
||||
*
|
||||
* @return array<class-string<\Illuminate\Database\Seeder>> 시더 클래스명 배열 (FQCN)
|
||||
*/
|
||||
public function getSeeders(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 의존성 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 의존성이 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub URL 반환
|
||||
*
|
||||
* plugin.json의 github_url 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|null GitHub URL 또는 null
|
||||
*/
|
||||
public function getGithubUrl(): ?string
|
||||
{
|
||||
return $this->loadManifest()['github_url'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 라이선스 반환
|
||||
*
|
||||
* plugin.json의 license 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
*
|
||||
* @return string|null 라이선스 또는 null
|
||||
*/
|
||||
public function getLicense(): ?string
|
||||
{
|
||||
return $this->loadManifest()['license'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 메타데이터 반환
|
||||
*
|
||||
* 기본적으로 빈 배열 반환
|
||||
* 플러그인 개발자가 메타데이터가 필요한 경우 오버라이드
|
||||
*/
|
||||
public function getMetadata(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 경로 반환
|
||||
*
|
||||
* @return string extensions 디렉토리 경로
|
||||
*/
|
||||
public function getExtensionsPath(): string
|
||||
{
|
||||
return $this->getPluginPath().'/resources/extensions';
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 목록 반환
|
||||
*
|
||||
* @return array<string> JSON 파일 경로 목록
|
||||
*/
|
||||
public function getLayoutExtensions(): array
|
||||
{
|
||||
$path = $this->getExtensionsPath();
|
||||
|
||||
if (! is_dir($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return glob($path.'/*.json') ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* SEO config 파일 경로를 반환합니다.
|
||||
*
|
||||
* @return string seo-config.json 파일 경로
|
||||
*/
|
||||
public function getSeoConfigPath(): string
|
||||
{
|
||||
return $this->getPluginPath().'/resources/seo-config.json';
|
||||
}
|
||||
|
||||
/**
|
||||
* SEO config를 로드하여 반환합니다.
|
||||
*
|
||||
* @return array SEO 설정 배열 (파일 미존재 시 빈 배열)
|
||||
*/
|
||||
public function getSeoConfig(): array
|
||||
{
|
||||
$path = $this->getSeoConfigPath();
|
||||
|
||||
if (! file_exists($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$config = json_decode(file_get_contents($path), true);
|
||||
|
||||
return is_array($config) ? $config : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 그누보드7 코어 요구 버전 제약 반환
|
||||
*
|
||||
* plugin.json의 g7_version 필드에서 읽습니다. 오버라이드 가능합니다.
|
||||
* null 반환 시 버전 검증 건너뜀 (역호환성)
|
||||
*
|
||||
* @return string|null 버전 제약 문자열 또는 null
|
||||
*/
|
||||
public function getRequiredCoreVersion(): ?string
|
||||
{
|
||||
return $this->loadManifest()['g7_version'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 프론트엔드 에셋 정보 반환
|
||||
*
|
||||
* plugin.json의 assets 섹션에서 정보를 읽어 반환합니다.
|
||||
* 빌드된 JS/CSS 파일 경로와 외부 스크립트 정보를 포함합니다.
|
||||
*
|
||||
* @return array 에셋 정보 배열
|
||||
* [
|
||||
* 'js' => ['entry' => 'resources/js/index.ts', 'output' => 'dist/js/plugin.iife.js'],
|
||||
* 'css' => ['entry' => 'resources/css/main.css', 'output' => 'dist/css/plugin.css'],
|
||||
* 'handlers' => true,
|
||||
* 'static' => 'resources/assets/',
|
||||
* 'external' => [...],
|
||||
* ]
|
||||
*/
|
||||
public function getAssets(): array
|
||||
{
|
||||
return $this->loadManifest()['assets'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 에셋 로딩 설정 반환
|
||||
*
|
||||
* plugin.json의 loading 섹션에서 정보를 읽어 반환합니다.
|
||||
*
|
||||
* @return array 로딩 설정 배열
|
||||
* [
|
||||
* 'strategy' => 'global' | 'layout' | 'lazy',
|
||||
* 'priority' => 100,
|
||||
* 'dependencies' => [],
|
||||
* ]
|
||||
*/
|
||||
public function getAssetLoadingConfig(): array
|
||||
{
|
||||
$loading = $this->loadManifest()['loading'] ?? [];
|
||||
|
||||
return [
|
||||
'strategy' => $loading['strategy'] ?? 'global',
|
||||
'priority' => $loading['priority'] ?? 100,
|
||||
'dependencies' => $loading['dependencies'] ?? [],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 프론트엔드 에셋 빌드가 가능한지 확인합니다.
|
||||
*
|
||||
* hasAssets()와 달리 빌드 결과물이 아닌 소스 엔트리포인트 정의 여부로 판단합니다.
|
||||
* 빌드 커맨드에서 빌드 대상 필터링에 사용됩니다.
|
||||
*
|
||||
* @return bool 빌드 가능 여부
|
||||
*/
|
||||
public function canBuild(): bool
|
||||
{
|
||||
$assets = $this->getAssets();
|
||||
|
||||
return ! empty($assets['js']['entry']) || ! empty($assets['css']['entry']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인에 프론트엔드 에셋이 있는지 확인
|
||||
*
|
||||
* @return bool 에셋 존재 여부
|
||||
*/
|
||||
public function hasAssets(): bool
|
||||
{
|
||||
$assets = $this->getAssets();
|
||||
|
||||
// js 또는 css output이 정의되어 있고 파일이 존재하는지 확인
|
||||
if (! empty($assets['js']['output'])) {
|
||||
$jsPath = $this->getPluginPath().'/'.$assets['js']['output'];
|
||||
if (file_exists($jsPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($assets['css']['output'])) {
|
||||
$cssPath = $this->getPluginPath().'/'.$assets['css']['output'];
|
||||
if (file_exists($cssPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드된 에셋 파일 경로 반환
|
||||
*
|
||||
* @return array 빌드된 에셋 경로 배열 ['js' => '...', 'css' => '...']
|
||||
*/
|
||||
public function getBuiltAssetPaths(): array
|
||||
{
|
||||
$assets = $this->getAssets();
|
||||
$result = [];
|
||||
|
||||
if (! empty($assets['js']['output'])) {
|
||||
$jsPath = $this->getPluginPath().'/'.$assets['js']['output'];
|
||||
if (file_exists($jsPath)) {
|
||||
$result['js'] = $assets['js']['output'];
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($assets['css']['output'])) {
|
||||
$cssPath = $this->getPluginPath().'/'.$assets['css']['output'];
|
||||
if (file_exists($cssPath)) {
|
||||
$result['css'] = $assets['css']['output'];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인이 설정 페이지를 가지고 있는지 확인합니다.
|
||||
*
|
||||
* 설정 레이아웃 파일이 존재하면 설정 페이지가 있는 것으로 간주합니다.
|
||||
*
|
||||
* @return bool 설정 페이지 존재 여부
|
||||
*/
|
||||
public function hasSettings(): bool
|
||||
{
|
||||
return $this->getSettingsLayout() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정 기본값 파일 경로를 반환합니다.
|
||||
*
|
||||
* config/settings/defaults.json 파일이 존재하면 해당 경로를 반환합니다.
|
||||
*
|
||||
* @return string|null defaults.json 파일 절대 경로 또는 null
|
||||
*/
|
||||
public function getSettingsDefaultsPath(): ?string
|
||||
{
|
||||
$path = $this->getPluginPath().'/config/settings/defaults.json';
|
||||
|
||||
return file_exists($path) ? $path : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정 페이지 레이아웃 경로를 반환합니다.
|
||||
*
|
||||
* 기본적으로 resources/layouts/admin/plugin_settings.json 경로를 반환합니다.
|
||||
* 파일이 존재하지 않으면 null을 반환합니다.
|
||||
* 플러그인 개발자가 커스텀 경로가 필요한 경우 오버라이드합니다.
|
||||
*
|
||||
* @return string|null 레이아웃 파일 절대 경로 또는 null
|
||||
*/
|
||||
public function getSettingsLayout(): ?string
|
||||
{
|
||||
$layoutPath = $this->getPluginPath().'/resources/layouts/admin/plugin_settings.json';
|
||||
|
||||
return file_exists($layoutPath) ? $layoutPath : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정 스키마를 반환합니다.
|
||||
*
|
||||
* 기본적으로 빈 배열 반환.
|
||||
* 플러그인 개발자가 설정이 필요한 경우 오버라이드합니다.
|
||||
*
|
||||
* @return array 설정 스키마 배열
|
||||
*/
|
||||
public function getSettingsSchema(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 설정 페이지 라우트 경로를 반환합니다.
|
||||
*
|
||||
* 기본적으로 '/admin/plugins/{identifier}/settings' 형식을 반환합니다.
|
||||
* 설정 레이아웃이 없으면 null을 반환합니다.
|
||||
* 플러그인 개발자가 커스텀 경로가 필요한 경우 오버라이드합니다.
|
||||
*
|
||||
* @return string|null 설정 페이지 라우트 또는 null
|
||||
*/
|
||||
public function getSettingsRoute(): ?string
|
||||
{
|
||||
if (! $this->hasSettings()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return '/admin/plugins/'.$this->getIdentifier().'/settings';
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 스토리지 드라이버 인스턴스 반환
|
||||
*
|
||||
* 플러그인별로 격리된 파일 저장소를 제공합니다.
|
||||
* 카테고리별로 파일을 분리하여 저장합니다 (settings, data, temp).
|
||||
*
|
||||
* @return StorageInterface 스토리지 드라이버 인스턴스
|
||||
*/
|
||||
public function getStorage(): StorageInterface
|
||||
{
|
||||
if ($this->storage === null) {
|
||||
$this->storage = new PluginStorageDriver(
|
||||
$this->getIdentifier(),
|
||||
$this->getStorageDisk()
|
||||
);
|
||||
}
|
||||
|
||||
return $this->storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인에서 사용할 스토리지 디스크 이름 반환
|
||||
*
|
||||
* 기본값은 'plugins'이며, 플러그인 개발자가 다른 디스크를 사용하려면 오버라이드합니다.
|
||||
* 예: config('plugin-name.disk', 'plugins')
|
||||
*
|
||||
* @return string 디스크 이름 (plugins, public, s3 등)
|
||||
*/
|
||||
public function getStorageDisk(): string
|
||||
{
|
||||
return 'plugins';
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리별 스토리지 기본 경로 반환
|
||||
*
|
||||
* @param string $category 카테고리 (settings, data, temp)
|
||||
* @return string 전체 파일 시스템 경로
|
||||
*/
|
||||
public function getStorageBasePath(string $category): string
|
||||
{
|
||||
return $this->getStorage()->getBasePath($category);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일의 공개 URL 반환
|
||||
*
|
||||
* public disk인 경우 직접 URL을 반환하고,
|
||||
* private disk인 경우 null을 반환합니다 (별도 API 엔드포인트 사용).
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @return string|null 파일 URL (private disk인 경우 null)
|
||||
*/
|
||||
public function getStorageUrl(string $category, string $path): ?string
|
||||
{
|
||||
return $this->getStorage()->url($category, $path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* 모듈 서비스 프로바이더 베이스 클래스
|
||||
*
|
||||
* 모든 모듈의 ServiceProvider가 상속받는 추상 클래스입니다.
|
||||
* 공통 기능을 자동화하여 코드 중복을 제거하고 일관성을 확보합니다.
|
||||
*/
|
||||
abstract class BaseModuleServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* 모듈 식별자 (자식 클래스에서 반드시 정의)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $moduleIdentifier;
|
||||
|
||||
/**
|
||||
* StorageInterface가 필요한 서비스 클래스 목록
|
||||
*
|
||||
* 이 배열에 정의된 서비스들은 자동으로 StorageInterface가 주입됩니다.
|
||||
*
|
||||
* @var array<int, class-string>
|
||||
*/
|
||||
protected array $storageServices = [];
|
||||
|
||||
/**
|
||||
* Repository 인터페이스와 구현체 매핑
|
||||
*
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
protected array $repositories = [];
|
||||
|
||||
/**
|
||||
* ServiceProvider 파일이 위치한 디렉토리 경로 (캐시)
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
private ?string $providerPath = null;
|
||||
|
||||
/**
|
||||
* Register services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
// Repository 바인딩
|
||||
$this->registerRepositories();
|
||||
|
||||
// StorageInterface 바인딩
|
||||
$this->registerStorageBindings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
// 마이그레이션 자동 로드
|
||||
$this->loadModuleMigrations();
|
||||
|
||||
// 다국어 자동 로드
|
||||
$this->loadModuleTranslations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Repository 인터페이스를 구현체에 바인딩합니다.
|
||||
*/
|
||||
protected function registerRepositories(): void
|
||||
{
|
||||
foreach ($this->repositories as $interface => $implementation) {
|
||||
$this->app->bind($interface, $implementation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* StorageInterface를 필요로 하는 서비스에 자동 바인딩합니다.
|
||||
*
|
||||
* 각 서비스의 생성자에서 StorageInterface를 주입받으면,
|
||||
* 해당 모듈의 Storage 인스턴스가 자동으로 주입됩니다.
|
||||
*/
|
||||
protected function registerStorageBindings(): void
|
||||
{
|
||||
if (empty($this->storageServices)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->app->when($this->storageServices)
|
||||
->needs(StorageInterface::class)
|
||||
->give(function () {
|
||||
return $this->app->make(ModuleManager::class)
|
||||
->getModule($this->moduleIdentifier)
|
||||
->getStorage();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceProvider 파일의 디렉토리 경로 반환
|
||||
*
|
||||
* ReflectionClass를 사용하여 자식 클래스의 실제 경로를 반환합니다.
|
||||
* __DIR__은 베이스 클래스 경로를 반환하므로 사용할 수 없습니다.
|
||||
*
|
||||
* @return string ServiceProvider 디렉토리 경로 (예: modules/vendor-module/src/Providers)
|
||||
*/
|
||||
protected function getProviderPath(): string
|
||||
{
|
||||
if ($this->providerPath === null) {
|
||||
$reflection = new ReflectionClass($this);
|
||||
$this->providerPath = dirname($reflection->getFileName());
|
||||
}
|
||||
|
||||
return $this->providerPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈의 마이그레이션 파일을 로드합니다.
|
||||
*
|
||||
* 기본 경로: {module}/database/migrations
|
||||
* 자식 클래스는 {module}/src/Providers에 위치해야 합니다.
|
||||
*
|
||||
* 참고: 모듈 마이그레이션은 php artisan migrate와 분리됩니다.
|
||||
* module:install, module:activate 명령어에서 ModuleManager::runMigrations()로 실행됩니다.
|
||||
*/
|
||||
protected function loadModuleMigrations(): void
|
||||
{
|
||||
// 모듈 마이그레이션은 loadMigrationsFrom()으로 등록하지 않음
|
||||
// 대신 ModuleManager::runMigrations()에서 별도로 실행됨
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈의 다국어 파일을 로드합니다.
|
||||
*
|
||||
* 기본 경로: {module}/src/lang
|
||||
* 자식 클래스는 {module}/src/Providers에 위치해야 합니다.
|
||||
*/
|
||||
protected function loadModuleTranslations(): void
|
||||
{
|
||||
$langPath = $this->getProviderPath().'/../lang';
|
||||
|
||||
if (is_dir($langPath)) {
|
||||
$this->loadTranslationsFrom($langPath, $this->moduleIdentifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use Composer\Semver\Semver;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 그누보드7 코어 버전 호환성 검증 유틸리티
|
||||
*
|
||||
* 확장(모듈, 플러그인, 템플릿)이 요구하는 그누보드7 코어 버전과
|
||||
* 현재 설치된 코어 버전의 호환성을 검증합니다.
|
||||
*/
|
||||
class CoreVersionChecker
|
||||
{
|
||||
/**
|
||||
* 캐시 키 접두사
|
||||
*/
|
||||
private const CACHE_PREFIX = 'core_version_check.';
|
||||
|
||||
/**
|
||||
* 캐시 유효 시간 (초)
|
||||
*/
|
||||
private const CACHE_TTL = 3600;
|
||||
|
||||
/**
|
||||
* 현재 설치된 그누보드7 코어 버전 반환
|
||||
*
|
||||
* @return string 코어 버전
|
||||
*/
|
||||
public static function getCoreVersion(): string
|
||||
{
|
||||
return config('app.version', '7.0.0-alpha.1');
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 제약 조건 충족 여부 확인
|
||||
*
|
||||
* @param string $constraint Semantic Versioning 제약 문자열
|
||||
* @return bool 충족 여부
|
||||
*/
|
||||
public static function satisfies(string $constraint): bool
|
||||
{
|
||||
try {
|
||||
return Semver::satisfies(self::getCoreVersion(), $constraint);
|
||||
} catch (Exception $e) {
|
||||
Log::warning(__('extensions.errors.version_check_failed'), [
|
||||
'constraint' => $constraint,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 코어 버전 호환성 검증
|
||||
*
|
||||
* @param string|null $requiredVersion 요구 버전 제약
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $type 확장 타입 (module, plugin, template)
|
||||
* @return bool 항상 true (검증 실패 시 예외 발생)
|
||||
*
|
||||
* @throws Exception 버전 미충족 시
|
||||
*/
|
||||
public static function validateExtension(
|
||||
?string $requiredVersion,
|
||||
string $identifier,
|
||||
string $type
|
||||
): bool {
|
||||
if ($requiredVersion === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! self::satisfies($requiredVersion)) {
|
||||
throw new Exception(__('extensions.errors.core_version_mismatch', [
|
||||
'extension' => $identifier,
|
||||
'type' => __('extensions.types.'.$type),
|
||||
'required' => $requiredVersion,
|
||||
'installed' => self::getCoreVersion(),
|
||||
]));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 코어 버전 호환성 확인 (예외 없음)
|
||||
*
|
||||
* @param string|null $requiredVersion 요구 버전 제약
|
||||
* @return bool 호환 여부
|
||||
*/
|
||||
public static function isCompatible(?string $requiredVersion): bool
|
||||
{
|
||||
if ($requiredVersion === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return self::satisfies($requiredVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 검증 캐시 키 생성
|
||||
*
|
||||
* @param string $type 확장 타입 (modules, plugins, templates)
|
||||
* @return string 캐시 키
|
||||
*/
|
||||
public static function getCacheKey(string $type): string
|
||||
{
|
||||
return self::CACHE_PREFIX.$type.'.'.self::getCoreVersion();
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 버전 검증 캐시 삭제
|
||||
*/
|
||||
public static function clearCache(): void
|
||||
{
|
||||
Cache::forget(self::getCacheKey('modules'));
|
||||
Cache::forget(self::getCacheKey('plugins'));
|
||||
Cache::forget(self::getCacheKey('templates'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 TTL 반환
|
||||
*
|
||||
* @return int 캐시 유효 시간 (초)
|
||||
*/
|
||||
public static function getCacheTtl(): int
|
||||
{
|
||||
return self::CACHE_TTL;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* Changelog 파서 헬퍼
|
||||
*
|
||||
* CHANGELOG.md 파일을 파싱하여 버전별 구조화된 배열을 반환합니다.
|
||||
* Keep a Changelog (https://keepachangelog.com) 형식을 따릅니다.
|
||||
*/
|
||||
class ChangelogParser
|
||||
{
|
||||
/**
|
||||
* CHANGELOG.md 파일을 파싱하여 버전별 구조화된 배열을 반환합니다.
|
||||
*
|
||||
* @param string $filePath CHANGELOG.md 파일 경로
|
||||
* @return array 버전별 구조화된 배열
|
||||
*/
|
||||
public static function parse(string $filePath): array
|
||||
{
|
||||
if (! File::exists($filePath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$content = File::get($filePath);
|
||||
|
||||
if (empty(trim($content))) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return static::parseContent($content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정된 버전 범위(from 초과 ~ to 이하)의 엔트리를 추출합니다.
|
||||
*
|
||||
* @param string $filePath CHANGELOG.md 파일 경로
|
||||
* @param string $fromVersion 시작 버전 (이 버전은 포함하지 않음)
|
||||
* @param string $toVersion 끝 버전 (이 버전은 포함)
|
||||
* @return array 범위 내 버전 엔트리 배열
|
||||
*/
|
||||
public static function getVersionRange(string $filePath, string $fromVersion, string $toVersion): array
|
||||
{
|
||||
$entries = static::parse($filePath);
|
||||
|
||||
if (empty($entries)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter($entries, function (array $entry) use ($fromVersion, $toVersion) {
|
||||
$version = $entry['version'];
|
||||
|
||||
return version_compare($version, $fromVersion, '>') && version_compare($version, $toVersion, '<=');
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 소스별(active/bundled) CHANGELOG.md 파일 경로를 결정합니다.
|
||||
*
|
||||
* active 소스에서 파일을 찾지 못하면 _bundled로 자동 폴백합니다.
|
||||
* (미설치 확장도 _bundled의 CHANGELOG를 표시할 수 있도록)
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로 (예: base_path('modules'))
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string|null $source 소스 ('active', 'bundled', null=active)
|
||||
* @return string|null CHANGELOG.md 파일 경로 (파일 미존재 시 null)
|
||||
*/
|
||||
public static function resolveChangelogPath(string $basePath, string $identifier, ?string $source = null): ?string
|
||||
{
|
||||
$source = $source ?? 'active';
|
||||
|
||||
if ($source === 'bundled') {
|
||||
$filePath = $basePath.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.$identifier.DIRECTORY_SEPARATOR.'CHANGELOG.md';
|
||||
} else {
|
||||
$filePath = $basePath.DIRECTORY_SEPARATOR.$identifier.DIRECTORY_SEPARATOR.'CHANGELOG.md';
|
||||
}
|
||||
|
||||
if (File::exists($filePath)) {
|
||||
return $filePath;
|
||||
}
|
||||
|
||||
// active에서 못 찾으면 _bundled로 폴백
|
||||
if ($source === 'active') {
|
||||
$bundledPath = $basePath.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.$identifier.DIRECTORY_SEPARATOR.'CHANGELOG.md';
|
||||
|
||||
if (File::exists($bundledPath)) {
|
||||
return $bundledPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* CHANGELOG.md 문자열 콘텐츠를 파싱합니다.
|
||||
*
|
||||
* @param string $content 파일 내용
|
||||
* @return array 버전별 구조화된 배열
|
||||
*/
|
||||
public static function parseFromString(string $content): array
|
||||
{
|
||||
if (empty(trim($content))) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return static::parseContent($content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 콘텐츠에서 지정된 버전 범위(from 초과 ~ to 이하)의 엔트리를 추출합니다.
|
||||
*
|
||||
* @param string $content CHANGELOG.md 파일 내용
|
||||
* @param string $fromVersion 시작 버전 (이 버전은 포함하지 않음)
|
||||
* @param string $toVersion 끝 버전 (이 버전은 포함)
|
||||
* @return array 범위 내 버전 엔트리 배열
|
||||
*/
|
||||
public static function getVersionRangeFromString(string $content, string $fromVersion, string $toVersion): array
|
||||
{
|
||||
$entries = static::parseFromString($content);
|
||||
|
||||
if (empty($entries)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter($entries, function (array $entry) use ($fromVersion, $toVersion) {
|
||||
$version = $entry['version'];
|
||||
|
||||
return version_compare($version, $fromVersion, '>') && version_compare($version, $toVersion, '<=');
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* CHANGELOG.md 내용을 파싱합니다.
|
||||
*
|
||||
* @param string $content 파일 내용
|
||||
* @return array 버전별 구조화된 배열
|
||||
*/
|
||||
private static function parseContent(string $content): array
|
||||
{
|
||||
$lines = explode("\n", $content);
|
||||
$entries = [];
|
||||
$currentEntry = null;
|
||||
$currentCategoryIndex = -1;
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$trimmedLine = trim($line);
|
||||
|
||||
// ## [버전] - 날짜 패턴 (프리릴리스 지원: 7.0.0-alpha.1 등)
|
||||
if (preg_match('/^##\s+\[?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*)?)\]?\s*(?:-\s*(.+))?$/', $trimmedLine, $matches)) {
|
||||
if ($currentEntry !== null) {
|
||||
$entries[] = $currentEntry;
|
||||
}
|
||||
|
||||
$currentEntry = [
|
||||
'version' => $matches[1],
|
||||
'date' => isset($matches[2]) ? trim($matches[2]) : null,
|
||||
'categories' => [],
|
||||
];
|
||||
$currentCategoryIndex = -1;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// ### 카테고리 패턴
|
||||
if (preg_match('/^###\s+(.+)$/', $trimmedLine, $matches)) {
|
||||
if ($currentEntry !== null) {
|
||||
$currentEntry['categories'][] = [
|
||||
'name' => trim($matches[1]),
|
||||
'items' => [],
|
||||
];
|
||||
$currentCategoryIndex = count($currentEntry['categories']) - 1;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// - 항목 패턴
|
||||
if (preg_match('/^-\s+(.+)$/', $trimmedLine, $matches)) {
|
||||
if ($currentEntry !== null && $currentCategoryIndex >= 0) {
|
||||
$currentEntry['categories'][$currentCategoryIndex]['items'][] = trim($matches[1]);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 마지막 엔트리 추가
|
||||
if ($currentEntry !== null) {
|
||||
$entries[] = $currentEntry;
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CoreBackupHelper
|
||||
{
|
||||
/**
|
||||
* 코어 파일을 선택적으로 백업합니다.
|
||||
*
|
||||
* @param array $targets 백업 대상 경로 목록
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @param array $excludes 제외할 디렉토리/파일 이름 목록 (예: ['node_modules', '.git'])
|
||||
* @return string 백업 디렉토리 경로
|
||||
*/
|
||||
public static function createBackup(array $targets, ?\Closure $onProgress = null, array $excludes = []): string
|
||||
{
|
||||
$timestamp = date('Ymd_His');
|
||||
$backupPath = storage_path("app/core_backups/core_{$timestamp}");
|
||||
|
||||
File::ensureDirectoryExists($backupPath, 0770, true);
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$sourcePath = base_path($target);
|
||||
|
||||
if (! File::exists($sourcePath) && ! File::isDirectory($sourcePath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$onProgress?->__invoke('backup', $target);
|
||||
$destPath = $backupPath.DIRECTORY_SEPARATOR.$target;
|
||||
|
||||
if (File::isDirectory($sourcePath)) {
|
||||
FilePermissionHelper::copyDirectory($sourcePath, $destPath, $onProgress, $excludes);
|
||||
} else {
|
||||
FilePermissionHelper::copyFile($sourcePath, $destPath);
|
||||
}
|
||||
}
|
||||
|
||||
Log::info('코어 백업 생성 완료', ['path' => $backupPath]);
|
||||
|
||||
return $backupPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 백업에서 코어 파일을 선택적으로 복원합니다.
|
||||
*
|
||||
* 복원 시에는 FilePermissionHelper를 사용하여 퍼미션을 보존합니다.
|
||||
* 백업 파일을 복원하되 현재 파일의 퍼미션은 유지합니다.
|
||||
* 개별 target 복원 실패 시에도 나머지 target 복원을 계속 진행합니다.
|
||||
*
|
||||
* @param string $backupPath 백업 디렉토리 경로
|
||||
* @param array $targets 복원 대상 경로 목록
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @param array $excludes 제외할 디렉토리/파일 이름 목록 (예: ['node_modules', '.git'])
|
||||
* @return array 복원 실패한 target 목록 (빈 배열이면 전체 성공)
|
||||
*/
|
||||
public static function restoreFromBackup(string $backupPath, array $targets, ?\Closure $onProgress = null, array $excludes = []): array
|
||||
{
|
||||
$failedTargets = [];
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$src = $backupPath.DIRECTORY_SEPARATOR.$target;
|
||||
$dest = base_path($target);
|
||||
|
||||
if (! File::exists($src) && ! File::isDirectory($src)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$onProgress?->__invoke('restore', $target);
|
||||
|
||||
if (File::isDirectory($src)) {
|
||||
FilePermissionHelper::copyDirectory($src, $dest, $onProgress, $excludes);
|
||||
} else {
|
||||
FilePermissionHelper::copyFile($src, $dest);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error("코어 백업 복원 실패 (계속 진행): {$target}", [
|
||||
'error' => $e->getMessage(),
|
||||
'backup_path' => $backupPath,
|
||||
]);
|
||||
$failedTargets[] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($failedTargets)) {
|
||||
Log::info('코어 백업 복원 완료', ['backup_path' => $backupPath]);
|
||||
} else {
|
||||
Log::warning('코어 백업 부분 복원 완료', [
|
||||
'backup_path' => $backupPath,
|
||||
'failed_targets' => $failedTargets,
|
||||
]);
|
||||
}
|
||||
|
||||
return $failedTargets;
|
||||
}
|
||||
|
||||
/**
|
||||
* 백업을 삭제합니다.
|
||||
*
|
||||
* @param string $backupPath 백업 디렉토리 경로
|
||||
*/
|
||||
public static function deleteBackup(string $backupPath): void
|
||||
{
|
||||
if (! File::isDirectory($backupPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
File::deleteDirectory($backupPath);
|
||||
|
||||
// Windows: 파일 핸들 잠금으로 빈 디렉토리가 남을 수 있음 — 재시도
|
||||
if (File::isDirectory($backupPath)) {
|
||||
usleep(500_000); // 0.5초 대기 후 재시도
|
||||
File::deleteDirectory($backupPath);
|
||||
}
|
||||
|
||||
if (File::isDirectory($backupPath)) {
|
||||
Log::warning('코어 백업 삭제 불완전 (잔여 디렉토리 존재)', ['path' => $backupPath]);
|
||||
} else {
|
||||
Log::info('코어 백업 삭제 완료', ['path' => $backupPath]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 코어 백업 목록을 반환합니다.
|
||||
*
|
||||
* @return array 백업 목록 [{path, created_at, size}]
|
||||
*/
|
||||
public static function listBackups(): array
|
||||
{
|
||||
$backupsDir = storage_path('app/core_backups');
|
||||
|
||||
if (! File::isDirectory($backupsDir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$backups = [];
|
||||
foreach (File::directories($backupsDir) as $dir) {
|
||||
$backups[] = [
|
||||
'path' => $dir,
|
||||
'name' => basename($dir),
|
||||
'created_at' => date('Y-m-d H:i:s', filectime($dir)),
|
||||
];
|
||||
}
|
||||
|
||||
return $backups;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* 확장 백업/복원 헬퍼
|
||||
*
|
||||
* 업데이트 시 롤백을 위한 백업 생성/복원/삭제 기능을 제공합니다.
|
||||
* 백업 위치: storage/app/extension_backups/{type}/{identifier}_{timestamp}/
|
||||
*/
|
||||
class ExtensionBackupHelper
|
||||
{
|
||||
/**
|
||||
* 확장 디렉토리를 백업합니다.
|
||||
*
|
||||
* @param string $type 확장 타입 ('modules', 'plugins', 'templates')
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return string 백업 경로
|
||||
*
|
||||
* @throws \RuntimeException 소스 디렉토리가 없거나 복사 실패 시
|
||||
*/
|
||||
public static function createBackup(string $type, string $identifier, ?\Closure $onProgress = null): string
|
||||
{
|
||||
$sourcePath = base_path("{$type}/{$identifier}");
|
||||
|
||||
if (! File::isDirectory($sourcePath)) {
|
||||
throw new \RuntimeException(
|
||||
"Backup source directory does not exist: {$sourcePath}"
|
||||
);
|
||||
}
|
||||
|
||||
$timestamp = date('Ymd_His');
|
||||
$backupPath = storage_path("app/extension_backups/{$type}/{$identifier}_{$timestamp}");
|
||||
|
||||
File::ensureDirectoryExists(dirname($backupPath));
|
||||
|
||||
// 파일별 복사로 진행 상세 보고
|
||||
self::copyDirectoryWithProgress($sourcePath, $backupPath, $sourcePath, $onProgress);
|
||||
|
||||
return $backupPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리를 파일별로 복사하며 진행 콜백에 개별 파일을 보고합니다.
|
||||
*
|
||||
* @param string $source 소스 디렉토리
|
||||
* @param string $dest 대상 디렉토리
|
||||
* @param string $basePath 상대 경로 계산 기준
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
*/
|
||||
private static function copyDirectoryWithProgress(
|
||||
string $source,
|
||||
string $dest,
|
||||
string $basePath,
|
||||
?\Closure $onProgress = null
|
||||
): void {
|
||||
File::ensureDirectoryExists($dest, 0775);
|
||||
$items = new \FilesystemIterator($source, \FilesystemIterator::SKIP_DOTS);
|
||||
|
||||
foreach ($items as $item) {
|
||||
// 제외 대상 디렉토리는 건너뛰기 (PendingHelper와 동일 목록)
|
||||
if ($item->isDir() && in_array($item->getBasename(), ExtensionPendingHelper::EXCLUDED_DIRECTORIES, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$target = $dest.DIRECTORY_SEPARATOR.$item->getBasename();
|
||||
$relativePath = ltrim(str_replace($basePath, '', $item->getPathname()), '/\\');
|
||||
|
||||
if ($item->isDir()) {
|
||||
self::copyDirectoryWithProgress($item->getPathname(), $target, $basePath, $onProgress);
|
||||
} else {
|
||||
$onProgress?->__invoke(null, $relativePath);
|
||||
FilePermissionHelper::copyFile($item->getPathname(), $target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 백업으로부터 확장 디렉토리를 복원합니다.
|
||||
*
|
||||
* ExtensionPendingHelper::copyToActive()의 원자적 교체 패턴을 사용합니다.
|
||||
*
|
||||
* @param string $type 확장 타입 ('modules', 'plugins', 'templates')
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $backupPath 백업 경로
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
*
|
||||
* @throws \RuntimeException 백업 디렉토리가 없을 때
|
||||
*
|
||||
* @see ExtensionPendingHelper::copyToActive() 원자적 디렉토리 교체 로직
|
||||
*/
|
||||
public static function restoreFromBackup(string $type, string $identifier, string $backupPath, ?\Closure $onProgress = null): void
|
||||
{
|
||||
if (! File::isDirectory($backupPath)) {
|
||||
throw new \RuntimeException(
|
||||
"Backup directory does not exist: {$backupPath}"
|
||||
);
|
||||
}
|
||||
|
||||
$targetPath = base_path("{$type}/{$identifier}");
|
||||
|
||||
// 원자적 복원: ExtensionPendingHelper의 안전한 교체 로직 사용
|
||||
ExtensionPendingHelper::copyToActive($backupPath, $targetPath, $onProgress);
|
||||
}
|
||||
|
||||
/**
|
||||
* 백업 디렉토리를 삭제합니다.
|
||||
*
|
||||
* @param string $backupPath 백업 경로
|
||||
*/
|
||||
public static function deleteBackup(string $backupPath): void
|
||||
{
|
||||
if (File::isDirectory($backupPath)) {
|
||||
File::deleteDirectory($backupPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use App\Contracts\Repositories\MenuRepositoryInterface;
|
||||
use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\MenuPermissionType;
|
||||
use App\Models\Menu;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 확장 메뉴 동기화 헬퍼
|
||||
*
|
||||
* 확장(모듈/플러그인) 설치/업데이트 시 사용자 커스터마이징을 보존하면서
|
||||
* 메뉴를 안전하게 동기화합니다.
|
||||
*
|
||||
* user_overrides 컬럼에서 유저가 수정한 필드명 목록을 읽어,
|
||||
* 해당 필드는 건너뛰고 나머지만 갱신합니다.
|
||||
* parent_id와 is_active는 항상 확장 정의값으로 업데이트됩니다.
|
||||
*/
|
||||
class ExtensionMenuSyncHelper
|
||||
{
|
||||
/**
|
||||
* @param MenuRepositoryInterface $menuRepository 메뉴 저장소
|
||||
* @param RoleRepositoryInterface $roleRepository 역할 저장소
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly MenuRepositoryInterface $menuRepository,
|
||||
private readonly RoleRepositoryInterface $roleRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 메뉴를 동기화합니다.
|
||||
*
|
||||
* 신규: 생성 (user_overrides 없음)
|
||||
* 기존: user_overrides에 없는 필드만 업데이트
|
||||
*
|
||||
* @param string $slug 메뉴 슬러그
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param array $newAttributes 새 메뉴 속성 (name, icon, order, url)
|
||||
* @param int|null $parentId 부모 메뉴 ID
|
||||
* @return Menu 동기화된 메뉴 모델
|
||||
*/
|
||||
public function syncMenu(
|
||||
string $slug,
|
||||
ExtensionOwnerType $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $newAttributes,
|
||||
?int $parentId = null,
|
||||
): Menu {
|
||||
$existing = $this->menuRepository->findBySlugAndExtension($slug, $extensionType, $extensionIdentifier);
|
||||
|
||||
if (! $existing) {
|
||||
// 신규 생성
|
||||
$menu = $this->menuRepository->updateOrCreate(
|
||||
[
|
||||
'slug' => $slug,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
],
|
||||
[
|
||||
'name' => $newAttributes['name'] ?? [],
|
||||
'url' => $newAttributes['url'] ?? null,
|
||||
'icon' => $newAttributes['icon'] ?? null,
|
||||
'order' => $newAttributes['order'] ?? 0,
|
||||
'parent_id' => $parentId,
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
// 관리자 역할 + 설치자 역할 자동 부여
|
||||
$this->grantDefaultRoles($menu);
|
||||
|
||||
return $menu;
|
||||
}
|
||||
|
||||
// 기존 메뉴 업데이트: user_overrides에 없는 필드만 갱신
|
||||
$userOverrides = $existing->user_overrides ?? [];
|
||||
|
||||
$updateData = [
|
||||
'parent_id' => $parentId,
|
||||
'is_active' => true,
|
||||
];
|
||||
|
||||
if (! in_array('name', $userOverrides, true)) {
|
||||
$updateData['name'] = $newAttributes['name'] ?? [];
|
||||
}
|
||||
|
||||
if (! in_array('icon', $userOverrides, true)) {
|
||||
$updateData['icon'] = $newAttributes['icon'] ?? null;
|
||||
}
|
||||
|
||||
if (! in_array('order', $userOverrides, true)) {
|
||||
$updateData['order'] = $newAttributes['order'] ?? 0;
|
||||
}
|
||||
|
||||
if (! in_array('url', $userOverrides, true)) {
|
||||
$updateData['url'] = $newAttributes['url'] ?? null;
|
||||
}
|
||||
|
||||
$this->menuRepository->update($existing, $updateData);
|
||||
|
||||
return $existing->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 메뉴 데이터를 재귀적으로 동기화합니다.
|
||||
*
|
||||
* createMenuRecursive()의 대체 메서드.
|
||||
* 다국어 name 역호환 처리 포함.
|
||||
*
|
||||
* @param array $menuData 메뉴 데이터 (slug, name, icon, order, url, children)
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param int|null $parentId 부모 메뉴 ID
|
||||
* @return Menu 동기화된 메뉴 모델
|
||||
*/
|
||||
public function syncMenuRecursive(
|
||||
array $menuData,
|
||||
ExtensionOwnerType $extensionType,
|
||||
string $extensionIdentifier,
|
||||
?int $parentId = null,
|
||||
): Menu {
|
||||
// 역호환성: 문자열 name을 다국어 배열로 변환
|
||||
$name = $menuData['name'];
|
||||
if (is_string($name)) {
|
||||
$locales = config('app.translatable_locales', ['ko', 'en']);
|
||||
$nameArray = [];
|
||||
foreach ($locales as $locale) {
|
||||
$nameArray[$locale] = $name;
|
||||
}
|
||||
$name = $nameArray;
|
||||
}
|
||||
|
||||
// slug는 문자열이어야 하므로 배열인 경우 첫 번째 값 사용
|
||||
$slug = $menuData['slug'] ?? (is_array($name) ? array_values($name)[0] : $name);
|
||||
|
||||
$menu = $this->syncMenu(
|
||||
slug: $slug,
|
||||
extensionType: $extensionType,
|
||||
extensionIdentifier: $extensionIdentifier,
|
||||
newAttributes: [
|
||||
'name' => $name,
|
||||
'icon' => $menuData['icon'] ?? null,
|
||||
'order' => $menuData['order'] ?? 0,
|
||||
'url' => $menuData['url'] ?? null,
|
||||
],
|
||||
parentId: $parentId,
|
||||
);
|
||||
|
||||
// 하위 메뉴가 있는 경우 재귀 처리
|
||||
if (isset($menuData['children']) && is_array($menuData['children'])) {
|
||||
foreach ($menuData['children'] as $childMenuData) {
|
||||
$this->syncMenuRecursive($childMenuData, $extensionType, $extensionIdentifier, $menu->id);
|
||||
}
|
||||
}
|
||||
|
||||
return $menu;
|
||||
}
|
||||
|
||||
/**
|
||||
* 신규 메뉴에 관리자 역할과 현재 사용자(설치자) 역할을 자동 부여합니다.
|
||||
*
|
||||
* @param Menu $menu 생성된 메뉴
|
||||
*/
|
||||
private function grantDefaultRoles(Menu $menu): void
|
||||
{
|
||||
try {
|
||||
$roleIds = [];
|
||||
|
||||
// 관리자 역할
|
||||
$adminRole = $this->roleRepository->findByIdentifier('admin');
|
||||
if ($adminRole) {
|
||||
$roleIds[] = $adminRole->id;
|
||||
}
|
||||
|
||||
// 현재 인증된 사용자(설치자)의 역할
|
||||
$currentUser = Auth::user();
|
||||
if ($currentUser) {
|
||||
$userRoleIds = $currentUser->roles()->pluck('roles.id')->toArray();
|
||||
foreach ($userRoleIds as $userRoleId) {
|
||||
if (! in_array($userRoleId, $roleIds)) {
|
||||
$roleIds[] = $userRoleId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 역할 권한 부여
|
||||
foreach ($roleIds as $roleId) {
|
||||
$menu->roles()->syncWithoutDetaching([
|
||||
$roleId => ['permission_type' => MenuPermissionType::Read->value],
|
||||
]);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('메뉴 기본 역할 부여 실패', [
|
||||
'menu_id' => $menu->id ?? null,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 확장에 속하지 않는 stale 메뉴를 정리합니다.
|
||||
*
|
||||
* ⚠️ 주의: 이 메서드는 정적 정의(getAdminMenus()) 기반으로만 판단하므로,
|
||||
* 확장이 런타임에 동적으로 생성한 메뉴도 삭제됩니다.
|
||||
* 자동 호출은 폐기되었으며, 필요 시 UpgradeStep에서 명시적으로 호출하세요.
|
||||
*
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param array $currentSlugs 현재 유효한 메뉴 슬러그 목록
|
||||
* @return int 삭제된 메뉴 수
|
||||
*
|
||||
* @see \App\Contracts\Extension\UpgradeStepInterface
|
||||
*/
|
||||
public function cleanupStaleMenus(
|
||||
ExtensionOwnerType $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $currentSlugs,
|
||||
): int {
|
||||
$existingMenus = $this->menuRepository->getMenusByExtension($extensionType, $extensionIdentifier);
|
||||
|
||||
$deleted = 0;
|
||||
foreach ($existingMenus as $menu) {
|
||||
if (! in_array($menu->slug, $currentSlugs, true)) {
|
||||
// role_menus 피벗 정리
|
||||
$menu->roles()->detach();
|
||||
|
||||
// 자식 메뉴 먼저 삭제
|
||||
foreach ($menu->children as $child) {
|
||||
$child->roles()->detach();
|
||||
$this->menuRepository->delete($child);
|
||||
$deleted++;
|
||||
}
|
||||
|
||||
$this->menuRepository->delete($menu);
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($deleted > 0) {
|
||||
Log::info('stale 메뉴 정리 완료', [
|
||||
'extension_type' => $extensionType->value,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'deleted' => $deleted,
|
||||
]);
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 메뉴 정의 배열에서 모든 slug를 재귀적으로 수집합니다.
|
||||
*
|
||||
* @param array $menuDataArray 메뉴 정의 배열
|
||||
* @return array slug 배열
|
||||
*/
|
||||
public function collectSlugsRecursive(array $menuDataArray): array
|
||||
{
|
||||
$slugs = [];
|
||||
foreach ($menuDataArray as $menuData) {
|
||||
$name = $menuData['name'] ?? '';
|
||||
if (is_string($name)) {
|
||||
$locales = config('app.translatable_locales', ['ko', 'en']);
|
||||
$nameArray = [];
|
||||
foreach ($locales as $locale) {
|
||||
$nameArray[$locale] = $name;
|
||||
}
|
||||
$name = $nameArray;
|
||||
}
|
||||
|
||||
$slug = $menuData['slug'] ?? (is_array($name) ? array_values($name)[0] : $name);
|
||||
$slugs[] = $slug;
|
||||
|
||||
if (isset($menuData['children']) && is_array($menuData['children'])) {
|
||||
$slugs = array_merge($slugs, $this->collectSlugsRecursive($menuData['children']));
|
||||
}
|
||||
}
|
||||
|
||||
return $slugs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 확장 _pending / _bundled 디렉토리 유틸리티
|
||||
*
|
||||
* _pending 및 _bundled 디렉토리의 확장 스캔, 복사, 삭제 등의 공통 로직을 제공합니다.
|
||||
*/
|
||||
class ExtensionPendingHelper
|
||||
{
|
||||
/**
|
||||
* 복사에서 제외할 디렉토리명 목록
|
||||
*
|
||||
* 빌드/테스트용 디렉토리는 _bundled에서만 사용되므로 활성 디렉토리에 불필요합니다.
|
||||
*/
|
||||
public const EXCLUDED_DIRECTORIES = [
|
||||
'node_modules',
|
||||
];
|
||||
|
||||
/**
|
||||
* _pending 또는 _bundled 디렉토리에서 확장 메타데이터를 로드합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로 (예: base_path('modules'))
|
||||
* @param string $subDir 하위 디렉토리명 ('_pending' 또는 '_bundled')
|
||||
* @param string $manifestName manifest 파일명 ('module.json', 'plugin.json', 'template.json')
|
||||
* @return array 확장 메타데이터 배열 (identifier 기준 키)
|
||||
*/
|
||||
public static function loadExtensions(string $basePath, string $subDir, string $manifestName): array
|
||||
{
|
||||
$scanPath = $basePath.DIRECTORY_SEPARATOR.$subDir;
|
||||
|
||||
if (! File::isDirectory($scanPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$dirs = File::directories($scanPath);
|
||||
|
||||
foreach ($dirs as $dir) {
|
||||
$manifestPath = $dir.DIRECTORY_SEPARATOR.$manifestName;
|
||||
|
||||
if (! File::exists($manifestPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$content = File::get($manifestPath);
|
||||
$data = json_decode($content, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$dirName = basename($dir);
|
||||
$identifier = $data['identifier'] ?? $dirName;
|
||||
|
||||
$result[$identifier] = array_merge($data, [
|
||||
'identifier' => $identifier,
|
||||
'directory' => $dirName,
|
||||
'source_path' => $dir,
|
||||
]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* _pending 디렉토리의 확장 메타데이터를 로드합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로 (예: base_path('modules'))
|
||||
* @param string $manifestName manifest 파일명
|
||||
* @return array 확장 메타데이터 배열
|
||||
*/
|
||||
public static function loadPendingExtensions(string $basePath, string $manifestName): array
|
||||
{
|
||||
return self::loadExtensions($basePath, '_pending', $manifestName);
|
||||
}
|
||||
|
||||
/**
|
||||
* _bundled 디렉토리의 확장 메타데이터를 로드합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로 (예: base_path('modules'))
|
||||
* @param string $manifestName manifest 파일명
|
||||
* @return array 확장 메타데이터 배열
|
||||
*/
|
||||
public static function loadBundledExtensions(string $basePath, string $manifestName): array
|
||||
{
|
||||
return self::loadExtensions($basePath, '_bundled', $manifestName);
|
||||
}
|
||||
|
||||
/**
|
||||
* _pending 또는 _bundled에서 활성 디렉토리로 확장을 복사합니다.
|
||||
*
|
||||
* 원자적 교체 패턴을 사용하여 복사 실패 시에도 기존 디렉토리를 보존합니다.
|
||||
* (1) 임시 경로에 소스 복사 → (2) 기존 삭제 → (3) 임시를 이동
|
||||
* 1단계 실패 시 기존 디렉토리가 온전히 보존됩니다.
|
||||
*
|
||||
* 이 메서드는 ExtensionBackupHelper::restoreFromBackup() 및
|
||||
* ModuleManager/PluginManager/TemplateManager의 downloadXxxUpdate()에서도
|
||||
* 공통 디렉토리 교체 로직으로 사용됩니다.
|
||||
*
|
||||
* @param string $sourcePath 소스 경로 (예: modules/_pending/sirsoft-board)
|
||||
* @param string $targetPath 대상 경로 (예: modules/sirsoft-board)
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
*
|
||||
* @throws \RuntimeException 소스가 존재하지 않을 때
|
||||
*
|
||||
* @see ExtensionPendingHelperTest File Facade Spy 패턴으로 복사 실패 테스트
|
||||
* @see ProtectsExtensionDirectories 확장 활성 디렉토리 보호 trait
|
||||
*/
|
||||
public static function copyToActive(string $sourcePath, string $targetPath, ?\Closure $onProgress = null): void
|
||||
{
|
||||
if (! File::isDirectory($sourcePath)) {
|
||||
throw new \RuntimeException(
|
||||
"Source directory does not exist: {$sourcePath}"
|
||||
);
|
||||
}
|
||||
|
||||
// 기존 대상 디렉토리가 없으면 바로 복사
|
||||
if (! File::isDirectory($targetPath)) {
|
||||
self::copyDirectoryWithProgress($sourcePath, $targetPath, $sourcePath, $onProgress);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 원자적 교체: 임시 경로에 복사 → 기존을 rename → 임시를 rename → 기존 삭제
|
||||
// Windows에서 deleteDirectory 직후 같은 이름으로 rename이 실패하는
|
||||
// 타이밍 이슈를 회피하기 위해 rename→rename→delete 패턴을 사용합니다.
|
||||
// 임시 디렉토리를 _pending/ 하위에 생성하여 오토로드 오염 방지
|
||||
$basePath = dirname($targetPath);
|
||||
$pendingPath = $basePath.DIRECTORY_SEPARATOR.'_pending';
|
||||
File::ensureDirectoryExists($pendingPath, 0775);
|
||||
|
||||
$identifier = basename($targetPath);
|
||||
$tempPath = $pendingPath.DIRECTORY_SEPARATOR.$identifier.'_updating_'.uniqid();
|
||||
$oldPath = $pendingPath.DIRECTORY_SEPARATOR.$identifier.'_old_'.uniqid();
|
||||
|
||||
try {
|
||||
self::copyDirectoryWithProgress($sourcePath, $tempPath, $sourcePath, $onProgress);
|
||||
} catch (\Exception $e) {
|
||||
// 복사 실패 시 임시 디렉토리 정리 후 예외 전파
|
||||
if (File::isDirectory($tempPath)) {
|
||||
File::deleteDirectory($tempPath);
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
|
||||
// 기존 → _old 이동 (rename, Windows NTFS 타이밍 이슈 대응 재시도)
|
||||
if (! self::retryMoveDirectory($targetPath, $oldPath)) {
|
||||
// 파일 잠금 감지 및 해제 시도
|
||||
if (self::tryReleaseLocks($targetPath, $onProgress)) {
|
||||
// 잠금 해제 후 재시도
|
||||
if (! self::retryMoveDirectory($targetPath, $oldPath)) {
|
||||
File::deleteDirectory($tempPath);
|
||||
throw new \RuntimeException(
|
||||
"Failed to move existing directory: {$targetPath} → {$oldPath}"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
File::deleteDirectory($tempPath);
|
||||
throw new \RuntimeException(
|
||||
"Failed to move existing directory: {$targetPath} → {$oldPath}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 임시 → 활성 이동 (rename, Windows NTFS 타이밍 이슈 대응 재시도)
|
||||
if (! self::retryMoveDirectory($tempPath, $targetPath)) {
|
||||
// 롤백: _old를 원래 위치로 복원
|
||||
File::moveDirectory($oldPath, $targetPath);
|
||||
throw new \RuntimeException(
|
||||
"Failed to move directory: {$tempPath} → {$targetPath}"
|
||||
);
|
||||
}
|
||||
|
||||
// 교체 완료 후 _old 삭제 (실패해도 무해)
|
||||
File::deleteDirectory($oldPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 디렉토리의 vendor/를 스테이징 디렉토리로 복사합니다.
|
||||
*
|
||||
* composer install을 스킵할 때, 스테이징에 vendor/가 없으므로
|
||||
* copyToActive() 원자적 교체 전에 기존 vendor/를 보존합니다.
|
||||
*
|
||||
* @param string $activePath 활성 디렉토리 (vendor/ 소스)
|
||||
* @param string $stagingPath 스테이징 디렉토리 (vendor/ 복사 대상)
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
*/
|
||||
public static function copyVendorFromActive(string $activePath, string $stagingPath, ?\Closure $onProgress = null): void
|
||||
{
|
||||
$sourceVendor = $activePath.DIRECTORY_SEPARATOR.'vendor';
|
||||
$destVendor = $stagingPath.DIRECTORY_SEPARATOR.'vendor';
|
||||
|
||||
if (! File::isDirectory($sourceVendor)) {
|
||||
Log::info('활성 디렉토리에 vendor/ 없음 — 복사 생략', [
|
||||
'active' => $activePath,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$onProgress?->__invoke(null, 'vendor 디렉토리 복사 중 (기존 유지)...');
|
||||
|
||||
self::copyDirectoryWithProgress($sourceVendor, $destVendor, $sourceVendor, $onProgress);
|
||||
|
||||
Log::info('활성 vendor/ → 스테이징 복사 완료', [
|
||||
'source' => $sourceVendor,
|
||||
'dest' => $destVendor,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 잠금을 감지하고 해제를 시도합니다.
|
||||
*
|
||||
* Windows에서 다른 프로세스(IDE 등)가 파일 핸들을 보유하고 있을 때,
|
||||
* 해당 프로세스를 감지하고 종료하여 디렉토리 이동이 가능하도록 합니다.
|
||||
* 프로그레스바와 별개로 STDERR에 직접 출력하여 메시지가 덮어씌워지지 않습니다.
|
||||
*
|
||||
* @param string $directoryPath 잠금 해제할 디렉토리 경로
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @return bool 잠금 해제 성공 여부
|
||||
*/
|
||||
private static function tryReleaseLocks(string $directoryPath, ?\Closure $onProgress = null): bool
|
||||
{
|
||||
if (! FileHandleHelper::isWindows()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 프로그레스바에 의해 메시지가 덮어씌워지지 않도록 STDERR에 직접 출력
|
||||
$stderr = fopen('php://stderr', 'w');
|
||||
$outputCallback = function (string $message) use ($stderr) {
|
||||
if ($stderr) {
|
||||
fwrite($stderr, $message.PHP_EOL);
|
||||
}
|
||||
Log::info($message, ['context' => 'file_lock_release']);
|
||||
};
|
||||
|
||||
$result = FileHandleHelper::releaseLocks($directoryPath, $outputCallback);
|
||||
|
||||
if ($stderr) {
|
||||
fclose($stderr);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리 이동을 재시도합니다 (Windows NTFS 타이밍 이슈 대응).
|
||||
*
|
||||
* Windows에서 rename(A→B) 직후 rename(C→A) 시도 시,
|
||||
* NTFS가 경로 A를 완전히 해제하지 않아 실패할 수 있습니다.
|
||||
* 최대 3회까지 200ms 간격으로 재시도합니다.
|
||||
*
|
||||
* @param string $from 소스 경로
|
||||
* @param string $to 대상 경로
|
||||
* @return bool 이동 성공 여부
|
||||
*/
|
||||
private static function retryMoveDirectory(string $from, string $to): bool
|
||||
{
|
||||
for ($attempt = 0; $attempt < 3; $attempt++) {
|
||||
if ($attempt > 0) {
|
||||
usleep(200_000); // 200ms 대기
|
||||
}
|
||||
|
||||
if (File::moveDirectory($from, $to)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리를 파일별로 복사하며 진행 콜백에 개별 파일을 보고합니다.
|
||||
*
|
||||
* @param string $source 소스 디렉토리
|
||||
* @param string $dest 대상 디렉토리
|
||||
* @param string $basePath 상대 경로 계산 기준
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
*/
|
||||
private static function copyDirectoryWithProgress(
|
||||
string $source,
|
||||
string $dest,
|
||||
string $basePath,
|
||||
?\Closure $onProgress = null
|
||||
): void {
|
||||
File::ensureDirectoryExists($dest, 0775);
|
||||
$items = new \FilesystemIterator($source, \FilesystemIterator::SKIP_DOTS);
|
||||
|
||||
foreach ($items as $item) {
|
||||
// 제외 대상 디렉토리는 건너뛰기
|
||||
if ($item->isDir() && in_array($item->getBasename(), self::EXCLUDED_DIRECTORIES, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$target = $dest.DIRECTORY_SEPARATOR.$item->getBasename();
|
||||
$relativePath = ltrim(str_replace($basePath, '', $item->getPathname()), '/\\');
|
||||
|
||||
if ($item->isDir()) {
|
||||
self::copyDirectoryWithProgress($item->getPathname(), $target, $basePath, $onProgress);
|
||||
} else {
|
||||
$onProgress?->__invoke(null, $relativePath);
|
||||
FilePermissionHelper::copyFile($item->getPathname(), $target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 디렉토리를 삭제합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로
|
||||
* @param string $identifier 확장 식별자
|
||||
*/
|
||||
public static function deleteExtensionDirectory(string $basePath, string $identifier): void
|
||||
{
|
||||
$targetPath = $basePath.DIRECTORY_SEPARATOR.$identifier;
|
||||
|
||||
if (File::isDirectory($targetPath)) {
|
||||
File::deleteDirectory($targetPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* _pending 디렉토리에 해당 확장이 존재하는지 확인합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로
|
||||
* @param string $identifier 확장 식별자
|
||||
*/
|
||||
public static function isPending(string $basePath, string $identifier): bool
|
||||
{
|
||||
return File::isDirectory(self::getPendingPath($basePath, $identifier));
|
||||
}
|
||||
|
||||
/**
|
||||
* _bundled 디렉토리에 해당 확장이 존재하는지 확인합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로
|
||||
* @param string $identifier 확장 식별자
|
||||
*/
|
||||
public static function isBundled(string $basePath, string $identifier): bool
|
||||
{
|
||||
return File::isDirectory(self::getBundledPath($basePath, $identifier));
|
||||
}
|
||||
|
||||
/**
|
||||
* _pending 경로를 반환합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로
|
||||
* @param string $identifier 확장 식별자
|
||||
*/
|
||||
public static function getPendingPath(string $basePath, string $identifier): string
|
||||
{
|
||||
return $basePath.DIRECTORY_SEPARATOR.'_pending'.DIRECTORY_SEPARATOR.$identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* _bundled 경로를 반환합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로
|
||||
* @param string $identifier 확장 식별자
|
||||
*/
|
||||
public static function getBundledPath(string $basePath, string $identifier): string
|
||||
{
|
||||
return $basePath.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.$identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 업데이트 스테이징용 타임스탬프 디렉토리를 생성합니다.
|
||||
*
|
||||
* `{basePath}/_pending/{identifier}_{Ymd_His}/` 형식의 격리된 디렉토리를 생성하여
|
||||
* 동시 실행 충돌을 방지합니다.
|
||||
*
|
||||
* @param string $basePath 확장 타입의 기본 경로 (예: base_path('modules'))
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return string 생성된 스테이징 경로
|
||||
*/
|
||||
public static function createUpdateStagingPath(string $basePath, string $identifier): string
|
||||
{
|
||||
$timestamp = date('Ymd_His');
|
||||
$stagingPath = $basePath.DIRECTORY_SEPARATOR.'_pending'.DIRECTORY_SEPARATOR.$identifier.'_'.$timestamp;
|
||||
|
||||
File::ensureDirectoryExists($stagingPath, 0775, true);
|
||||
|
||||
return $stagingPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 소스를 스테이징 디렉토리로 복사합니다.
|
||||
*
|
||||
* FilePermissionHelper를 사용하여 퍼미션/소유자/소유그룹을 보존합니다.
|
||||
*
|
||||
* @param string $sourcePath 소스 경로
|
||||
* @param string $stagingPath 스테이징 경로
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return void
|
||||
*
|
||||
* @throws \RuntimeException 소스가 존재하지 않을 때
|
||||
*/
|
||||
public static function stageForUpdate(string $sourcePath, string $stagingPath, ?\Closure $onProgress = null): void
|
||||
{
|
||||
if (! File::isDirectory($sourcePath)) {
|
||||
throw new \RuntimeException(
|
||||
"Source directory does not exist: {$sourcePath}"
|
||||
);
|
||||
}
|
||||
|
||||
self::copyDirectoryWithProgress($sourcePath, $stagingPath, $sourcePath, $onProgress);
|
||||
}
|
||||
|
||||
/**
|
||||
* 스테이징 디렉토리를 정리합니다.
|
||||
*
|
||||
* Windows 환경에서 File::deleteDirectory() 호출 후에도
|
||||
* 파일 핸들 해제 지연으로 빈 디렉토리가 남을 수 있습니다.
|
||||
* 이를 방지하기 위해 삭제 후 디렉토리가 잔존하면 재시도합니다.
|
||||
*
|
||||
* @param string $stagingPath 스테이징 경로
|
||||
* @return void
|
||||
*/
|
||||
public static function cleanupStaging(string $stagingPath): void
|
||||
{
|
||||
if (! File::isDirectory($stagingPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
File::deleteDirectory($stagingPath);
|
||||
|
||||
// Windows: 파일 핸들 해제 지연으로 빈 디렉토리 잔존 시 재시도
|
||||
if (File::isDirectory($stagingPath)) {
|
||||
usleep(100_000); // 100ms 대기
|
||||
File::deleteDirectory($stagingPath);
|
||||
}
|
||||
|
||||
// 최종 시도: 재귀적으로 빈 디렉토리만 제거
|
||||
if (File::isDirectory($stagingPath)) {
|
||||
usleep(200_000); // 200ms 추가 대기
|
||||
self::removeEmptyDirectories($stagingPath);
|
||||
@rmdir($stagingPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 디렉토리를 재귀적으로 제거합니다.
|
||||
*
|
||||
* @param string $path 대상 경로
|
||||
* @return bool 디렉토리가 비어있어 삭제되었으면 true
|
||||
*/
|
||||
private static function removeEmptyDirectories(string $path): bool
|
||||
{
|
||||
if (! is_dir($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$items = scandir($path);
|
||||
if ($items === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$isEmpty = true;
|
||||
foreach ($items as $item) {
|
||||
if ($item === '.' || $item === '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fullPath = $path.DIRECTORY_SEPARATOR.$item;
|
||||
if (is_dir($fullPath)) {
|
||||
if (! self::removeEmptyDirectories($fullPath)) {
|
||||
$isEmpty = false;
|
||||
}
|
||||
} else {
|
||||
$isEmpty = false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($isEmpty) {
|
||||
@rmdir($path);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use App\Contracts\Repositories\PermissionRepositoryInterface;
|
||||
use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 확장 역할/권한 동기화 헬퍼
|
||||
*
|
||||
* 확장(모듈/플러그인) 설치/업데이트 시 사용자 커스터마이징을 보존하면서
|
||||
* 역할/권한을 안전하게 동기화합니다.
|
||||
*
|
||||
* user_overrides 컬럼에서 유저가 수정한 필드명 목록을 읽어,
|
||||
* 해당 필드는 건너뛰고 나머지만 갱신합니다.
|
||||
*/
|
||||
class ExtensionRoleSyncHelper
|
||||
{
|
||||
/**
|
||||
* @param RoleRepositoryInterface $roleRepository 역할 저장소
|
||||
* @param PermissionRepositoryInterface $permissionRepository 권한 저장소
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly RoleRepositoryInterface $roleRepository,
|
||||
private readonly PermissionRepositoryInterface $permissionRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 역할을 동기화합니다.
|
||||
*
|
||||
* 신규: 생성 (user_overrides 없음)
|
||||
* 기존: user_overrides에 없는 필드만 업데이트
|
||||
*
|
||||
* @param string $identifier 역할 식별자
|
||||
* @param array $newDescription 새 역할 설명 (다국어 배열)
|
||||
* @param array $newName 새 역할 이름 (다국어 배열)
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param array $otherAttributes 기타 속성 (is_active 등)
|
||||
* @return Role 동기화된 역할 모델
|
||||
*/
|
||||
public function syncRole(
|
||||
string $identifier,
|
||||
array $newDescription,
|
||||
array $newName,
|
||||
ExtensionOwnerType $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $otherAttributes = [],
|
||||
): Role {
|
||||
$existing = $this->roleRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $existing) {
|
||||
// 신규 생성
|
||||
return $this->roleRepository->updateOrCreate(
|
||||
['identifier' => $identifier],
|
||||
array_merge([
|
||||
'name' => $newName,
|
||||
'description' => $newDescription,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'is_active' => true,
|
||||
], $otherAttributes)
|
||||
);
|
||||
}
|
||||
|
||||
// 기존 역할 업데이트: user_overrides에 없는 필드만 갱신
|
||||
$userOverrides = $existing->user_overrides ?? [];
|
||||
|
||||
$updateData = [
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
];
|
||||
|
||||
if (! in_array('name', $userOverrides, true)) {
|
||||
$updateData['name'] = $newName;
|
||||
}
|
||||
|
||||
if (! in_array('description', $userOverrides, true)) {
|
||||
$updateData['description'] = $newDescription;
|
||||
}
|
||||
|
||||
// 기타 속성 병합
|
||||
$updateData = array_merge($updateData, $otherAttributes);
|
||||
|
||||
$this->roleRepository->update($existing, $updateData);
|
||||
|
||||
return $existing->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한을 동기화합니다.
|
||||
*
|
||||
* Permission은 유저가 수정할 수 없는 테이블이므로 항상 확장 정의값으로 덮어씁니다.
|
||||
*
|
||||
* @param string $identifier 권한 식별자
|
||||
* @param array $newName 새 권한 이름 (다국어 배열)
|
||||
* @param array $newDescription 새 권한 설명 (다국어 배열)
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param array $otherAttributes 기타 속성 (type, order, parent_id 등)
|
||||
* @return Permission 동기화된 권한 모델
|
||||
*/
|
||||
public function syncPermission(
|
||||
string $identifier,
|
||||
array $newName,
|
||||
array $newDescription,
|
||||
ExtensionOwnerType $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $otherAttributes = [],
|
||||
): Permission {
|
||||
return $this->permissionRepository->updateOrCreate(
|
||||
['identifier' => $identifier],
|
||||
array_merge([
|
||||
'name' => $newName,
|
||||
'description' => $newDescription,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
], $otherAttributes)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 확장에 속하지 않는 stale 권한을 정리합니다.
|
||||
*
|
||||
* ⚠️ 주의: 이 메서드는 정적 정의(getPermissions()) 기반으로만 판단하므로,
|
||||
* 확장이 런타임에 동적으로 생성한 권한도 삭제됩니다.
|
||||
* 자동 호출은 폐기되었으며, 필요 시 UpgradeStep에서 명시적으로 호출하세요.
|
||||
*
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param array $currentIdentifiers 현재 유효한 권한 식별자 목록
|
||||
* @return int 삭제된 권한 수
|
||||
*
|
||||
* @see \App\Contracts\Extension\UpgradeStepInterface
|
||||
*/
|
||||
public function cleanupStalePermissions(
|
||||
ExtensionOwnerType $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $currentIdentifiers,
|
||||
): int {
|
||||
$existingPermissions = $this->permissionRepository->getByExtension($extensionType, $extensionIdentifier);
|
||||
|
||||
$deleted = 0;
|
||||
foreach ($existingPermissions as $permission) {
|
||||
if (! in_array($permission->identifier, $currentIdentifiers, true)) {
|
||||
// 역할 연결 해제
|
||||
$permission->roles()->detach();
|
||||
// 자식 권한도 정리
|
||||
foreach ($permission->children as $child) {
|
||||
$child->roles()->detach();
|
||||
$this->permissionRepository->delete($child);
|
||||
$deleted++;
|
||||
}
|
||||
$this->permissionRepository->delete($permission);
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($deleted > 0) {
|
||||
Log::info('stale 권한 정리 완료', [
|
||||
'extension_type' => $extensionType->value,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'deleted' => $deleted,
|
||||
]);
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 전체 역할-권한 할당을 일괄 동기화합니다.
|
||||
*
|
||||
* DB 기반 diff: 현재 DB 상태와 확장 정의를 비교하여
|
||||
* 새 권한은 attach, 제거된 권한은 detach합니다.
|
||||
* user_overrides에 기록된 개별 권한 식별자는 보호됩니다.
|
||||
*
|
||||
* @param array $permissionRoleMap 권한→역할 맵 (예: ['board.read' => [['role' => 'admin', 'scope_type' => null], ...]])
|
||||
* @param array $allExtensionPermIdentifiers 이 확장의 모든 권한 식별자 목록
|
||||
*/
|
||||
public function syncAllRoleAssignments(
|
||||
array $permissionRoleMap,
|
||||
array $allExtensionPermIdentifiers,
|
||||
): void {
|
||||
// 역방향 매핑 구축: 역할→권한 맵 (scope_type 포함)
|
||||
$rolePermissionMap = [];
|
||||
foreach ($permissionRoleMap as $permIdentifier => $roleEntries) {
|
||||
foreach ($roleEntries as $roleEntry) {
|
||||
// 하위호환: 문자열이면 scope_type=null
|
||||
if (is_string($roleEntry)) {
|
||||
$roleIdentifier = $roleEntry;
|
||||
$scopeType = null;
|
||||
} else {
|
||||
$roleIdentifier = $roleEntry['role'];
|
||||
$scopeType = $roleEntry['scope_type'] ?? null;
|
||||
}
|
||||
$rolePermissionMap[$roleIdentifier][] = [
|
||||
'identifier' => $permIdentifier,
|
||||
'scope_type' => $scopeType,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// '*' 와일드카드 처리: 모든 활성 역할에 해당 권한 할당
|
||||
$wildcardPermEntries = $rolePermissionMap['*'] ?? [];
|
||||
unset($rolePermissionMap['*']);
|
||||
|
||||
if (! empty($wildcardPermEntries)) {
|
||||
$allRoles = $this->roleRepository->getActiveRoles();
|
||||
foreach ($allRoles as $role) {
|
||||
// 와일드카드 권한과 해당 역할에 명시된 권한을 병합
|
||||
$roleSpecificEntries = $rolePermissionMap[$role->identifier] ?? [];
|
||||
$mergedEntries = array_merge($wildcardPermEntries, $roleSpecificEntries);
|
||||
|
||||
// 중복 제거 (identifier 기준)
|
||||
$seen = [];
|
||||
$uniqueEntries = [];
|
||||
foreach ($mergedEntries as $entry) {
|
||||
if (! isset($seen[$entry['identifier']])) {
|
||||
$seen[$entry['identifier']] = true;
|
||||
$uniqueEntries[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
$this->syncRolePermissions($role, $uniqueEntries, $allExtensionPermIdentifiers);
|
||||
// 이미 처리된 역할은 아래 루프에서 건너뛰도록 제거
|
||||
unset($rolePermissionMap[$role->identifier]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($rolePermissionMap as $roleIdentifier => $definedPermEntries) {
|
||||
$role = $this->roleRepository->findByIdentifier($roleIdentifier);
|
||||
if (! $role) {
|
||||
continue;
|
||||
}
|
||||
$this->syncRolePermissions($role, $definedPermEntries, $allExtensionPermIdentifiers);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 역할의 확장 권한 할당을 동기화합니다.
|
||||
*
|
||||
* user_overrides에 기록된 개별 권한 식별자는 보호하고,
|
||||
* 나머지 권한만 DB 기반 diff로 attach/detach합니다.
|
||||
*
|
||||
* @param Role $role 대상 역할
|
||||
* @param array $definedPermEntries 이 확장이 이 역할에 정의한 권한 목록 [['identifier' => ..., 'scope_type' => ...], ...]
|
||||
* @param array $allExtensionPermIdentifiers 이 확장의 모든 권한 식별자 목록
|
||||
*/
|
||||
private function syncRolePermissions(
|
||||
Role $role,
|
||||
array $definedPermEntries,
|
||||
array $allExtensionPermIdentifiers,
|
||||
): void {
|
||||
$userOverrides = $role->user_overrides ?? [];
|
||||
|
||||
// 정의된 권한 식별자 목록 및 scope_type 맵 구축
|
||||
$definedPermIdentifiers = array_map(fn ($e) => $e['identifier'], $definedPermEntries);
|
||||
$scopeTypeMap = [];
|
||||
foreach ($definedPermEntries as $entry) {
|
||||
$scopeTypeMap[$entry['identifier']] = $entry['scope_type'];
|
||||
}
|
||||
|
||||
// DB에서 이 역할이 현재 갖고 있는 이 확장의 권한 목록
|
||||
$currentExtPermIds = $role->permissions()
|
||||
->whereIn('identifier', $allExtensionPermIdentifiers)
|
||||
->pluck('identifier')
|
||||
->toArray();
|
||||
|
||||
// user_overrides에 기록된 권한 식별자 필터링 (필드명 "name", "description" 등 제외)
|
||||
$protectedPermissions = array_intersect($userOverrides, $allExtensionPermIdentifiers);
|
||||
|
||||
// 보호된 권한을 제외하고 diff 계산
|
||||
$unprotectedDefined = array_diff($definedPermIdentifiers, $protectedPermissions);
|
||||
$unprotectedCurrent = array_diff($currentExtPermIds, $protectedPermissions);
|
||||
|
||||
// 새 권한: 보호되지 않은 정의 중 현재 DB에 없는 것 → attach (scope_type 포함)
|
||||
$toAttach = array_diff($unprotectedDefined, $currentExtPermIds);
|
||||
foreach ($toAttach as $permIdentifier) {
|
||||
$permission = $this->permissionRepository->findByIdentifier($permIdentifier);
|
||||
if ($permission) {
|
||||
$this->roleRepository->attachPermission($role, $permission->id, [
|
||||
'scope_type' => $scopeTypeMap[$permIdentifier] ?? null,
|
||||
'granted_at' => now(),
|
||||
'granted_by' => Auth::id(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// 제거된 권한: 보호되지 않은 현재 DB 중 정의에 없는 것 → detach
|
||||
$toDetach = array_diff($unprotectedCurrent, $unprotectedDefined);
|
||||
foreach ($toDetach as $permIdentifier) {
|
||||
$permission = $this->permissionRepository->findByIdentifier($permIdentifier);
|
||||
if ($permission) {
|
||||
$this->roleRepository->detachPermission($role, $permission->id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
|
||||
/**
|
||||
* 확장 상태 가드
|
||||
*
|
||||
* 설치/활성화/비활성화/삭제/업데이트 등의 작업 실행 전,
|
||||
* 현재 상태가 진행 중(installing, uninstalling, updating)이면 예외를 발생시킵니다.
|
||||
*/
|
||||
class ExtensionStatusGuard
|
||||
{
|
||||
/**
|
||||
* 진행 중인 작업이 없는지 확인합니다.
|
||||
*
|
||||
* @param ExtensionStatus $status 현재 상태
|
||||
* @param string $identifier 확장 식별자 (에러 메시지용)
|
||||
*
|
||||
* @throws \RuntimeException 진행 중인 작업이 있을 때
|
||||
*/
|
||||
public static function assertNotInProgress(ExtensionStatus $status, string $identifier): void
|
||||
{
|
||||
$inProgressStatuses = [
|
||||
ExtensionStatus::Installing,
|
||||
ExtensionStatus::Uninstalling,
|
||||
ExtensionStatus::Updating,
|
||||
];
|
||||
|
||||
if (in_array($status, $inProgressStatuses, true)) {
|
||||
throw new \RuntimeException(
|
||||
__('extensions.errors.operation_in_progress', [
|
||||
'name' => $identifier,
|
||||
'status' => $status->value,
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Windows 파일 핸들(잠금) 감지 및 해제 헬퍼
|
||||
*
|
||||
* 확장 업데이트 시 디렉토리 이동(rename)이 실패하면,
|
||||
* 해당 디렉토리를 잠그고 있는 프로세스를 감지하고 종료할 수 있습니다.
|
||||
*
|
||||
* 탐지 전략 (우선순위 순):
|
||||
* 1. WMI CommandLine + 프로세스 모듈 검색 — 디렉토리 핸들 잠금 (Node.js 워처, IDE 등)
|
||||
* 2. Restart Manager API — 파일 수준 잠금
|
||||
* 3. handle.exe (Sysinternals) — 폴백
|
||||
*/
|
||||
class FileHandleHelper
|
||||
{
|
||||
/**
|
||||
* 현재 PHP 프로세스의 PID (종료 대상에서 제외)
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private static function currentPid(): int
|
||||
{
|
||||
return getmypid() ?: 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows 환경인지 확인합니다.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isWindows(): bool
|
||||
{
|
||||
return PHP_OS_FAMILY === 'Windows';
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리를 잠그고 있는 프로세스 목록을 반환합니다.
|
||||
*
|
||||
* 3단계 전략으로 탐지합니다:
|
||||
* 1. WMI CommandLine + 모듈 검색 (디렉토리 핸들 — Node.js, IDE 등)
|
||||
* 2. Restart Manager API (파일 수준 잠금)
|
||||
* 3. handle.exe 폴백
|
||||
*
|
||||
* @param string $directoryPath 잠금 확인할 디렉토리 경로
|
||||
* @param int $maxFiles Restart Manager에서 검사할 최대 파일 수
|
||||
* @param \Closure|null $onOutput 진단 출력 콜백 (string $message)
|
||||
* @return array<int, array{pid: int, name: string, app: string}> 프로세스 목록
|
||||
*/
|
||||
public static function findLockingProcesses(string $directoryPath, int $maxFiles = 30, ?\Closure $onOutput = null): array
|
||||
{
|
||||
$output = $onOutput ?? function () {};
|
||||
|
||||
if (! self::isWindows()) {
|
||||
$output('[lock-detect] Windows 환경이 아니므로 잠금 감지를 건너뜁니다.');
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$allProcesses = [];
|
||||
|
||||
// 1순위: WMI CommandLine + 프로세스 모듈 검색
|
||||
$output('[lock-detect] 1단계: WMI 프로세스 CommandLine + 모듈 검색...');
|
||||
$wmiResults = self::detectViaWmi($directoryPath, $onOutput);
|
||||
foreach ($wmiResults as $proc) {
|
||||
$allProcesses[$proc['pid']] = $proc;
|
||||
}
|
||||
|
||||
// 2순위: Restart Manager API (파일 수준 잠금)
|
||||
$files = self::sampleFiles($directoryPath, $maxFiles);
|
||||
if (! empty($files)) {
|
||||
$output('[lock-detect] 2단계: Restart Manager API ('.count($files).'개 파일)...');
|
||||
$rmResults = self::detectViaRestartManager($files, $onOutput);
|
||||
foreach ($rmResults as $proc) {
|
||||
if (! isset($allProcesses[$proc['pid']])) {
|
||||
$allProcesses[$proc['pid']] = $proc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3순위: handle.exe 폴백
|
||||
if (empty($allProcesses)) {
|
||||
$output('[lock-detect] 3단계: handle.exe 폴백...');
|
||||
$handleResults = self::detectViaHandle($directoryPath, $onOutput);
|
||||
foreach ($handleResults as $proc) {
|
||||
if (! isset($allProcesses[$proc['pid']])) {
|
||||
$allProcesses[$proc['pid']] = $proc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 현재 PHP 프로세스 제외
|
||||
$currentPid = self::currentPid();
|
||||
unset($allProcesses[$currentPid]);
|
||||
|
||||
$filtered = array_values($allProcesses);
|
||||
|
||||
if (! empty($filtered)) {
|
||||
$output('[lock-detect] 감지된 잠금 프로세스: '.count($filtered).'개');
|
||||
foreach ($filtered as $proc) {
|
||||
$output("[lock-detect] PID {$proc['pid']}: {$proc['name']} ({$proc['app']})");
|
||||
}
|
||||
} else {
|
||||
$output('[lock-detect] 잠금 프로세스를 감지하지 못했습니다.');
|
||||
}
|
||||
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
/**
|
||||
* 잠금 프로세스를 종료합니다.
|
||||
*
|
||||
* @param array<int, array{pid: int, name: string, app: string}> $processes 종료할 프로세스 목록
|
||||
* @return array{killed: array, failed: array} 종료 결과
|
||||
*/
|
||||
public static function killProcesses(array $processes): array
|
||||
{
|
||||
$killed = [];
|
||||
$failed = [];
|
||||
|
||||
foreach ($processes as $proc) {
|
||||
$pid = $proc['pid'];
|
||||
$name = $proc['name'];
|
||||
|
||||
// 시스템 프로세스 보호
|
||||
if (self::isSystemProcess($name)) {
|
||||
$failed[] = array_merge($proc, ['reason' => '시스템 프로세스는 종료할 수 없습니다']);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (self::isWindows()) {
|
||||
$result = self::killWindowsProcess($pid);
|
||||
} else {
|
||||
$result = self::killUnixProcess($pid);
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
$killed[] = $proc;
|
||||
} else {
|
||||
$failed[] = array_merge($proc, ['reason' => '프로세스 종료 실패']);
|
||||
}
|
||||
}
|
||||
|
||||
return ['killed' => $killed, 'failed' => $failed];
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리 잠금을 감지하고 해제합니다.
|
||||
*
|
||||
* @param string $directoryPath 잠금 해제할 디렉토리 경로
|
||||
* @param \Closure|null $onOutput 출력 콜백 (string $message)
|
||||
* @return bool 잠금 해제 성공 여부 (잠금이 없었거나, 모두 해제된 경우 true)
|
||||
*/
|
||||
public static function releaseLocks(string $directoryPath, ?\Closure $onOutput = null): bool
|
||||
{
|
||||
$output = $onOutput ?? function () {};
|
||||
|
||||
$output('');
|
||||
$output('🔍 파일 잠금 감지 시작: '.$directoryPath);
|
||||
|
||||
$processes = self::findLockingProcesses($directoryPath, 30, $onOutput);
|
||||
|
||||
if (empty($processes)) {
|
||||
$output('');
|
||||
$output('ℹ️ 잠금 프로세스가 감지되지 않았습니다.');
|
||||
$output(' 수동 해결: 해당 디렉토리를 참조하는 프로세스를 닫은 후 재시도하세요.');
|
||||
$output('');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$output('');
|
||||
$output('⚠️ 파일 잠금 프로세스 감지됨 ('.count($processes).'개):');
|
||||
foreach ($processes as $proc) {
|
||||
$output(" - PID {$proc['pid']}: {$proc['name']} ({$proc['app']})");
|
||||
}
|
||||
$output('');
|
||||
$output('🔧 잠금 프로세스 종료 시도...');
|
||||
|
||||
$result = self::killProcesses($processes);
|
||||
|
||||
foreach ($result['killed'] as $proc) {
|
||||
$output(" ✅ PID {$proc['pid']} ({$proc['name']}) 종료 완료");
|
||||
}
|
||||
|
||||
foreach ($result['failed'] as $proc) {
|
||||
$output(" ❌ PID {$proc['pid']} ({$proc['name']}) 종료 실패: {$proc['reason']}");
|
||||
}
|
||||
|
||||
if (! empty($result['failed'])) {
|
||||
$output('');
|
||||
$output('❌ 일부 프로세스를 종료하지 못했습니다. 수동으로 종료 후 재시도하세요.');
|
||||
Log::warning('파일 잠금 해제 실패', [
|
||||
'directory' => $directoryPath,
|
||||
'failed' => $result['failed'],
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// 프로세스 종료 후 핸들 해제 대기
|
||||
$output('');
|
||||
$output('⏳ 핸들 해제 대기 중 (500ms)...');
|
||||
usleep(500_000); // 500ms
|
||||
$output('✅ 잠금 해제 완료 — 디렉토리 이동 재시도합니다.');
|
||||
$output('');
|
||||
|
||||
Log::info('파일 잠금 해제 완료', [
|
||||
'directory' => $directoryPath,
|
||||
'killed' => $result['killed'],
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 탐지 전략 1: WMI CommandLine + 프로세스 모듈 검색
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* WMI로 해당 디렉토리 경로를 참조하는 프로세스를 탐지합니다.
|
||||
*
|
||||
* Get-CimInstance Win32_Process의 CommandLine에 디렉토리 경로가 포함된 프로세스와,
|
||||
* Get-Process의 Modules에서 해당 디렉토리 내 DLL을 로드한 프로세스를 찾습니다.
|
||||
* Node.js 워처, IDE, 파일 탐색기 등 프로세스 종류 무관하게 감지합니다.
|
||||
*
|
||||
* @param string $directoryPath 디렉토리 경로
|
||||
* @param \Closure|null $onOutput 진단 출력 콜백
|
||||
* @return array<int, array{pid: int, name: string, app: string}> 프로세스 목록
|
||||
*/
|
||||
private static function detectViaWmi(string $directoryPath, ?\Closure $onOutput = null): array
|
||||
{
|
||||
$output = $onOutput ?? function () {};
|
||||
|
||||
if (! function_exists('exec')) {
|
||||
$output('[WMI] exec() 함수 사용 불가');
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$normalizedPath = str_replace('/', '\\', $directoryPath);
|
||||
// PowerShell에서 안전하게 사용할 수 있도록 이스케이프
|
||||
$escapedPath = str_replace("'", "''", $normalizedPath);
|
||||
|
||||
// 간결한 인라인 PowerShell — 임시 파일 불필요
|
||||
$psCommand = implode('; ', [
|
||||
'$ErrorActionPreference = "SilentlyContinue"',
|
||||
'$p = "'.addcslashes($escapedPath, '"').'"',
|
||||
'$pl = $p.ToLower()',
|
||||
'$r = @{}',
|
||||
// Strategy 1: CommandLine search
|
||||
'Get-CimInstance Win32_Process | ForEach-Object { if ($_.CommandLine) { $cl = $_.CommandLine.ToLower().Replace("/","\\"); if ($cl.Contains($pl)) { $r[$_.ProcessId] = "$($_.ProcessId)|$($_.Name)|$($_.CommandLine.Substring(0,[Math]::Min(120,$_.CommandLine.Length)))" } } }',
|
||||
// Strategy 2: Modules search
|
||||
'Get-Process | ForEach-Object { if (-not $r.ContainsKey($_.Id)) { try { foreach ($m in $_.Modules) { if ($m.FileName -and $m.FileName.ToLower().StartsWith($pl)) { $r[$_.Id] = "$($_.Id)|$($_.ProcessName)|module:$($m.FileName)"; break } } } catch {} } }',
|
||||
// Output
|
||||
'foreach ($v in $r.Values) { Write-Output $v }',
|
||||
]);
|
||||
|
||||
$cmdOutput = [];
|
||||
$exitCode = 0;
|
||||
exec(
|
||||
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command '.escapeshellarg($psCommand).' 2>NUL',
|
||||
$cmdOutput,
|
||||
$exitCode
|
||||
);
|
||||
|
||||
$output("[WMI] PowerShell exit code: {$exitCode}, 출력: ".count($cmdOutput).'줄');
|
||||
|
||||
if (! empty($cmdOutput)) {
|
||||
foreach ($cmdOutput as $line) {
|
||||
$output("[WMI] → {$line}");
|
||||
}
|
||||
}
|
||||
|
||||
return self::parseProcessOutput($cmdOutput);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 탐지 전략 2: Restart Manager API (파일 수준 잠금)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Windows Restart Manager API를 사용하여 잠금 프로세스를 탐지합니다.
|
||||
*
|
||||
* PowerShell에서 인라인 C# 코드로 Restart Manager API를 호출합니다.
|
||||
* 외부 도구(handle.exe 등)가 필요 없으며, Windows Vista+ 내장 API입니다.
|
||||
* 파일 수준 잠금만 감지 가능 (디렉토리 핸들은 감지 불가).
|
||||
*
|
||||
* @param string[] $filePaths 검사할 파일 경로 목록
|
||||
* @param \Closure|null $onOutput 진단 출력 콜백
|
||||
* @return array<int, array{pid: int, name: string, app: string}> 프로세스 목록
|
||||
*/
|
||||
private static function detectViaRestartManager(array $filePaths, ?\Closure $onOutput = null): array
|
||||
{
|
||||
$output = $onOutput ?? function () {};
|
||||
|
||||
if (! function_exists('exec')) {
|
||||
$output('[RestartManager] exec() 함수 사용 불가');
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$tempScript = tempnam(sys_get_temp_dir(), 'g7lock_');
|
||||
$scriptPath = $tempScript.'.ps1';
|
||||
rename($tempScript, $scriptPath);
|
||||
|
||||
$escapedFiles = array_map(
|
||||
fn ($f) => "'".str_replace("'", "''", str_replace('/', '\\', $f))."'",
|
||||
$filePaths
|
||||
);
|
||||
$fileListPs = '@('.implode(',', $escapedFiles).')';
|
||||
|
||||
$psScript = self::getRestartManagerScript($fileListPs);
|
||||
file_put_contents($scriptPath, $psScript);
|
||||
|
||||
$stderrPath = $scriptPath.'.err';
|
||||
|
||||
try {
|
||||
$cmdOutput = [];
|
||||
$exitCode = 0;
|
||||
exec(
|
||||
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File '.escapeshellarg($scriptPath).' 2>'.escapeshellarg($stderrPath),
|
||||
$cmdOutput,
|
||||
$exitCode
|
||||
);
|
||||
|
||||
$output("[RestartManager] exit code: {$exitCode}, 출력: ".count($cmdOutput).'줄');
|
||||
|
||||
if (file_exists($stderrPath)) {
|
||||
$stderr = trim(file_get_contents($stderrPath));
|
||||
if (! empty($stderr)) {
|
||||
$lines = array_slice(explode("\n", $stderr), 0, 3);
|
||||
foreach ($lines as $line) {
|
||||
$output('[RestartManager] stderr: '.trim($line));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self::parseProcessOutput($cmdOutput);
|
||||
} finally {
|
||||
@unlink($scriptPath);
|
||||
@unlink($stderrPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restart Manager API를 호출하는 PowerShell 스크립트를 생성합니다.
|
||||
*
|
||||
* @param string $fileListPs PowerShell 배열 형식의 파일 목록
|
||||
* @return string PowerShell 스크립트 내용
|
||||
*/
|
||||
private static function getRestartManagerScript(string $fileListPs): string
|
||||
{
|
||||
return <<<'PSHEADER'
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
|
||||
Add-Type -TypeDefinition @"
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.InteropServices.ComTypes;
|
||||
|
||||
public class RmLockDetector
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct RM_UNIQUE_PROCESS
|
||||
{
|
||||
public int dwProcessId;
|
||||
public FILETIME ProcessStartTime;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
struct RM_PROCESS_INFO
|
||||
{
|
||||
public RM_UNIQUE_PROCESS Process;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
|
||||
public string strAppName;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
|
||||
public string strServiceShortName;
|
||||
public int ApplicationType;
|
||||
public uint AppStatus;
|
||||
public uint TSSessionId;
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bRestartable;
|
||||
}
|
||||
|
||||
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
|
||||
static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
|
||||
|
||||
[DllImport("rstrtmgr.dll")]
|
||||
static extern int RmEndSession(uint pSessionHandle);
|
||||
|
||||
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
|
||||
static extern int RmRegisterResources(uint pSessionHandle, uint nFiles, string[] rgsFilenames, uint nApplications, [In] RM_UNIQUE_PROCESS[] rgApplications, uint nServices, string[] rgsServiceNames);
|
||||
|
||||
[DllImport("rstrtmgr.dll")]
|
||||
static extern int RmGetList(uint dwSessionHandle, out uint pnProcInfoNeeded, ref uint pnProcInfo, [In, Out] RM_PROCESS_INFO[] rgAffectedApps, ref uint lpdwRebootReasons);
|
||||
|
||||
public static string[] FindLockingProcesses(string[] filePaths)
|
||||
{
|
||||
uint handle;
|
||||
string key = Guid.NewGuid().ToString();
|
||||
int res = RmStartSession(out handle, 0, key);
|
||||
if (res != 0) return new string[0];
|
||||
|
||||
try
|
||||
{
|
||||
res = RmRegisterResources(handle, (uint)filePaths.Length, filePaths, 0, null, 0, null);
|
||||
if (res != 0) return new string[0];
|
||||
|
||||
uint pnProcInfoNeeded = 0;
|
||||
uint pnProcInfo = 0;
|
||||
uint lpdwRebootReasons = 0;
|
||||
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
|
||||
|
||||
if (pnProcInfoNeeded == 0) return new string[0];
|
||||
|
||||
RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
|
||||
pnProcInfo = pnProcInfoNeeded;
|
||||
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
|
||||
if (res != 0) return new string[0];
|
||||
|
||||
var results = new List<string>();
|
||||
var seen = new HashSet<int>();
|
||||
for (int i = 0; i < pnProcInfo; i++)
|
||||
{
|
||||
int pid = processInfo[i].Process.dwProcessId;
|
||||
if (seen.Contains(pid)) continue;
|
||||
seen.Add(pid);
|
||||
try
|
||||
{
|
||||
var proc = Process.GetProcessById(pid);
|
||||
results.Add(pid + "|" + proc.ProcessName + "|" + processInfo[i].strAppName);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return results.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
RmEndSession(handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
"@
|
||||
|
||||
PSHEADER
|
||||
."\$files = {$fileListPs}\n"
|
||||
.<<<'PSFOOTER'
|
||||
$results = [RmLockDetector]::FindLockingProcesses($files)
|
||||
foreach ($r in $results) {
|
||||
Write-Output $r
|
||||
}
|
||||
PSFOOTER;
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 탐지 전략 3: handle.exe (Sysinternals) 폴백
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* handle.exe (Sysinternals)를 사용하여 잠금 프로세스를 탐지합니다.
|
||||
*
|
||||
* @param string $directoryPath 디렉토리 경로
|
||||
* @param \Closure|null $onOutput 진단 출력 콜백
|
||||
* @return array<int, array{pid: int, name: string, app: string}> 프로세스 목록
|
||||
*/
|
||||
private static function detectViaHandle(string $directoryPath, ?\Closure $onOutput = null): array
|
||||
{
|
||||
$logOutput = $onOutput ?? function () {};
|
||||
|
||||
if (! function_exists('exec')) {
|
||||
$logOutput('[handle.exe] exec() 함수 사용 불가');
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$cmdOutput = [];
|
||||
$exitCode = 0;
|
||||
|
||||
$dirPath = str_replace('/', '\\', $directoryPath);
|
||||
exec(
|
||||
'handle.exe -nobanner -accepteula '.escapeshellarg($dirPath).' 2>NUL',
|
||||
$cmdOutput,
|
||||
$exitCode
|
||||
);
|
||||
|
||||
if ($exitCode !== 0 || empty($cmdOutput)) {
|
||||
$logOutput("[handle.exe] 사용 불가 (exit code: {$exitCode})");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$logOutput('[handle.exe] '.count($cmdOutput).'줄 출력 수신');
|
||||
|
||||
return self::parseHandleOutput($cmdOutput);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 파서/유틸리티
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 디렉토리 내 파일을 샘플링합니다.
|
||||
*
|
||||
* @param string $directoryPath 디렉토리 경로
|
||||
* @param int $maxFiles 최대 파일 수
|
||||
* @return string[] 파일 경로 목록
|
||||
*/
|
||||
private static function sampleFiles(string $directoryPath, int $maxFiles): array
|
||||
{
|
||||
if (! is_dir($directoryPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$files = [];
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($directoryPath, \RecursiveDirectoryIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::SELF_FIRST
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isFile()) {
|
||||
$files[] = $file->getPathname();
|
||||
if (count($files) >= $maxFiles) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* "PID|ProcessName|AppName" 형식의 출력을 파싱합니다.
|
||||
*
|
||||
* @param string[] $output 프로세스 출력 라인
|
||||
* @return array<int, array{pid: int, name: string, app: string}> 프로세스 목록
|
||||
*/
|
||||
private static function parseProcessOutput(array $output): array
|
||||
{
|
||||
$processes = [];
|
||||
$seen = [];
|
||||
|
||||
foreach ($output as $line) {
|
||||
$line = trim($line);
|
||||
if (empty($line) || str_starts_with($line, 'ERROR:')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts = explode('|', $line, 3);
|
||||
if (count($parts) < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$pid = (int) $parts[0];
|
||||
if ($pid <= 0 || isset($seen[$pid])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$seen[$pid] = true;
|
||||
$processes[] = [
|
||||
'pid' => $pid,
|
||||
'name' => $parts[1] ?? 'unknown',
|
||||
'app' => $parts[2] ?? $parts[1] ?? 'unknown',
|
||||
];
|
||||
}
|
||||
|
||||
return $processes;
|
||||
}
|
||||
|
||||
/**
|
||||
* handle.exe 출력을 파싱합니다.
|
||||
*
|
||||
* @param string[] $output handle.exe 출력
|
||||
* @return array<int, array{pid: int, name: string, app: string}> 프로세스 목록
|
||||
*/
|
||||
private static function parseHandleOutput(array $output): array
|
||||
{
|
||||
$processes = [];
|
||||
$seen = [];
|
||||
|
||||
foreach ($output as $line) {
|
||||
if (preg_match('/^(.+?)\s+pid:\s*(\d+)\s/', $line, $matches)) {
|
||||
$name = trim($matches[1]);
|
||||
$pid = (int) $matches[2];
|
||||
|
||||
if ($pid <= 0 || isset($seen[$pid])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$seen[$pid] = true;
|
||||
$processes[] = [
|
||||
'pid' => $pid,
|
||||
'name' => $name,
|
||||
'app' => $name,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $processes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 프로세스 여부를 확인합니다.
|
||||
*
|
||||
* @param string $processName 프로세스명
|
||||
* @return bool 시스템 프로세스이면 true
|
||||
*/
|
||||
private static function isSystemProcess(string $processName): bool
|
||||
{
|
||||
$systemProcesses = [
|
||||
'System',
|
||||
'svchost',
|
||||
'csrss',
|
||||
'wininit',
|
||||
'winlogon',
|
||||
'services',
|
||||
'lsass',
|
||||
'smss',
|
||||
'explorer',
|
||||
'dwm',
|
||||
'RuntimeBroker',
|
||||
'SearchHost',
|
||||
'StartMenuExperienceHost',
|
||||
];
|
||||
|
||||
return in_array($processName, $systemProcesses, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows 프로세스를 종료합니다.
|
||||
*
|
||||
* @param int $pid 프로세스 ID
|
||||
* @return bool 종료 성공 여부
|
||||
*/
|
||||
private static function killWindowsProcess(int $pid): bool
|
||||
{
|
||||
if (! function_exists('exec')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
exec("taskkill /PID {$pid} /F 2>NUL", $output, $exitCode);
|
||||
|
||||
return $exitCode === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unix 프로세스를 종료합니다.
|
||||
*
|
||||
* @param int $pid 프로세스 ID
|
||||
* @return bool 종료 성공 여부
|
||||
*/
|
||||
private static function killUnixProcess(int $pid): bool
|
||||
{
|
||||
if (function_exists('posix_kill')) {
|
||||
return posix_kill($pid, 9); // SIGKILL
|
||||
}
|
||||
|
||||
if (function_exists('exec')) {
|
||||
$output = [];
|
||||
$exitCode = 0;
|
||||
exec("kill -9 {$pid} 2>/dev/null", $output, $exitCode);
|
||||
|
||||
return $exitCode === 0;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
class FilePermissionHelper
|
||||
{
|
||||
/**
|
||||
* 디렉토리를 재귀적으로 복사하면서 기존 파일/디렉토리의 퍼미션을 보존합니다.
|
||||
*
|
||||
* - 기존 디렉토리: 퍼미션/소유자/그룹 유지
|
||||
* - 신규 디렉토리: 부모 디렉토리의 퍼미션 상속
|
||||
* - 기존 파일: 퍼미션/소유자/그룹 유지한 채 내용만 교체
|
||||
* - 신규 파일: PHP 기본 퍼미션 적용 (umask 기반)
|
||||
* - removeOrphans=false: 소스에 없고 대상에만 있는 파일 유지 (사용자 추가 파일 보호)
|
||||
* - removeOrphans=true: 소스에 없고 대상에만 있는 파일/디렉토리 삭제 (excludes 제외)
|
||||
*
|
||||
* @param string $source 소스 디렉토리 경로
|
||||
* @param string $destination 대상 디렉토리 경로
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @param array $excludes 제외할 이름 또는 경로 목록 (예: ['node_modules', '.git', 'node_modules/test_dir'])
|
||||
* @param string $relativePath 현재 상대 경로 (내부 재귀용)
|
||||
* @param bool $removeOrphans 소스에 없는 대상 파일/디렉토리 삭제 여부
|
||||
* @return void
|
||||
*/
|
||||
public static function copyDirectory(string $source, string $destination, ?\Closure $onProgress = null, array $excludes = [], string $relativePath = '', bool $removeOrphans = false): void
|
||||
{
|
||||
if (! File::isDirectory($destination)) {
|
||||
// 신규 디렉토리: 부모 디렉토리의 퍼미션 상속
|
||||
$parentDir = dirname($destination);
|
||||
$parentPerms = File::isDirectory($parentDir) ? (fileperms($parentDir) & 0777) : 0755;
|
||||
File::ensureDirectoryExists($destination, $parentPerms, true);
|
||||
}
|
||||
// 기존 디렉토리: 퍼미션 건드리지 않음 (그대로 유지)
|
||||
|
||||
$items = new \FilesystemIterator($source, \FilesystemIterator::SKIP_DOTS);
|
||||
|
||||
foreach ($items as $item) {
|
||||
$itemName = $item->getFilename();
|
||||
$itemRelativePath = $relativePath === '' ? $itemName : $relativePath.'/'.$itemName;
|
||||
|
||||
if (static::isExcluded($itemName, $itemRelativePath, $excludes)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$destPath = $destination.DIRECTORY_SEPARATOR.$itemName;
|
||||
|
||||
if ($item->isDir()) {
|
||||
static::copyDirectory($item->getPathname(), $destPath, $onProgress, $excludes, $itemRelativePath, $removeOrphans);
|
||||
} else {
|
||||
static::copyFile($item->getPathname(), $destPath);
|
||||
}
|
||||
}
|
||||
|
||||
// 소스에 없는 대상 파일/디렉토리 삭제
|
||||
if ($removeOrphans && File::isDirectory($destination)) {
|
||||
static::removeOrphanItems($source, $destination, $excludes, $relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 소스에 없고 대상에만 있는 파일/디렉토리를 삭제합니다.
|
||||
*
|
||||
* excludes 목록에 해당하는 항목은 삭제하지 않습니다.
|
||||
*
|
||||
* @param string $source 소스 디렉토리 경로
|
||||
* @param string $destination 대상 디렉토리 경로
|
||||
* @param array $excludes 제외할 이름 또는 경로 목록
|
||||
* @param string $relativePath 현재 상대 경로
|
||||
* @return void
|
||||
*/
|
||||
protected static function removeOrphanItems(string $source, string $destination, array $excludes, string $relativePath): void
|
||||
{
|
||||
$destItems = new \FilesystemIterator($destination, \FilesystemIterator::SKIP_DOTS);
|
||||
|
||||
foreach ($destItems as $destItem) {
|
||||
$itemName = $destItem->getFilename();
|
||||
$itemRelativePath = $relativePath === '' ? $itemName : $relativePath.'/'.$itemName;
|
||||
|
||||
// excludes 대상은 삭제하지 않음
|
||||
if (static::isExcluded($itemName, $itemRelativePath, $excludes)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$srcPath = $source.DIRECTORY_SEPARATOR.$itemName;
|
||||
|
||||
// 소스에 존재하지 않는 항목만 삭제
|
||||
if (! File::exists($srcPath) && ! File::isDirectory($srcPath)) {
|
||||
if ($destItem->isDir()) {
|
||||
File::deleteDirectory($destItem->getPathname());
|
||||
} else {
|
||||
File::delete($destItem->getPathname());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 항목이 제외 대상인지 확인합니다.
|
||||
*
|
||||
* - 단순 이름 (슬래시 미포함): 모든 레벨에서 해당 이름과 매칭
|
||||
* - 경로 패턴 (슬래시 포함): 상대 경로와 정확히 매칭
|
||||
*
|
||||
* @param string $itemName 현재 항목의 파일/디렉토리 이름
|
||||
* @param string $itemRelativePath 루트로부터의 상대 경로
|
||||
* @param array $excludes 제외 목록
|
||||
* @return bool 제외 대상 여부
|
||||
*/
|
||||
public static function isExcluded(string $itemName, string $itemRelativePath, array $excludes): bool
|
||||
{
|
||||
foreach ($excludes as $exclude) {
|
||||
if (str_contains($exclude, '/')) {
|
||||
// 경로 패턴: 상대 경로와 정확히 매칭
|
||||
if ($itemRelativePath === $exclude) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
// 단순 이름: 모든 레벨에서 매칭
|
||||
if ($itemName === $exclude) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 퍼미션과 소유권을 보존하면서 파일을 복사합니다.
|
||||
*
|
||||
* - 기존 파일: 복사 후 원래 퍼미션/소유자/그룹 복원
|
||||
* - 신규 파일: PHP 기본 퍼미션 적용 (umask 기반)
|
||||
*
|
||||
* @param string $source 소스 파일
|
||||
* @param string $destination 대상 파일
|
||||
* @return void
|
||||
*/
|
||||
public static function copyFile(string $source, string $destination): void
|
||||
{
|
||||
$existingPerms = null;
|
||||
$existingOwner = null;
|
||||
$existingGroup = null;
|
||||
|
||||
if (File::exists($destination)) {
|
||||
$existingPerms = fileperms($destination);
|
||||
$existingOwner = fileowner($destination);
|
||||
$existingGroup = filegroup($destination);
|
||||
}
|
||||
|
||||
File::ensureDirectoryExists(dirname($destination));
|
||||
File::copy($source, $destination);
|
||||
|
||||
if ($existingPerms !== null) {
|
||||
@chmod($destination, $existingPerms);
|
||||
}
|
||||
if ($existingOwner !== null && function_exists('chown')) {
|
||||
@chown($destination, $existingOwner);
|
||||
}
|
||||
if ($existingGroup !== null && function_exists('chgrp')) {
|
||||
@chgrp($destination, $existingGroup);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* GitHub API 연동 공통 유틸리티.
|
||||
*
|
||||
* 코어 업데이트(CoreUpdateService)와 확장 수동 설치(ModuleService, PluginService, TemplateService)
|
||||
* 모두에서 사용할 수 있는 GitHub API 관련 공통 메서드를 제공합니다.
|
||||
*/
|
||||
class GithubHelper
|
||||
{
|
||||
/**
|
||||
* GitHub URL에서 owner/repo를 추출합니다.
|
||||
*
|
||||
* @param string $githubUrl GitHub 저장소 URL
|
||||
* @return array{0: string, 1: string} [owner, repo]
|
||||
*
|
||||
* @throws \RuntimeException URL 파싱 실패 시
|
||||
*/
|
||||
public static function parseUrl(string $githubUrl): array
|
||||
{
|
||||
if (empty($githubUrl)) {
|
||||
throw new \RuntimeException(__('common.errors.github_url_empty'));
|
||||
}
|
||||
|
||||
if (! preg_match('#github\.com[/:]([^/]+)/([^/\.]+)(?:\.git)?/?$#', $githubUrl, $matches)) {
|
||||
throw new \RuntimeException(__('common.errors.github_url_invalid'));
|
||||
}
|
||||
|
||||
return [$matches[1], $matches[2]];
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub 저장소 존재 여부를 확인합니다.
|
||||
*
|
||||
* @param string $owner 저장소 소유자
|
||||
* @param string $repo 저장소 이름
|
||||
* @param string $token GitHub Personal Access Token (빈 문자열이면 인증 없음)
|
||||
* @return bool 저장소가 존재하면 true
|
||||
*/
|
||||
public static function checkRepoExists(string $owner, string $repo, string $token = ''): bool
|
||||
{
|
||||
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}";
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'timeout' => 5,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$response = @file_get_contents($apiUrl, false, $context);
|
||||
|
||||
if ($response === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$statusCode = static::extractStatusCode($http_response_header ?? []);
|
||||
|
||||
return $statusCode === 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* 최신 릴리스 정보를 조회합니다.
|
||||
*
|
||||
* @param string $owner 저장소 소유자
|
||||
* @param string $repo 저장소 이름
|
||||
* @param string $token GitHub Personal Access Token
|
||||
* @return array{version: string|null, zipball_url: string|null, error: string|null}
|
||||
*/
|
||||
public static function fetchLatestRelease(string $owner, string $repo, string $token = ''): array
|
||||
{
|
||||
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}/releases/latest";
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'timeout' => 10,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$response = @file_get_contents($apiUrl, false, $context);
|
||||
|
||||
if ($response === false) {
|
||||
return ['version' => null, 'zipball_url' => null, 'error' => __('common.errors.github_api_failed')];
|
||||
}
|
||||
|
||||
$statusCode = static::extractStatusCode($http_response_header ?? []);
|
||||
|
||||
if ($statusCode !== 200) {
|
||||
return ['version' => null, 'zipball_url' => null, 'error' => null];
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
|
||||
if (! isset($data['tag_name'])) {
|
||||
return ['version' => null, 'zipball_url' => null, 'error' => null];
|
||||
}
|
||||
|
||||
return [
|
||||
'version' => ltrim($data['tag_name'], 'v'),
|
||||
'zipball_url' => $data['zipball_url'] ?? null,
|
||||
'error' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub에서 ZIP을 다운로드합니다.
|
||||
*
|
||||
* 우선순위: 릴리스 zipball → main 브랜치 → master 브랜치
|
||||
*
|
||||
* @param string $owner 저장소 소유자
|
||||
* @param string $repo 저장소 이름
|
||||
* @param string $tempPath ZIP을 저장할 임시 디렉토리
|
||||
* @param string $token GitHub Personal Access Token
|
||||
* @return string 다운로드된 ZIP 파일 경로
|
||||
*
|
||||
* @throws \RuntimeException 다운로드 실패 시
|
||||
*/
|
||||
public static function downloadZip(string $owner, string $repo, string $tempPath, string $token = ''): string
|
||||
{
|
||||
$zipPath = $tempPath.'/'.uniqid('github_').'.zip';
|
||||
|
||||
// 1단계: 릴리스에서 다운로드 시도
|
||||
$release = static::fetchLatestRelease($owner, $repo, $token);
|
||||
if ($release['zipball_url']) {
|
||||
try {
|
||||
static::downloadArchive($release['zipball_url'], $zipPath, $token);
|
||||
|
||||
return $zipPath;
|
||||
} catch (\RuntimeException $e) {
|
||||
Log::info('GitHub 릴리스 ZIP 다운로드 실패, 브랜치 폴백', [
|
||||
'owner' => $owner,
|
||||
'repo' => $repo,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// 2단계: main 브랜치 시도
|
||||
$mainUrl = "https://github.com/{$owner}/{$repo}/archive/refs/heads/main.zip";
|
||||
try {
|
||||
static::downloadArchive($mainUrl, $zipPath);
|
||||
|
||||
return $zipPath;
|
||||
} catch (\RuntimeException $e) {
|
||||
// main 실패 → master 폴백
|
||||
}
|
||||
|
||||
// 3단계: master 브랜치 시도
|
||||
$masterUrl = "https://github.com/{$owner}/{$repo}/archive/refs/heads/master.zip";
|
||||
try {
|
||||
static::downloadArchive($masterUrl, $zipPath);
|
||||
|
||||
return $zipPath;
|
||||
} catch (\RuntimeException $e) {
|
||||
throw new \RuntimeException(__('common.errors.github_download_failed'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 URL에서 아카이브를 다운로드합니다.
|
||||
*
|
||||
* @param string $url 다운로드 URL
|
||||
* @param string $savePath 저장할 파일 경로
|
||||
* @param string $token GitHub Personal Access Token
|
||||
*
|
||||
* @throws \RuntimeException 다운로드 실패 시
|
||||
*/
|
||||
public static function downloadArchive(string $url, string $savePath, string $token = ''): void
|
||||
{
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'follow_location' => true,
|
||||
'timeout' => 120,
|
||||
],
|
||||
]);
|
||||
|
||||
$content = @file_get_contents($url, false, $context);
|
||||
|
||||
if ($content === false) {
|
||||
throw new \RuntimeException(__('common.errors.github_archive_download_failed', ['url' => $url]));
|
||||
}
|
||||
|
||||
\Illuminate\Support\Facades\File::put($savePath, $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub 저장소에서 특정 태그/브랜치의 파일 내용을 가져옵니다.
|
||||
*
|
||||
* @param string $owner 저장소 소유자
|
||||
* @param string $repo 저장소 이름
|
||||
* @param string $ref 태그 또는 브랜치 (예: 'v7.0.0-alpha.5', 'main')
|
||||
* @param string $filePath 파일 경로 (예: 'CHANGELOG.md')
|
||||
* @param string $token GitHub Personal Access Token
|
||||
* @return string|null 파일 내용 (실패 시 null)
|
||||
*/
|
||||
public static function fetchRawFile(string $owner, string $repo, string $ref, string $filePath, string $token = ''): ?string
|
||||
{
|
||||
// v 접두사 있는/없는 태그 모두 시도
|
||||
$refs = [$ref];
|
||||
if (! str_starts_with($ref, 'v')) {
|
||||
$refs[] = 'v'.$ref;
|
||||
}
|
||||
|
||||
foreach ($refs as $tryRef) {
|
||||
$url = "https://raw.githubusercontent.com/{$owner}/{$repo}/{$tryRef}/{$filePath}";
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'timeout' => 10,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$content = @file_get_contents($url, false, $context);
|
||||
|
||||
if ($content === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$statusCode = static::extractStatusCode($http_response_header ?? []);
|
||||
|
||||
if ($statusCode === 200) {
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub API 요청용 HTTP 헤더를 생성합니다.
|
||||
*
|
||||
* @param string $token GitHub Personal Access Token (빈 문자열이면 인증 없음)
|
||||
* @return array HTTP 헤더 배열
|
||||
*/
|
||||
public static function buildHeaders(string $token = ''): array
|
||||
{
|
||||
$headers = [
|
||||
'User-Agent: G7',
|
||||
'Accept: application/vnd.github.v3+json',
|
||||
];
|
||||
|
||||
if (! empty($token)) {
|
||||
$headers[] = 'Authorization: Bearer '.$token;
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP 응답 헤더에서 상태 코드를 추출합니다.
|
||||
*
|
||||
* @param array $responseHeaders $http_response_header 배열
|
||||
* @return int HTTP 상태 코드
|
||||
*/
|
||||
public static function extractStatusCode(array $responseHeaders): int
|
||||
{
|
||||
$statusCode = 0;
|
||||
|
||||
foreach ($responseHeaders as $header) {
|
||||
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $header, $matches)) {
|
||||
// 리다이렉트 시 마지막 상태 코드를 사용하기 위해 계속 진행
|
||||
$statusCode = (int) $matches[1];
|
||||
}
|
||||
}
|
||||
|
||||
return $statusCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 확장 환경설정 마이그레이션 헬퍼
|
||||
*
|
||||
* UpgradeStep 내에서 사용하여 설정 파일의 스키마를 안전하게 변경합니다.
|
||||
* 모듈은 카테고리별 다중 파일, 플러그인은 단일 파일 구조를 지원합니다.
|
||||
*
|
||||
* @example
|
||||
* SettingsMigrator::forModule('sirsoft-ecommerce')
|
||||
* ->addField('shipping.tracking_enabled', false)
|
||||
* ->renameField('order_settings.auto_cancel_days', 'order_settings.pending_cancel_days')
|
||||
* ->removeField('seo.deprecated_field')
|
||||
* ->addCategory('notifications', ['email_enabled' => true])
|
||||
* ->apply();
|
||||
*/
|
||||
class SettingsMigrator
|
||||
{
|
||||
/**
|
||||
* 확장 타입 ('module' 또는 'plugin')
|
||||
*/
|
||||
private string $type;
|
||||
|
||||
/**
|
||||
* 확장 식별자
|
||||
*/
|
||||
private string $identifier;
|
||||
|
||||
/**
|
||||
* 적용할 오퍼레이션 큐
|
||||
*
|
||||
* @var array<int, array{operation: string, args: array}>
|
||||
*/
|
||||
private array $operations = [];
|
||||
|
||||
/**
|
||||
* @param string $type 확장 타입 ('module' 또는 'plugin')
|
||||
* @param string $identifier 확장 식별자
|
||||
*/
|
||||
private function __construct(string $type, string $identifier)
|
||||
{
|
||||
$this->type = $type;
|
||||
$this->identifier = $identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈용 마이그레이터를 생성합니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return static
|
||||
*/
|
||||
public static function forModule(string $identifier): static
|
||||
{
|
||||
return new static('module', $identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인용 마이그레이터를 생성합니다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return static
|
||||
*/
|
||||
public static function forPlugin(string $identifier): static
|
||||
{
|
||||
return new static('plugin', $identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* 새 필드를 추가합니다. 이미 존재하면 스킵합니다.
|
||||
*
|
||||
* @param string $path dot notation 경로 (모듈: 'category.field', 플러그인: 'field')
|
||||
* @param mixed $default 기본값
|
||||
* @return $this
|
||||
*/
|
||||
public function addField(string $path, mixed $default): static
|
||||
{
|
||||
$this->operations[] = [
|
||||
'operation' => 'addField',
|
||||
'args' => ['path' => $path, 'default' => $default],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 필드 이름을 변경합니다. 이전 키가 없으면 스킵합니다.
|
||||
*
|
||||
* @param string $oldPath 이전 경로 (dot notation)
|
||||
* @param string $newPath 새 경로 (dot notation)
|
||||
* @return $this
|
||||
*/
|
||||
public function renameField(string $oldPath, string $newPath): static
|
||||
{
|
||||
$this->operations[] = [
|
||||
'operation' => 'renameField',
|
||||
'args' => ['oldPath' => $oldPath, 'newPath' => $newPath],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 필드를 제거합니다. 키가 없으면 스킵합니다.
|
||||
*
|
||||
* @param string $path 제거할 경로 (dot notation)
|
||||
* @return $this
|
||||
*/
|
||||
public function removeField(string $path): static
|
||||
{
|
||||
$this->operations[] = [
|
||||
'operation' => 'removeField',
|
||||
'args' => ['path' => $path],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 필드 값을 변환합니다. 키가 없으면 스킵합니다.
|
||||
*
|
||||
* @param string $path 변환할 경로 (dot notation)
|
||||
* @param callable $transformer 변환 함수 (현재 값을 받아 새 값 반환)
|
||||
* @return $this
|
||||
*/
|
||||
public function transformField(string $path, callable $transformer): static
|
||||
{
|
||||
$this->operations[] = [
|
||||
'operation' => 'transformField',
|
||||
'args' => ['path' => $path, 'transformer' => $transformer],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 새 카테고리를 추가합니다. 모듈 전용입니다.
|
||||
*
|
||||
* 카테고리 파일을 생성하고 defaults.json의 _meta.categories 배열을 업데이트합니다.
|
||||
*
|
||||
* @param string $category 카테고리 이름
|
||||
* @param array $defaults 기본값
|
||||
* @return $this
|
||||
*
|
||||
* @throws \LogicException 플러그인에서 호출 시
|
||||
*/
|
||||
public function addCategory(string $category, array $defaults): static
|
||||
{
|
||||
$this->operations[] = [
|
||||
'operation' => 'addCategory',
|
||||
'args' => ['category' => $category, 'defaults' => $defaults],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 오퍼레이션을 실행합니다.
|
||||
*
|
||||
* @return array{applied: int, skipped: int, errors: array<string>}
|
||||
*/
|
||||
public function apply(): array
|
||||
{
|
||||
$result = ['applied' => 0, 'skipped' => 0, 'errors' => []];
|
||||
|
||||
foreach ($this->operations as $op) {
|
||||
try {
|
||||
$method = 'execute'.ucfirst($op['operation']);
|
||||
$applied = $this->{$method}($op['args']);
|
||||
|
||||
if ($applied) {
|
||||
$result['applied']++;
|
||||
} else {
|
||||
$result['skipped']++;
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$result['errors'][] = "[{$op['operation']}] {$e->getMessage()}";
|
||||
|
||||
Log::warning('SettingsMigrator 오퍼레이션 실패', [
|
||||
'type' => $this->type,
|
||||
'identifier' => $this->identifier,
|
||||
'operation' => $op['operation'],
|
||||
'args' => array_filter($op['args'], fn ($v) => ! is_callable($v)),
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* addField 오퍼레이션을 실행합니다.
|
||||
*
|
||||
* @param array $args 오퍼레이션 인수
|
||||
* @return bool 적용 여부
|
||||
*/
|
||||
private function executeAddField(array $args): bool
|
||||
{
|
||||
$path = $args['path'];
|
||||
$default = $args['default'];
|
||||
|
||||
[$filePath, $fieldPath] = $this->resolveFilePath($path);
|
||||
|
||||
if (! File::exists($filePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$data = $this->readJsonFile($filePath);
|
||||
|
||||
if (Arr::has($data, $fieldPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Arr::set($data, $fieldPath, $default);
|
||||
$this->writeJsonFile($filePath, $data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* renameField 오퍼레이션을 실행합니다.
|
||||
*
|
||||
* @param array $args 오퍼레이션 인수
|
||||
* @return bool 적용 여부
|
||||
*/
|
||||
private function executeRenameField(array $args): bool
|
||||
{
|
||||
$oldPath = $args['oldPath'];
|
||||
$newPath = $args['newPath'];
|
||||
|
||||
[$oldFilePath, $oldFieldPath] = $this->resolveFilePath($oldPath);
|
||||
[$newFilePath, $newFieldPath] = $this->resolveFilePath($newPath);
|
||||
|
||||
if (! File::exists($oldFilePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$oldData = $this->readJsonFile($oldFilePath);
|
||||
|
||||
if (! Arr::has($oldData, $oldFieldPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$value = Arr::get($oldData, $oldFieldPath);
|
||||
|
||||
// 같은 파일 내 이동
|
||||
if ($oldFilePath === $newFilePath) {
|
||||
Arr::forget($oldData, $oldFieldPath);
|
||||
Arr::set($oldData, $newFieldPath, $value);
|
||||
$this->writeJsonFile($oldFilePath, $oldData);
|
||||
} else {
|
||||
// 다른 파일 간 이동
|
||||
Arr::forget($oldData, $oldFieldPath);
|
||||
$this->writeJsonFile($oldFilePath, $oldData);
|
||||
|
||||
if (! File::exists($newFilePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$newData = $this->readJsonFile($newFilePath);
|
||||
Arr::set($newData, $newFieldPath, $value);
|
||||
$this->writeJsonFile($newFilePath, $newData);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* removeField 오퍼레이션을 실행합니다.
|
||||
*
|
||||
* @param array $args 오퍼레이션 인수
|
||||
* @return bool 적용 여부
|
||||
*/
|
||||
private function executeRemoveField(array $args): bool
|
||||
{
|
||||
$path = $args['path'];
|
||||
|
||||
[$filePath, $fieldPath] = $this->resolveFilePath($path);
|
||||
|
||||
if (! File::exists($filePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$data = $this->readJsonFile($filePath);
|
||||
|
||||
if (! Arr::has($data, $fieldPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Arr::forget($data, $fieldPath);
|
||||
$this->writeJsonFile($filePath, $data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* transformField 오퍼레이션을 실행합니다.
|
||||
*
|
||||
* @param array $args 오퍼레이션 인수
|
||||
* @return bool 적용 여부
|
||||
*/
|
||||
private function executeTransformField(array $args): bool
|
||||
{
|
||||
$path = $args['path'];
|
||||
$transformer = $args['transformer'];
|
||||
|
||||
[$filePath, $fieldPath] = $this->resolveFilePath($path);
|
||||
|
||||
if (! File::exists($filePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$data = $this->readJsonFile($filePath);
|
||||
|
||||
if (! Arr::has($data, $fieldPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$currentValue = Arr::get($data, $fieldPath);
|
||||
$newValue = $transformer($currentValue);
|
||||
|
||||
Arr::set($data, $fieldPath, $newValue);
|
||||
$this->writeJsonFile($filePath, $data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* addCategory 오퍼레이션을 실행합니다.
|
||||
*
|
||||
* @param array $args 오퍼레이션 인수
|
||||
* @return bool 적용 여부
|
||||
*
|
||||
* @throws \LogicException 플러그인에서 호출 시
|
||||
*/
|
||||
private function executeAddCategory(array $args): bool
|
||||
{
|
||||
if ($this->type === 'plugin') {
|
||||
throw new \LogicException('addCategory는 모듈에서만 사용할 수 있습니다.');
|
||||
}
|
||||
|
||||
$category = $args['category'];
|
||||
$defaults = $args['defaults'];
|
||||
|
||||
$settingsDir = $this->getSettingsDir();
|
||||
$categoryFile = $settingsDir.'/'.$category.'.json';
|
||||
|
||||
// 카테고리 파일이 이미 존재하면 스킵
|
||||
if (File::exists($categoryFile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 디렉토리 확인 및 생성
|
||||
if (! File::isDirectory($settingsDir)) {
|
||||
File::makeDirectory($settingsDir, 0755, true);
|
||||
}
|
||||
|
||||
// 카테고리 파일 생성
|
||||
$this->writeJsonFile($categoryFile, $defaults);
|
||||
|
||||
// defaults.json의 _meta.categories 업데이트
|
||||
$this->updateDefaultsJsonCategories($category);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* dot notation 경로를 파일 경로와 필드 경로로 분리합니다.
|
||||
*
|
||||
* @param string $path dot notation 경로
|
||||
* @return array{0: string, 1: string} [파일 경로, 필드 경로]
|
||||
*/
|
||||
private function resolveFilePath(string $path): array
|
||||
{
|
||||
$settingsDir = $this->getSettingsDir();
|
||||
|
||||
if ($this->type === 'module') {
|
||||
// 모듈: 'category.field.subfield' → category.json 내 'field.subfield'
|
||||
$dotPos = strpos($path, '.');
|
||||
if ($dotPos === false) {
|
||||
// 카테고리 자체를 대상으로 하는 경우 (addCategory에서 처리)
|
||||
return [$settingsDir.'/'.$path.'.json', ''];
|
||||
}
|
||||
|
||||
$category = substr($path, 0, $dotPos);
|
||||
$fieldPath = substr($path, $dotPos + 1);
|
||||
|
||||
return [$settingsDir.'/'.$category.'.json', $fieldPath];
|
||||
}
|
||||
|
||||
// 플러그인: 'field.subfield' → setting.json 내 'field.subfield'
|
||||
return [$settingsDir.'/setting.json', $path];
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 디렉토리 경로를 반환합니다.
|
||||
*
|
||||
* @return string 설정 디렉토리 절대 경로
|
||||
*/
|
||||
private function getSettingsDir(): string
|
||||
{
|
||||
if ($this->type === 'module') {
|
||||
return storage_path('app/modules/'.$this->identifier.'/settings');
|
||||
}
|
||||
|
||||
return storage_path('app/plugins/'.$this->identifier.'/settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 파일을 읽어 배열로 반환합니다.
|
||||
*
|
||||
* @param string $filePath 파일 절대 경로
|
||||
* @return array 파싱된 데이터
|
||||
*
|
||||
* @throws \RuntimeException JSON 파싱 실패 시
|
||||
*/
|
||||
private function readJsonFile(string $filePath): array
|
||||
{
|
||||
$content = File::get($filePath);
|
||||
$data = json_decode($content, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new \RuntimeException(
|
||||
"JSON 파싱 실패: {$filePath} - ".json_last_error_msg()
|
||||
);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열 데이터를 JSON 파일로 저장합니다.
|
||||
*
|
||||
* @param string $filePath 파일 절대 경로
|
||||
* @param array $data 저장할 데이터
|
||||
* @return void
|
||||
*/
|
||||
private function writeJsonFile(string $filePath, array $data): void
|
||||
{
|
||||
$content = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||
File::put($filePath, $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* defaults.json의 _meta.categories 배열에 새 카테고리를 추가합니다.
|
||||
*
|
||||
* @param string $category 추가할 카테고리 이름
|
||||
* @return void
|
||||
*/
|
||||
private function updateDefaultsJsonCategories(string $category): void
|
||||
{
|
||||
$defaultsPath = base_path("modules/{$this->identifier}/config/settings/defaults.json");
|
||||
|
||||
if (! File::exists($defaultsPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$data = $this->readJsonFile($defaultsPath);
|
||||
$categories = $data['_meta']['categories'] ?? [];
|
||||
|
||||
if (! in_array($category, $categories)) {
|
||||
$categories[] = $category;
|
||||
$data['_meta']['categories'] = $categories;
|
||||
$this->writeJsonFile($defaultsPath, $data);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('defaults.json 카테고리 업데이트 실패', [
|
||||
'module' => $this->identifier,
|
||||
'category' => $category,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* ZIP 추출 + manifest 검증 공통 유틸리티.
|
||||
*
|
||||
* 확장 수동 설치(ModuleService, PluginService, TemplateService)의 ZIP 처리 중복을 제거하고,
|
||||
* 코어에서도 ZIP 추출 시 재사용할 수 있는 공통 메서드를 제공합니다.
|
||||
*/
|
||||
class ZipInstallHelper
|
||||
{
|
||||
/**
|
||||
* ZIP 파일을 추출합니다.
|
||||
*
|
||||
* @param string $zipPath ZIP 파일 경로
|
||||
* @param string $extractPath 추출 대상 디렉토리
|
||||
* @return void
|
||||
*
|
||||
* @throws \RuntimeException ZIP 파일 열기/추출 실패 시
|
||||
*/
|
||||
public static function extractZip(string $zipPath, string $extractPath): void
|
||||
{
|
||||
if (! file_exists($zipPath)) {
|
||||
throw new \RuntimeException(__('common.errors.zip_file_not_found'));
|
||||
}
|
||||
|
||||
$zip = new ZipArchive;
|
||||
|
||||
if ($zip->open($zipPath) !== true) {
|
||||
throw new \RuntimeException(__('common.errors.zip_open_failed'));
|
||||
}
|
||||
|
||||
File::ensureDirectoryExists($extractPath);
|
||||
$zip->extractTo($extractPath);
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* ZIP 파일을 추출하고 manifest를 찾아 검증합니다.
|
||||
*
|
||||
* extractZip + findAndValidateManifest를 한번에 수행하는 편의 메서드입니다.
|
||||
*
|
||||
* @param string $zipPath ZIP 파일 경로
|
||||
* @param string $extractPath 추출 대상 디렉토리
|
||||
* @param string $manifestName manifest 파일명 (module.json, plugin.json, template.json)
|
||||
* @param string $extensionType 확장 타입 (modules, plugins, templates)
|
||||
* @return array{identifier: string, config: array, sourcePath: string}
|
||||
*
|
||||
* @throws \RuntimeException 추출 또는 검증 실패 시
|
||||
*/
|
||||
public static function extractAndValidate(
|
||||
string $zipPath,
|
||||
string $extractPath,
|
||||
string $manifestName,
|
||||
string $extensionType
|
||||
): array {
|
||||
static::extractZip($zipPath, $extractPath);
|
||||
|
||||
return static::findAndValidateManifest($extractPath, $manifestName, $extensionType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 추출된 디렉토리에서 manifest를 찾고 검증합니다.
|
||||
*
|
||||
* @param string $extractPath 추출된 디렉토리 경로
|
||||
* @param string $manifestName manifest 파일명 (module.json, plugin.json, template.json)
|
||||
* @param string $extensionType 확장 타입 (modules, plugins, templates)
|
||||
* @return array{identifier: string, config: array, sourcePath: string}
|
||||
*
|
||||
* @throws \RuntimeException manifest를 찾을 수 없거나 유효하지 않은 경우
|
||||
*/
|
||||
public static function findAndValidateManifest(
|
||||
string $extractPath,
|
||||
string $manifestName,
|
||||
string $extensionType
|
||||
): array {
|
||||
$manifestPath = static::findManifest($extractPath, $manifestName);
|
||||
|
||||
if (! $manifestPath) {
|
||||
// 확장 타입별 에러 메시지 키 생성 (modules → module, plugins → plugin, templates → template)
|
||||
$typeKey = rtrim($extensionType, 's');
|
||||
throw new \RuntimeException(__("{$extensionType}.errors.{$typeKey}_json_not_found"));
|
||||
}
|
||||
|
||||
$config = json_decode(File::get($manifestPath), true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$typeKey = rtrim($extensionType, 's');
|
||||
throw new \RuntimeException(__("{$extensionType}.errors.{$typeKey}_json_invalid"));
|
||||
}
|
||||
|
||||
$identifier = $config['identifier'] ?? null;
|
||||
|
||||
if (! $identifier) {
|
||||
throw new \RuntimeException(__("{$extensionType}.errors.identifier_missing"));
|
||||
}
|
||||
|
||||
return [
|
||||
'identifier' => $identifier,
|
||||
'config' => $config,
|
||||
'sourcePath' => dirname($manifestPath),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 파일을 디렉토리에서 찾습니다 (루트 + 1단계 하위).
|
||||
*
|
||||
* GitHub 아카이브는 owner-repo-hash/ 구조이므로 1단계 하위 검색이 필수입니다.
|
||||
*
|
||||
* @param string $directory 검색할 디렉토리
|
||||
* @param string $manifestName manifest 파일명
|
||||
* @return string|null manifest 파일 경로 또는 null
|
||||
*/
|
||||
public static function findManifest(string $directory, string $manifestName): ?string
|
||||
{
|
||||
// 루트에 있는 경우
|
||||
$rootPath = $directory.'/'.$manifestName;
|
||||
if (File::exists($rootPath)) {
|
||||
return $rootPath;
|
||||
}
|
||||
|
||||
// 하위 디렉토리 검색 (1단계만)
|
||||
$directories = File::directories($directory);
|
||||
foreach ($directories as $subDir) {
|
||||
$subPath = $subDir.'/'.$manifestName;
|
||||
if (File::exists($subPath)) {
|
||||
return $subPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 추출된 소스를 _pending 디렉토리로 이동합니다.
|
||||
*
|
||||
* @param string $sourcePath 소스 디렉토리 경로
|
||||
* @param string $pendingBasePath _pending 기본 경로 (예: base_path('modules/_pending'))
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return string 이동된 _pending 경로
|
||||
*/
|
||||
public static function moveToPending(
|
||||
string $sourcePath,
|
||||
string $pendingBasePath,
|
||||
string $identifier
|
||||
): string {
|
||||
$pendingTargetPath = $pendingBasePath.'/'.$identifier;
|
||||
|
||||
if (File::exists($pendingTargetPath)) {
|
||||
File::deleteDirectory($pendingTargetPath);
|
||||
}
|
||||
|
||||
File::ensureDirectoryExists($pendingBasePath);
|
||||
File::moveDirectory($sourcePath, $pendingTargetPath);
|
||||
|
||||
return $pendingTargetPath;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\HookManagerInterface;
|
||||
use App\Models\PermissionHook;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
|
||||
class HookManager implements HookManagerInterface
|
||||
{
|
||||
private static array $hooks = [];
|
||||
private static array $filters = [];
|
||||
private static array $dispatching = [];
|
||||
|
||||
/**
|
||||
* Hook 이벤트를 발생시켜 등록된 콜백들을 실행합니다.
|
||||
*
|
||||
* @param string $hookName Hook 이름
|
||||
* @param mixed ...$args Hook에 전달할 인수들
|
||||
* @return void
|
||||
*/
|
||||
public static function doAction(string $hookName, ...$args): void
|
||||
{
|
||||
// 가드 플래그 설정 (addAction으로 등록된 콜백의 Event::listen 중복 실행 방지)
|
||||
self::$dispatching[$hookName] = true;
|
||||
|
||||
// 등록된 Hook이 있는지 확인
|
||||
if (isset(self::$hooks[$hookName])) {
|
||||
// Hook들을 우선순위에 따라 정렬
|
||||
$hooks = self::$hooks[$hookName];
|
||||
ksort($hooks);
|
||||
|
||||
// 각 Hook을 순차적으로 실행
|
||||
foreach ($hooks as $priority => $callbacks) {
|
||||
foreach ($callbacks as $callback) {
|
||||
call_user_func_array($callback, $args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Laravel 이벤트 시스템에도 전달 (직접 Event::listen으로 등록한 외부 리스너용)
|
||||
Event::dispatch("hook.{$hookName}", $args);
|
||||
|
||||
unset(self::$dispatching[$hookName]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter를 적용하여 데이터를 변환합니다.
|
||||
*
|
||||
* @param string $filterName Filter 이름
|
||||
* @param mixed $value 변환할 원본 값
|
||||
* @param mixed ...$args Filter에 전달할 추가 인수들
|
||||
* @return mixed 변환된 값
|
||||
*/
|
||||
public static function applyFilters(string $filterName, $value, ...$args)
|
||||
{
|
||||
$eventName = "filter.{$filterName}";
|
||||
|
||||
// 등록된 필터가 있는지 확인
|
||||
if (!isset(self::$filters[$filterName])) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// 필터들을 우선순위에 따라 정렬
|
||||
$filters = self::$filters[$filterName];
|
||||
ksort($filters);
|
||||
|
||||
// 각 필터를 순차적으로 적용
|
||||
foreach ($filters as $priority => $callbacks) {
|
||||
foreach ($callbacks as $callback) {
|
||||
$value = call_user_func_array($callback, array_merge([$value], $args));
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook 이벤트에 콜백 함수를 등록합니다.
|
||||
*
|
||||
* @param string $hookName Hook 이름
|
||||
* @param callable $callback 실행할 콜백 함수
|
||||
* @param int $priority 실행 우선순위 (기본값: 10)
|
||||
* @return void
|
||||
*/
|
||||
public static function addAction(string $hookName, callable $callback, int $priority = 10): void
|
||||
{
|
||||
if (!isset(self::$hooks[$hookName])) {
|
||||
self::$hooks[$hookName] = [];
|
||||
}
|
||||
|
||||
if (!isset(self::$hooks[$hookName][$priority])) {
|
||||
self::$hooks[$hookName][$priority] = [];
|
||||
}
|
||||
|
||||
self::$hooks[$hookName][$priority][] = $callback;
|
||||
|
||||
// Laravel 이벤트 시스템에도 등록 (가드 래핑으로 doAction 실행 중 중복 방지)
|
||||
Event::listen("hook.{$hookName}", function (...$args) use ($hookName, $callback) {
|
||||
if (!empty(self::$dispatching[$hookName])) {
|
||||
return; // doAction() 내부 배열에서 이미 실행됨 → 스킵
|
||||
}
|
||||
call_user_func_array($callback, $args);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter에 콜백 함수를 등록합니다.
|
||||
*
|
||||
* @param string $filterName Filter 이름
|
||||
* @param callable $callback 실행할 콜백 함수
|
||||
* @param int $priority 실행 우선순위 (기본값: 10)
|
||||
* @return void
|
||||
*/
|
||||
public static function addFilter(string $filterName, callable $callback, int $priority = 10): void
|
||||
{
|
||||
if (!isset(self::$filters[$filterName])) {
|
||||
self::$filters[$filterName] = [];
|
||||
}
|
||||
|
||||
if (!isset(self::$filters[$filterName][$priority])) {
|
||||
self::$filters[$filterName][$priority] = [];
|
||||
}
|
||||
|
||||
self::$filters[$filterName][$priority][] = $callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook 이벤트에서 콜백 함수를 제거합니다.
|
||||
*
|
||||
* @param string $hookName Hook 이름
|
||||
* @param callable $callback 제거할 콜백 함수
|
||||
* @return void
|
||||
*/
|
||||
public static function removeAction(string $hookName, callable $callback): void
|
||||
{
|
||||
if (isset(self::$hooks[$hookName])) {
|
||||
foreach (self::$hooks[$hookName] as $priority => $callbacks) {
|
||||
$key = array_search($callback, $callbacks, true);
|
||||
if ($key !== false) {
|
||||
unset(self::$hooks[$hookName][$priority][$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Laravel 이벤트 시스템에서도 제거
|
||||
Event::forget("hook.{$hookName}");
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter에서 콜백 함수를 제거합니다.
|
||||
*
|
||||
* @param string $filterName Filter 이름
|
||||
* @param callable $callback 제거할 콜백 함수
|
||||
* @return void
|
||||
*/
|
||||
public static function removeFilter(string $filterName, callable $callback): void
|
||||
{
|
||||
if (isset(self::$filters[$filterName])) {
|
||||
foreach (self::$filters[$filterName] as $priority => $callbacks) {
|
||||
$key = array_search($callback, $callbacks, true);
|
||||
if ($key !== false) {
|
||||
unset(self::$filters[$filterName][$priority][$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록된 모든 Hook 목록을 조회합니다.
|
||||
*
|
||||
* @return array Hook 목록 배열
|
||||
*/
|
||||
public static function getHooks(): array
|
||||
{
|
||||
return self::$hooks;
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록된 모든 Filter 목록을 조회합니다.
|
||||
*
|
||||
* @return array Filter 목록 배열
|
||||
*/
|
||||
public static function getFilters(): array
|
||||
{
|
||||
return self::$filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 Hook에 등록된 모든 콜백을 제거합니다.
|
||||
*
|
||||
* @param string $hookName Hook 이름
|
||||
* @return void
|
||||
*/
|
||||
public static function clearAction(string $hookName): void
|
||||
{
|
||||
if (isset(self::$hooks[$hookName])) {
|
||||
unset(self::$hooks[$hookName]);
|
||||
}
|
||||
|
||||
// Laravel 이벤트 시스템에서도 제거
|
||||
Event::forget("hook.{$hookName}");
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 Filter에 등록된 모든 콜백을 제거합니다.
|
||||
*
|
||||
* @param string $filterName Filter 이름
|
||||
* @return void
|
||||
*/
|
||||
public static function clearFilter(string $filterName): void
|
||||
{
|
||||
if (isset(self::$filters[$filterName])) {
|
||||
unset(self::$filters[$filterName]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 환경에서 등록된 모든 Hook과 Filter를 초기화합니다.
|
||||
*
|
||||
* 주의: 이 메서드는 테스트 환경에서만 사용해야 합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function resetAll(): void
|
||||
{
|
||||
self::$hooks = [];
|
||||
self::$filters = [];
|
||||
self::$dispatching = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 훅 실행 전 권한 체크
|
||||
*
|
||||
* permission_hooks 테이블에 해당 훅이 매핑되어 있으면
|
||||
* 현재 사용자가 해당 권한을 보유하고 있는지 확인합니다.
|
||||
*
|
||||
* @param string $hookName 훅 이름
|
||||
* @param User|null $user 사용자 (null이면 현재 인증된 사용자)
|
||||
* @return void
|
||||
* @throws AuthorizationException 권한이 없는 경우
|
||||
*/
|
||||
public static function checkHookPermission(string $hookName, ?User $user = null): void
|
||||
{
|
||||
// 훅에 권한 매핑이 없으면 모든 사용자 허용
|
||||
if (!PermissionHook::hasPermissionMapping($hookName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 사용자 결정 (파라미터 우선, 없으면 현재 인증 사용자)
|
||||
$user = $user ?? Auth::user();
|
||||
|
||||
// 비인증 사용자는 권한 매핑된 훅 접근 불가
|
||||
if (!$user) {
|
||||
throw new AuthorizationException(__('auth.unauthorized'));
|
||||
}
|
||||
|
||||
// 관리자는 모든 권한 보유
|
||||
if ($user->isAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 사용자가 훅에 매핑된 권한 중 하나라도 보유하는지 확인
|
||||
$requiredPermissions = PermissionHook::getPermissionsForHook($hookName);
|
||||
|
||||
foreach ($requiredPermissions as $permission) {
|
||||
if ($user->hasPermission($permission->identifier)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new AuthorizationException(__('auth.unauthorized'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 훅 실행 전 권한 체크 후 Action 실행
|
||||
*
|
||||
* @param string $hookName 훅 이름
|
||||
* @param User|null $user 권한 체크 대상 사용자
|
||||
* @param mixed ...$args 훅에 전달할 인자
|
||||
* @return void
|
||||
* @throws AuthorizationException 권한이 없는 경우
|
||||
*/
|
||||
public static function doActionWithPermission(string $hookName, ?User $user = null, ...$args): void
|
||||
{
|
||||
static::checkHookPermission($hookName, $user);
|
||||
static::doAction($hookName, ...$args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 훅 실행 전 권한 체크 후 Filter 실행
|
||||
*
|
||||
* @param string $hookName 훅 이름
|
||||
* @param User|null $user 권한 체크 대상 사용자
|
||||
* @param mixed $value 필터링할 값
|
||||
* @param mixed ...$args 필터에 전달할 추가 인자
|
||||
* @return mixed 필터링된 값
|
||||
* @throws AuthorizationException 권한이 없는 경우
|
||||
*/
|
||||
public static function applyFiltersWithPermission(string $hookName, ?User $user = null, mixed $value = null, ...$args): mixed
|
||||
{
|
||||
static::checkHookPermission($hookName, $user);
|
||||
|
||||
return static::applyFilters($hookName, $value, ...$args);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Storage;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* 코어 스토리지 드라이버
|
||||
*
|
||||
* 코어 서비스(AttachmentService 등)에서 사용하는 파일 저장소를 제공합니다.
|
||||
* 모듈/플러그인과 달리 identifier 없이 {category}/{path} 경로 패턴을 사용합니다.
|
||||
*/
|
||||
class CoreStorageDriver implements StorageInterface
|
||||
{
|
||||
/**
|
||||
* 사용할 디스크 이름
|
||||
*/
|
||||
private string $disk;
|
||||
|
||||
/**
|
||||
* CoreStorageDriver 생성자
|
||||
*
|
||||
* @param string $disk 디스크 이름 (예: local, public, s3)
|
||||
*/
|
||||
public function __construct(string $disk = 'local')
|
||||
{
|
||||
$this->disk = $disk;
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리와 경로를 조합하여 전체 경로를 생성합니다.
|
||||
*
|
||||
* @param string $category 카테고리 (빈 문자열이면 경로만 사용)
|
||||
* @param string $path 상대 경로
|
||||
* @return string 전체 경로 ({category}/{path} 또는 {path})
|
||||
*/
|
||||
private function resolvePath(string $category, string $path): string
|
||||
{
|
||||
if (empty($category)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
if (empty($path)) {
|
||||
return $category;
|
||||
}
|
||||
|
||||
return "{$category}/{$path}";
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function put(string $category, string $path, mixed $content): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->put($fullPath, $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $category, string $path): ?string
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->get($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function exists(string $category, string $path): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->exists($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $category, string $path): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->delete($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function url(string $category, string $path): ?string
|
||||
{
|
||||
if ($this->disk !== 'public') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->url($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function files(string $category, string $directory = ''): array
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $directory);
|
||||
|
||||
return Storage::disk($this->disk)->files($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteDirectory(string $category, string $directory = ''): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $directory);
|
||||
|
||||
return Storage::disk($this->disk)->deleteDirectory($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getBasePath(string $category): string
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, '');
|
||||
|
||||
return Storage::disk($this->disk)->path($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getDisk(): string
|
||||
{
|
||||
return $this->disk;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteAll(string $category): bool
|
||||
{
|
||||
return $this->deleteDirectory($category, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function response(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->response($fullPath, $filename, $headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function withDisk(string $disk): static
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->disk = $disk;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function download(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->download($fullPath, $filename, $headers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Storage;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* 모듈 스토리지 드라이버
|
||||
*
|
||||
* 모듈별로 격리된 파일 저장소를 제공합니다.
|
||||
* 경로 패턴: storage/app/modules/{identifier}/{category}/{path}
|
||||
*/
|
||||
class ModuleStorageDriver implements StorageInterface
|
||||
{
|
||||
/**
|
||||
* 모듈 식별자
|
||||
*/
|
||||
private string $identifier;
|
||||
|
||||
/**
|
||||
* 사용할 디스크 이름
|
||||
*/
|
||||
private string $disk;
|
||||
|
||||
/**
|
||||
* ModuleStorageDriver 생성자
|
||||
*
|
||||
* @param string $identifier 모듈 식별자 (예: sirsoft-board)
|
||||
* @param string $disk 디스크 이름 (예: local, public, s3)
|
||||
*/
|
||||
public function __construct(string $identifier, string $disk = 'local')
|
||||
{
|
||||
$this->identifier = $identifier;
|
||||
$this->disk = $disk;
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리와 경로를 조합하여 전체 경로를 생성합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 상대 경로
|
||||
* @return string 전체 경로 ({identifier}/{category}/{path})
|
||||
*/
|
||||
private function resolvePath(string $category, string $path): string
|
||||
{
|
||||
$basePath = "{$this->identifier}/{$category}";
|
||||
|
||||
if (empty($path)) {
|
||||
return $basePath;
|
||||
}
|
||||
|
||||
return "{$basePath}/{$path}";
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function put(string $category, string $path, mixed $content): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->put($fullPath, $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $category, string $path): ?string
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->get($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function exists(string $category, string $path): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->exists($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $category, string $path): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->delete($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function url(string $category, string $path): ?string
|
||||
{
|
||||
// public disk인 경우에만 직접 URL 반환
|
||||
if ($this->disk !== 'public') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->url($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function files(string $category, string $directory = ''): array
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $directory);
|
||||
|
||||
return Storage::disk($this->disk)->files($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteDirectory(string $category, string $directory = ''): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $directory);
|
||||
|
||||
return Storage::disk($this->disk)->deleteDirectory($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getBasePath(string $category): string
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, '');
|
||||
|
||||
return Storage::disk($this->disk)->path($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getDisk(): string
|
||||
{
|
||||
return $this->disk;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteAll(string $category): bool
|
||||
{
|
||||
return $this->deleteDirectory($category, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function response(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->response($fullPath, $filename, $headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function withDisk(string $disk): static
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->disk = $disk;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function download(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->download($fullPath, $filename, $headers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Storage;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* 플러그인 스토리지 드라이버
|
||||
*
|
||||
* 플러그인별로 격리된 파일 저장소를 제공합니다.
|
||||
* 경로 패턴: storage/app/plugins/{identifier}/{category}/{path}
|
||||
*/
|
||||
class PluginStorageDriver implements StorageInterface
|
||||
{
|
||||
/**
|
||||
* 플러그인 식별자
|
||||
*/
|
||||
private string $identifier;
|
||||
|
||||
/**
|
||||
* 사용할 디스크 이름
|
||||
*/
|
||||
private string $disk;
|
||||
|
||||
/**
|
||||
* PluginStorageDriver 생성자
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자 (예: sirsoft-payment)
|
||||
* @param string $disk 디스크 이름 (예: local, public, s3)
|
||||
*/
|
||||
public function __construct(string $identifier, string $disk = 'local')
|
||||
{
|
||||
$this->identifier = $identifier;
|
||||
$this->disk = $disk;
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리와 경로를 조합하여 전체 경로를 생성합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 상대 경로
|
||||
* @return string 전체 경로 ({identifier}/{category}/{path})
|
||||
*/
|
||||
private function resolvePath(string $category, string $path): string
|
||||
{
|
||||
$basePath = "{$this->identifier}/{$category}";
|
||||
|
||||
if (empty($path)) {
|
||||
return $basePath;
|
||||
}
|
||||
|
||||
return "{$basePath}/{$path}";
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function put(string $category, string $path, mixed $content): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->put($fullPath, $content);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function get(string $category, string $path): ?string
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->get($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function exists(string $category, string $path): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->exists($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function delete(string $category, string $path): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->delete($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function url(string $category, string $path): ?string
|
||||
{
|
||||
// public disk인 경우에만 직접 URL 반환
|
||||
if ($this->disk !== 'public') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
return Storage::disk($this->disk)->url($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function files(string $category, string $directory = ''): array
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $directory);
|
||||
|
||||
return Storage::disk($this->disk)->files($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteDirectory(string $category, string $directory = ''): bool
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $directory);
|
||||
|
||||
return Storage::disk($this->disk)->deleteDirectory($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getBasePath(string $category): string
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, '');
|
||||
|
||||
return Storage::disk($this->disk)->path($fullPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getDisk(): string
|
||||
{
|
||||
return $this->disk;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function deleteAll(string $category): bool
|
||||
{
|
||||
return $this->deleteDirectory($category, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function response(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->response($fullPath, $filename, $headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function withDisk(string $disk): static
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->disk = $disk;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function download(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse
|
||||
{
|
||||
$fullPath = $this->resolvePath($category, $path);
|
||||
|
||||
if (! Storage::disk($this->disk)->exists($fullPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Storage::disk($this->disk)->download($fullPath, $filename, $headers);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Module;
|
||||
use App\Services\CacheService;
|
||||
|
||||
/**
|
||||
* 모듈 상태 캐시를 관리하는 Trait
|
||||
*
|
||||
* 활성화된 모듈, 설치된 모듈 목록을 캐시하여 DB 조회 오버헤드를 줄입니다.
|
||||
* ModuleManager, ModuleServiceProvider 등에서 사용됩니다.
|
||||
*/
|
||||
trait CachesModuleStatus
|
||||
{
|
||||
/**
|
||||
* 캐시 그룹
|
||||
*/
|
||||
private static string $cacheGroup = 'modules';
|
||||
|
||||
/**
|
||||
* 활성화된 모듈 identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array<string> 활성화된 모듈 identifier 배열
|
||||
*/
|
||||
public static function getActiveModuleIdentifiers(): array
|
||||
{
|
||||
return CacheService::remember(
|
||||
self::$cacheGroup,
|
||||
'active_identifiers',
|
||||
fn () => Module::where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
null,
|
||||
'modules'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 모듈 (active + inactive) identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array<string> 설치된 모듈 identifier 배열
|
||||
*/
|
||||
public static function getInstalledModuleIdentifiers(): array
|
||||
{
|
||||
return CacheService::remember(
|
||||
self::$cacheGroup,
|
||||
'installed_identifiers',
|
||||
fn () => Module::whereIn('status', [
|
||||
ExtensionStatus::Active->value,
|
||||
ExtensionStatus::Inactive->value,
|
||||
])->pluck('identifier')->toArray(),
|
||||
null,
|
||||
'modules'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 상태 캐시를 무효화합니다.
|
||||
* 모듈 상태 변경 시 (install, activate, deactivate, uninstall) 호출해야 합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function invalidateModuleStatusCache(): void
|
||||
{
|
||||
CacheService::forgetMany(self::$cacheGroup, [
|
||||
'active_identifiers',
|
||||
'installed_identifiers',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Plugin;
|
||||
use App\Services\CacheService;
|
||||
|
||||
/**
|
||||
* 플러그인 상태 캐시를 관리하는 Trait
|
||||
*
|
||||
* 활성화된 플러그인, 설치된 플러그인 목록을 캐시하여 DB 조회 오버헤드를 줄입니다.
|
||||
* PluginManager, PluginServiceProvider 등에서 사용됩니다.
|
||||
*/
|
||||
trait CachesPluginStatus
|
||||
{
|
||||
/**
|
||||
* 캐시 그룹
|
||||
*/
|
||||
private static string $pluginCacheGroup = 'plugins';
|
||||
|
||||
/**
|
||||
* 활성화된 플러그인 identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array<string> 활성화된 플러그인 identifier 배열
|
||||
*/
|
||||
public static function getActivePluginIdentifiers(): array
|
||||
{
|
||||
return CacheService::remember(
|
||||
self::$pluginCacheGroup,
|
||||
'active_identifiers',
|
||||
fn () => Plugin::where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
null,
|
||||
'plugins'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 플러그인 (active + inactive) identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array<string> 설치된 플러그인 identifier 배열
|
||||
*/
|
||||
public static function getInstalledPluginIdentifiers(): array
|
||||
{
|
||||
return CacheService::remember(
|
||||
self::$pluginCacheGroup,
|
||||
'installed_identifiers',
|
||||
fn () => Plugin::whereIn('status', [
|
||||
ExtensionStatus::Active->value,
|
||||
ExtensionStatus::Inactive->value,
|
||||
])->pluck('identifier')->toArray(),
|
||||
null,
|
||||
'plugins'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 상태 캐시를 무효화합니다.
|
||||
* 플러그인 상태 변경 시 (install, activate, deactivate, uninstall) 호출해야 합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function invalidatePluginStatusCache(): void
|
||||
{
|
||||
CacheService::forgetMany(self::$pluginCacheGroup, [
|
||||
'active_identifiers',
|
||||
'installed_identifiers',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\Template;
|
||||
use App\Services\CacheService;
|
||||
|
||||
/**
|
||||
* 템플릿 상태 캐시를 관리하는 Trait
|
||||
*
|
||||
* 활성화된 템플릿, 설치된 템플릿 목록을 캐시하여 DB 조회 오버헤드를 줄입니다.
|
||||
* TemplateManager, TemplateServiceProvider 등에서 사용됩니다.
|
||||
*/
|
||||
trait CachesTemplateStatus
|
||||
{
|
||||
/**
|
||||
* 캐시 그룹
|
||||
*/
|
||||
private static string $templateCacheGroup = 'templates';
|
||||
|
||||
/**
|
||||
* 활성화된 템플릿 identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array<string> 활성화된 템플릿 identifier 배열
|
||||
*/
|
||||
public static function getActiveTemplateIdentifiers(): array
|
||||
{
|
||||
return CacheService::remember(
|
||||
self::$templateCacheGroup,
|
||||
'active_identifiers',
|
||||
fn () => Template::where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
null,
|
||||
'templates'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 타입의 활성화된 템플릿 identifier 목록을 조회합니다.
|
||||
*
|
||||
* @param string $type 템플릿 타입 (admin, user)
|
||||
* @return array<string> 활성화된 템플릿 identifier 배열
|
||||
*/
|
||||
public static function getActiveTemplateIdentifiersByType(string $type): array
|
||||
{
|
||||
return CacheService::remember(
|
||||
self::$templateCacheGroup,
|
||||
"active_identifiers_{$type}",
|
||||
fn () => Template::where('status', ExtensionStatus::Active->value)
|
||||
->where('type', $type)
|
||||
->pluck('identifier')
|
||||
->toArray(),
|
||||
null,
|
||||
'templates'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 템플릿 (active + inactive) identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array<string> 설치된 템플릿 identifier 배열
|
||||
*/
|
||||
public static function getInstalledTemplateIdentifiers(): array
|
||||
{
|
||||
return CacheService::remember(
|
||||
self::$templateCacheGroup,
|
||||
'installed_identifiers',
|
||||
fn () => Template::whereIn('status', [
|
||||
ExtensionStatus::Active->value,
|
||||
ExtensionStatus::Inactive->value,
|
||||
])->pluck('identifier')->toArray(),
|
||||
null,
|
||||
'templates'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 상태 캐시를 무효화합니다.
|
||||
* 템플릿 상태 변경 시 (install, activate, deactivate, uninstall) 호출해야 합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function invalidateTemplateStatusCache(): void
|
||||
{
|
||||
CacheService::forgetMany(self::$templateCacheGroup, [
|
||||
'active_identifiers',
|
||||
'active_identifiers_admin',
|
||||
'active_identifiers_user',
|
||||
'installed_identifiers',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 템플릿 관련 캐시를 무효화하는 기능을 제공하는 트레이트.
|
||||
*
|
||||
* 모듈, 플러그인 등의 확장 기능이 활성화/비활성화될 때
|
||||
* 캐시 버전을 증가시켜 프론트엔드가 새로운 캐시 키로 요청하도록 합니다.
|
||||
* 이전 버전 캐시는 TTL로 자연 만료됩니다.
|
||||
*/
|
||||
trait ClearsTemplateCaches
|
||||
{
|
||||
/**
|
||||
* 확장 기능 캐시 버전을 증가시킵니다.
|
||||
*
|
||||
* 모듈/플러그인/템플릿 활성화/비활성화/설치/삭제 시 호출되어
|
||||
* 프론트엔드가 새로운 캐시 버전으로 API를 요청하도록 합니다.
|
||||
* 이전 버전 캐시는 TTL로 자연 만료됩니다.
|
||||
*/
|
||||
protected function incrementExtensionCacheVersion(): void
|
||||
{
|
||||
try {
|
||||
$newVersion = time();
|
||||
Cache::put('extension_cache_version', $newVersion);
|
||||
|
||||
Log::info('확장 기능 캐시 버전 증가', [
|
||||
'new_version' => $newVersion,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('확장 기능 캐시 버전 증가 중 오류', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 확장 기능 캐시 버전을 반환합니다.
|
||||
*
|
||||
* @return int 캐시 버전 (타임스탬프) 또는 0 (미설정 시)
|
||||
*/
|
||||
public static function getExtensionCacheVersion(): int
|
||||
{
|
||||
return (int) Cache::get('extension_cache_version', 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 템플릿의 언어 캐시를 무효화합니다.
|
||||
*
|
||||
* 버전 있는 캐시는 incrementExtensionCacheVersion()으로 무효화됩니다.
|
||||
* 이전 버전 캐시는 TTL로 자연 만료됩니다.
|
||||
* 이 메서드는 호출 호환성 유지용입니다.
|
||||
*/
|
||||
protected function clearAllTemplateLanguageCaches(): void
|
||||
{
|
||||
Log::info('템플릿 언어 캐시 무효화 (캐시 버전 증가로 처리)');
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 템플릿의 routes 캐시를 무효화합니다.
|
||||
*
|
||||
* 버전 있는 캐시는 incrementExtensionCacheVersion()으로 무효화됩니다.
|
||||
* 이전 버전 캐시는 TTL로 자연 만료됩니다.
|
||||
* 이 메서드는 호출 호환성 유지용입니다.
|
||||
*/
|
||||
protected function clearAllTemplateRoutesCaches(): void
|
||||
{
|
||||
Log::info('템플릿 routes 캐시 무효화 (캐시 버전 증가로 처리)');
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 템플릿의 레이아웃 캐시를 무효화합니다.
|
||||
*
|
||||
* 버전 있는 캐시는 incrementExtensionCacheVersion()으로 무효화됩니다.
|
||||
* 이전 버전 캐시는 TTL로 자연 만료됩니다.
|
||||
* 이 메서드는 호출 호환성 유지용입니다.
|
||||
*/
|
||||
protected function clearAllTemplateLayoutCaches(): void
|
||||
{
|
||||
Log::info('템플릿 레이아웃 캐시 무효화 (캐시 버전 증가로 처리)');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 모듈/플러그인 삭제 시 삭제될 데이터 정보를 조회하는 Trait
|
||||
*
|
||||
* 마이그레이션 파일에서 테이블 목록 추출, 테이블 용량 조회(DB 드라이버별 분기),
|
||||
* 스토리지 디렉토리 용량 계산 등의 공통 유틸리티를 제공합니다.
|
||||
*
|
||||
* ModuleManager, PluginManager에서 사용됩니다.
|
||||
*/
|
||||
trait InspectsUninstallData
|
||||
{
|
||||
/**
|
||||
* 마이그레이션 파일들에서 생성하는 테이블 이름을 추출합니다.
|
||||
*
|
||||
* @param array $migrationPaths 마이그레이션 디렉토리 경로 배열
|
||||
* @return array<string> 테이블 이름 배열
|
||||
*/
|
||||
protected function extractTablesFromMigrations(array $migrationPaths): array
|
||||
{
|
||||
$tables = [];
|
||||
|
||||
foreach ($migrationPaths as $migrationPath) {
|
||||
$migrationFiles = glob($migrationPath.'/*.php');
|
||||
if (empty($migrationFiles)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($migrationFiles as $filePath) {
|
||||
try {
|
||||
$content = File::get($filePath);
|
||||
if (preg_match_all('/Schema::create\s*\(\s*[\'"]([a-zA-Z0-9_]+)[\'"]/', $content, $matches)) {
|
||||
$tables = array_merge($tables, $matches[1]);
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// 개별 파일 읽기 실패 시 건너뜀
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_unique($tables);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테이블 목록의 용량 정보를 조회합니다.
|
||||
*
|
||||
* DB 드라이버별 분기 처리:
|
||||
* - MySQL/MariaDB: information_schema.TABLES 조회
|
||||
* - 기타(SQLite, PostgreSQL 등): 테이블 존재 여부만 확인, 용량은 null 반환
|
||||
*
|
||||
* @param array<string> $tables 테이블 이름 배열
|
||||
* @return array<array{name: string, size_bytes: int|null, size_formatted: string}> 테이블 용량 정보
|
||||
*/
|
||||
protected function getTablesSizeInfo(array $tables): array
|
||||
{
|
||||
if (empty($tables)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$driver = DB::getDriverName();
|
||||
|
||||
if ($driver === 'mysql' || $driver === 'mariadb') {
|
||||
return $this->getTablesSizeInfoMysql($tables);
|
||||
}
|
||||
|
||||
// TODO: PostgreSQL, SQLite 등 다른 DB 드라이버 용량 조회 지원
|
||||
return $this->getTablesSizeInfoFallback($tables);
|
||||
}
|
||||
|
||||
/**
|
||||
* MySQL/MariaDB에서 테이블 용량 정보를 조회합니다.
|
||||
*
|
||||
* @param array<string> $tables 테이블 이름 배열
|
||||
* @return array<array{name: string, size_bytes: int, size_formatted: string}> 테이블 용량 정보
|
||||
*/
|
||||
protected function getTablesSizeInfoMysql(array $tables): array
|
||||
{
|
||||
$prefix = DB::getTablePrefix();
|
||||
$dbName = DB::getDatabaseName();
|
||||
$result = [];
|
||||
|
||||
foreach ($tables as $table) {
|
||||
$prefixedTable = $prefix.$table;
|
||||
|
||||
try {
|
||||
$row = DB::selectOne(
|
||||
'SELECT (DATA_LENGTH + INDEX_LENGTH) AS size_bytes FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?',
|
||||
[$dbName, $prefixedTable]
|
||||
);
|
||||
|
||||
$sizeBytes = $row ? (int) $row->size_bytes : 0;
|
||||
$result[] = [
|
||||
'name' => $table,
|
||||
'size_bytes' => $sizeBytes,
|
||||
'size_formatted' => $this->formatBytes($sizeBytes),
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
$result[] = [
|
||||
'name' => $table,
|
||||
'size_bytes' => 0,
|
||||
'size_formatted' => '0 B',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 용량 조회를 지원하지 않는 DB에서 테이블 존재 여부만 확인합니다.
|
||||
*
|
||||
* @param array<string> $tables 테이블 이름 배열
|
||||
* @return array<array{name: string, size_bytes: null, size_formatted: string}> 테이블 정보 (용량 null)
|
||||
*/
|
||||
protected function getTablesSizeInfoFallback(array $tables): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($tables as $table) {
|
||||
$exists = Schema::hasTable($table);
|
||||
$result[] = [
|
||||
'name' => $table,
|
||||
'size_bytes' => null,
|
||||
'size_formatted' => $exists ? '-' : '0 B',
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 스토리지 디렉토리의 1-depth 서브디렉토리 용량 정보를 조회합니다.
|
||||
*
|
||||
* @param string $basePath 기본 경로
|
||||
* @return array<array{name: string, size_bytes: int, size_formatted: string}> 디렉토리 용량 정보
|
||||
*/
|
||||
protected function getStorageDirectoriesInfo(string $basePath): array
|
||||
{
|
||||
if (! File::isDirectory($basePath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$directories = File::directories($basePath);
|
||||
|
||||
foreach ($directories as $directory) {
|
||||
$sizeBytes = $this->getDirectorySize($directory);
|
||||
$result[] = [
|
||||
'name' => basename($directory),
|
||||
'size_bytes' => $sizeBytes,
|
||||
'size_formatted' => $this->formatBytes($sizeBytes),
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리의 전체 용량을 계산합니다.
|
||||
*
|
||||
* @param string $directory 디렉토리 경로
|
||||
* @return int 바이트 단위 용량
|
||||
*/
|
||||
protected function getDirectorySize(string $directory): int
|
||||
{
|
||||
$size = 0;
|
||||
|
||||
try {
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS)
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isFile()) {
|
||||
$size += $file->getSize();
|
||||
}
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// 접근 불가 파일 무시
|
||||
}
|
||||
|
||||
return $size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 Composer vendor 디렉토리 정보를 조회합니다.
|
||||
*
|
||||
* vendor/ 디렉토리와 composer.lock 파일의 존재 여부 및 용량을 반환합니다.
|
||||
* 둘 다 존재하지 않으면 null을 반환합니다.
|
||||
*
|
||||
* @param string $type 확장 타입 ('modules' 또는 'plugins')
|
||||
* @param string $dirName 디렉토리명
|
||||
* @return array{items: array, total_size_bytes: int, total_size_formatted: string}|null
|
||||
*/
|
||||
protected function getVendorDirectoryInfo(string $type, string $dirName): ?array
|
||||
{
|
||||
$basePath = base_path("{$type}/{$dirName}");
|
||||
$vendorPath = $basePath.'/vendor';
|
||||
$lockPath = $basePath.'/composer.lock';
|
||||
|
||||
$hasVendor = File::isDirectory($vendorPath);
|
||||
$hasLock = File::exists($lockPath);
|
||||
|
||||
if (! $hasVendor && ! $hasLock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$totalSize = 0;
|
||||
$items = [];
|
||||
|
||||
if ($hasVendor) {
|
||||
$vendorSize = $this->getDirectorySize($vendorPath);
|
||||
$totalSize += $vendorSize;
|
||||
$items[] = [
|
||||
'name' => 'vendor/',
|
||||
'size_bytes' => $vendorSize,
|
||||
'size_formatted' => $this->formatBytes($vendorSize),
|
||||
];
|
||||
}
|
||||
|
||||
if ($hasLock) {
|
||||
$lockSize = File::size($lockPath);
|
||||
$totalSize += $lockSize;
|
||||
$items[] = [
|
||||
'name' => 'composer.lock',
|
||||
'size_bytes' => $lockSize,
|
||||
'size_formatted' => $this->formatBytes($lockSize),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'items' => $items,
|
||||
'total_size_bytes' => $totalSize,
|
||||
'total_size_formatted' => $this->formatBytes($totalSize),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인) 설치 디렉토리 정보를 조회합니다.
|
||||
*
|
||||
* 확장의 루트 디렉토리 경로와 전체 용량을 반환합니다.
|
||||
*
|
||||
* @param string $type 확장 타입 ('modules' 또는 'plugins')
|
||||
* @param string $dirName 디렉토리명
|
||||
* @return array{path: string, size_bytes: int, size_formatted: string}|null
|
||||
*/
|
||||
protected function getExtensionDirectoryInfo(string $type, string $dirName): ?array
|
||||
{
|
||||
$dirPath = base_path("{$type}/{$dirName}");
|
||||
|
||||
if (! File::isDirectory($dirPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = $this->getDirectorySize($dirPath);
|
||||
|
||||
return [
|
||||
'path' => "{$type}/{$dirName}",
|
||||
'size_bytes' => $size,
|
||||
'size_formatted' => $this->formatBytes($size),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 Composer vendor 디렉토리 및 관련 파일을 삭제합니다.
|
||||
*
|
||||
* vendor/ 디렉토리와 composer.lock 파일을 삭제합니다.
|
||||
*
|
||||
* @param string $type 확장 타입 ('modules' 또는 'plugins')
|
||||
* @param string $dirName 디렉토리명
|
||||
*/
|
||||
protected function deleteVendorDirectory(string $type, string $dirName): void
|
||||
{
|
||||
$basePath = base_path("{$type}/{$dirName}");
|
||||
$vendorPath = $basePath.'/vendor';
|
||||
$lockPath = $basePath.'/composer.lock';
|
||||
|
||||
if (File::isDirectory($vendorPath)) {
|
||||
try {
|
||||
File::deleteDirectory($vendorPath);
|
||||
|
||||
Log::info('Composer vendor 디렉토리 삭제 완료', [
|
||||
'type' => $type,
|
||||
'extension' => $dirName,
|
||||
'path' => $vendorPath,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Composer vendor 디렉토리 삭제 실패', [
|
||||
'type' => $type,
|
||||
'extension' => $dirName,
|
||||
'path' => $vendorPath,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (File::exists($lockPath)) {
|
||||
try {
|
||||
File::delete($lockPath);
|
||||
|
||||
Log::info('composer.lock 파일 삭제 완료', [
|
||||
'type' => $type,
|
||||
'extension' => $dirName,
|
||||
'path' => $lockPath,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('composer.lock 파일 삭제 실패', [
|
||||
'type' => $type,
|
||||
'extension' => $dirName,
|
||||
'path' => $lockPath,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 바이트를 사람이 읽을 수 있는 형식으로 변환합니다.
|
||||
*
|
||||
* @param int $bytes 바이트 수
|
||||
* @return string 포맷된 문자열 (예: "1.5 MB")
|
||||
*/
|
||||
protected function formatBytes(int $bytes): string
|
||||
{
|
||||
if ($bytes === 0) {
|
||||
return '0 B';
|
||||
}
|
||||
|
||||
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
$i = (int) floor(log($bytes, 1024));
|
||||
$i = min($i, count($units) - 1);
|
||||
|
||||
return round($bytes / pow(1024, $i), 1).' '.$units[$i];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use App\Contracts\Repositories\LayoutRepositoryInterface;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 레이아웃 캐시 무효화 공통 로직을 제공하는 Trait
|
||||
*
|
||||
* 버전 없는 내부 캐시 키를 능동 삭제합니다:
|
||||
* 1. template.{templateId}.layout.{layoutName} - LayoutService에서 사용
|
||||
* 2. template.{templateId}.layout.{layoutName}.{sourceHash} - 모듈/플러그인 레이아웃
|
||||
*
|
||||
* 버전 포함 캐시 (layout.{identifier}.{name}.v{version})는
|
||||
* incrementExtensionCacheVersion() + TTL로 무효화됩니다.
|
||||
* 레이아웃 내용 편집 시에만 현재 버전 키를 능동 삭제합니다.
|
||||
*
|
||||
* 이 Trait를 사용하는 클래스는 반드시 다음 속성/메서드를 제공해야 합니다:
|
||||
* - $layoutRepository: LayoutRepositoryInterface 인스턴스
|
||||
*
|
||||
* @property LayoutRepositoryInterface $layoutRepository
|
||||
*/
|
||||
trait InvalidatesLayoutCache
|
||||
{
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 레이아웃 캐시를 무효화합니다.
|
||||
*
|
||||
* @param string $extensionIdentifier 확장 식별자 (모듈 또는 플러그인)
|
||||
* @param string $extensionType 확장 타입 ('module' 또는 'plugin')
|
||||
*/
|
||||
protected function invalidateExtensionLayoutCache(string $extensionIdentifier, string $extensionType = 'module'): void
|
||||
{
|
||||
try {
|
||||
// 확장 타입에 따라 올바른 소스 타입으로 레이아웃 조회
|
||||
$sourceType = $extensionType === 'plugin' ? LayoutSourceType::Plugin : LayoutSourceType::Module;
|
||||
$extensionLayouts = $this->layoutRepository->getBySourceIdentifier($extensionIdentifier, $sourceType);
|
||||
|
||||
foreach ($extensionLayouts as $layout) {
|
||||
// 레이아웃에 연결된 템플릿 식별자 조회
|
||||
$templateIdentifier = $layout->template?->identifier ?? '';
|
||||
$this->forgetLayoutCacheKeys($layout, $templateIdentifier);
|
||||
}
|
||||
|
||||
Log::info("{$extensionType} 레이아웃 캐시 무효화 완료: {$extensionIdentifier}");
|
||||
} catch (\Exception $e) {
|
||||
Log::warning("레이아웃 캐시 무효화 중 오류: {$extensionIdentifier}", [
|
||||
'type' => $extensionType,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿의 레이아웃 캐시를 무효화합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $templateIdentifier 템플릿 식별자 (PublicLayoutController 캐시 삭제에 필요)
|
||||
*/
|
||||
protected function invalidateTemplateLayoutCache(int $templateId, string $templateIdentifier = ''): void
|
||||
{
|
||||
try {
|
||||
// 개별 레이아웃 캐시 삭제
|
||||
$layouts = $this->layoutRepository->getByTemplateId($templateId);
|
||||
|
||||
foreach ($layouts as $layout) {
|
||||
$this->forgetLayoutCacheKeys($layout, $templateIdentifier);
|
||||
}
|
||||
|
||||
if ($templateIdentifier) {
|
||||
Log::info("템플릿 레이아웃 캐시 무효화 완료: {$templateIdentifier}");
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('레이아웃 캐시 무효화 중 오류', [
|
||||
'template_id' => $templateId,
|
||||
'template_identifier' => $templateIdentifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 레이아웃의 캐시 키를 삭제합니다.
|
||||
*
|
||||
* 버전 없는 내부 캐시는 능동 삭제합니다.
|
||||
* 버전 포함 PublicLayoutController 캐시는 현재 버전 키만 삭제합니다
|
||||
* (레이아웃 내용 편집 시 버전 변경 없이 내용만 바뀌는 경우에 필요).
|
||||
*
|
||||
* @param object $layout 레이아웃 모델 (template_id, name, source_type, source_identifier 필드 필요)
|
||||
* @param string $templateIdentifier 템플릿 식별자 (PublicLayoutController 캐시 삭제에 필요)
|
||||
*/
|
||||
protected function forgetLayoutCacheKeys(object $layout, string $templateIdentifier = ''): void
|
||||
{
|
||||
// 1. LayoutService 내부 캐시 (버전 없음 → 능동 삭제)
|
||||
Cache::forget("template.{$layout->template_id}.layout.{$layout->name}");
|
||||
|
||||
// 2. 소스 해시 포함 키 (버전 없음 → 능동 삭제)
|
||||
if ($layout->source_type && $layout->source_identifier) {
|
||||
$sourceHash = md5($layout->source_type->value.$layout->source_identifier);
|
||||
Cache::forget("template.{$layout->template_id}.layout.{$layout->name}.{$sourceHash}");
|
||||
}
|
||||
|
||||
// 3. PublicLayoutController 캐시 (버전 포함)
|
||||
// 레이아웃 내용 편집 시 현재 버전 키 삭제 (버전 변경 없이 내용만 바뀜)
|
||||
if ($templateIdentifier) {
|
||||
$cacheVersion = (int) Cache::get('extension_cache_version', 0);
|
||||
Cache::forget("layout.{$templateIdentifier}.{$layout->name}.v{$cacheVersion}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 캐시 키를 생성합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param string|null $sourceType 소스 타입 (선택)
|
||||
* @param string|null $sourceIdentifier 소스 식별자 (선택)
|
||||
* @return string 캐시 키
|
||||
*/
|
||||
protected function buildLayoutCacheKey(
|
||||
int $templateId,
|
||||
string $layoutName,
|
||||
?string $sourceType = null,
|
||||
?string $sourceIdentifier = null
|
||||
): string {
|
||||
$baseKey = "template.{$templateId}.layout.{$layoutName}";
|
||||
|
||||
if ($sourceType && $sourceIdentifier) {
|
||||
$sourceHash = md5($sourceType.$sourceIdentifier);
|
||||
|
||||
return "{$baseKey}.{$sourceHash}";
|
||||
}
|
||||
|
||||
return $baseKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Services\LayoutExtensionService;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 갱신 공통 로직을 제공하는 Trait
|
||||
*
|
||||
* 모듈과 플러그인의 레이아웃 확장(extensions) 파일을 파일 시스템에서 읽어
|
||||
* DB에 동기화하는 공통 로직을 제공합니다.
|
||||
*
|
||||
* 이 Trait를 사용하는 클래스는 반드시 다음 속성을 제공해야 합니다:
|
||||
* - $layoutExtensionService: LayoutExtensionService 인스턴스
|
||||
*
|
||||
* @property LayoutExtensionService $layoutExtensionService
|
||||
*/
|
||||
trait RefreshesLayoutExtensions
|
||||
{
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 레이아웃 확장을 파일에서 다시 읽어 DB에 갱신합니다.
|
||||
*
|
||||
* @param ModuleInterface|PluginInterface $extension 모듈 또는 플러그인 인스턴스
|
||||
* @param Collection $adminTemplates admin 템플릿 컬렉션
|
||||
* @param LayoutSourceType $sourceType 소스 타입 (Module 또는 Plugin)
|
||||
* @return array{refreshed: int, created: int, updated: int, deleted: int} 갱신 통계
|
||||
*/
|
||||
protected function refreshExtensionLayoutExtensions(
|
||||
ModuleInterface|PluginInterface $extension,
|
||||
Collection $adminTemplates,
|
||||
LayoutSourceType $sourceType
|
||||
): array {
|
||||
$extensionFiles = $extension->getLayoutExtensions();
|
||||
$identifier = $extension->getIdentifier();
|
||||
$extensionType = $sourceType === LayoutSourceType::Module ? 'module' : 'plugin';
|
||||
$stats = ['refreshed' => 0, 'created' => 0, 'updated' => 0, 'deleted' => 0];
|
||||
|
||||
if ($adminTemplates->isEmpty()) {
|
||||
return $stats;
|
||||
}
|
||||
|
||||
// 파일에서 읽은 확장 데이터 수집 (target_layout 또는 extension_point)
|
||||
$fileExtensions = [];
|
||||
foreach ($extensionFiles as $extensionFile) {
|
||||
try {
|
||||
$content = File::get($extensionFile);
|
||||
$extensionData = json_decode($content, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
Log::error("레이아웃 확장 JSON 파싱 실패: {$extensionFile}", [
|
||||
$extensionType => $identifier,
|
||||
'error' => json_last_error_msg(),
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// target_layout (overlay) 또는 extension_point 중 하나가 있어야 함
|
||||
$targetKey = $extensionData['target_layout'] ?? $extensionData['extension_point'] ?? null;
|
||||
if ($targetKey) {
|
||||
$fileExtensions[$targetKey] = $extensionData;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
Log::error("레이아웃 확장 파일 읽기 실패: {$extensionFile}", [
|
||||
$extensionType => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// 각 admin 템플릿에 대해 확장 동기화
|
||||
foreach ($adminTemplates as $template) {
|
||||
// 파일에서 읽은 확장 등록/업데이트
|
||||
foreach ($fileExtensions as $targetKey => $extensionData) {
|
||||
try {
|
||||
$result = $this->layoutExtensionService->registerExtension(
|
||||
$extensionData,
|
||||
$sourceType,
|
||||
$identifier,
|
||||
$template->id
|
||||
);
|
||||
|
||||
if ($result === 'created') {
|
||||
$stats['created']++;
|
||||
} elseif ($result === 'updated') {
|
||||
$stats['updated']++;
|
||||
}
|
||||
$stats['refreshed']++;
|
||||
} catch (\Exception $e) {
|
||||
Log::error("레이아웃 확장 갱신 실패: {$targetKey}", [
|
||||
$extensionType => $identifier,
|
||||
'template' => $template->identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($stats['refreshed'] > 0) {
|
||||
$typeLabel = $sourceType === LayoutSourceType::Module ? '모듈' : '플러그인';
|
||||
Log::info("{$typeLabel} 레이아웃 확장 갱신 완료", [
|
||||
$extensionType => $identifier,
|
||||
'created' => $stats['created'],
|
||||
'updated' => $stats['updated'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $stats;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
/**
|
||||
* 다국어 파일의 $partial 디렉티브를 해석하는 Trait
|
||||
*
|
||||
* 레이아웃 시스템의 partial 패턴과 유사하게 다국어 파일을
|
||||
* 여러 개의 fragment 파일로 분할하고 런타임에 병합합니다.
|
||||
*/
|
||||
trait ResolvesLanguageFragments
|
||||
{
|
||||
/**
|
||||
* 순환 참조 감지를 위한 스택
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
private array $fragmentStack = [];
|
||||
|
||||
/**
|
||||
* 최대 중첩 깊이
|
||||
*/
|
||||
private const MAX_FRAGMENT_DEPTH = 10;
|
||||
|
||||
/**
|
||||
* 다국어 데이터에서 $partial 디렉티브를 해석합니다.
|
||||
*
|
||||
* @param array $data 다국어 데이터
|
||||
* @param string $basePath 기준 경로 (fragments 디렉토리 포함)
|
||||
* @param int $depth 현재 깊이
|
||||
* @return array 해석된 데이터
|
||||
*
|
||||
* @throws \RuntimeException 최대 깊이 초과 시
|
||||
*/
|
||||
protected function resolveLanguageFragments(array $data, string $basePath, int $depth = 0): array
|
||||
{
|
||||
if ($depth > self::MAX_FRAGMENT_DEPTH) {
|
||||
throw new \RuntimeException("다국어 fragment 최대 깊이(10) 초과: {$basePath}");
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
if (isset($value['$partial'])) {
|
||||
// $partial 디렉티브 처리
|
||||
$fragmentPath = $basePath . '/' . $value['$partial'];
|
||||
$resolved[$key] = $this->loadLanguageFragment($fragmentPath, $basePath, $depth);
|
||||
} else {
|
||||
// 재귀적으로 하위 배열 처리
|
||||
$resolved[$key] = $this->resolveLanguageFragments($value, $basePath, $depth);
|
||||
}
|
||||
} else {
|
||||
$resolved[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fragment 파일을 로드합니다.
|
||||
*
|
||||
* @param string $fragmentPath fragment 파일 경로
|
||||
* @param string $basePath 기준 경로
|
||||
* @param int $depth 현재 깊이
|
||||
* @return array fragment 데이터
|
||||
*
|
||||
* @throws \RuntimeException 순환 참조, 파일 없음, JSON 파싱 오류 시
|
||||
*/
|
||||
private function loadLanguageFragment(string $fragmentPath, string $basePath, int $depth): array
|
||||
{
|
||||
// Windows 경로 정규화
|
||||
$fragmentPath = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $fragmentPath);
|
||||
$normalizedPath = realpath($fragmentPath) ?: $fragmentPath;
|
||||
|
||||
// 순환 참조 검사
|
||||
if (in_array($normalizedPath, $this->fragmentStack)) {
|
||||
$cycle = implode(' -> ', $this->fragmentStack) . ' -> ' . $normalizedPath;
|
||||
throw new \RuntimeException("다국어 fragment 순환 참조 감지: {$cycle}");
|
||||
}
|
||||
|
||||
if (! file_exists($fragmentPath)) {
|
||||
throw new \RuntimeException("다국어 fragment 파일을 찾을 수 없습니다: {$fragmentPath}");
|
||||
}
|
||||
|
||||
$this->fragmentStack[] = $normalizedPath;
|
||||
|
||||
try {
|
||||
$content = file_get_contents($fragmentPath);
|
||||
$fragmentData = json_decode($content, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new \RuntimeException("다국어 fragment JSON 파싱 오류: {$fragmentPath} - " . json_last_error_msg());
|
||||
}
|
||||
|
||||
// fragment 내부의 $partial도 재귀적으로 처리
|
||||
$fragmentBasePath = dirname($fragmentPath);
|
||||
$resolved = $this->resolveLanguageFragments($fragmentData, $fragmentBasePath, $depth + 1);
|
||||
|
||||
return $resolved;
|
||||
} finally {
|
||||
array_pop($this->fragmentStack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fragment 스택을 초기화합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function resetFragmentStack(): void
|
||||
{
|
||||
$this->fragmentStack = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,663 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use App\Exceptions\LayoutIncludeException;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 레이아웃 JSON 파일 검증 및 partial 해석 기능을 제공하는 트레이트.
|
||||
*
|
||||
* 템플릿 설치 및 모듈 활성화 시 레이아웃 파일의 유효성을 검사하고
|
||||
* partial 파일을 병합하는 공통 로직을 제공합니다.
|
||||
*/
|
||||
trait ValidatesLayoutFiles
|
||||
{
|
||||
/**
|
||||
* Partial 순환 참조 추적용 스택
|
||||
*/
|
||||
private array $partialStack = [];
|
||||
|
||||
/**
|
||||
* 레이아웃 파일들을 검증합니다.
|
||||
*
|
||||
* @param string $layoutsPath 레이아웃 디렉토리 경로
|
||||
* @param string $identifier 소스 식별자 (템플릿 또는 모듈)
|
||||
* @param string $sourceType 소스 타입 ('template' 또는 'module')
|
||||
* @param bool $recursive 재귀적으로 하위 디렉토리를 스캔할지 여부
|
||||
* @return array 검증된 레이아웃 데이터 배열
|
||||
*
|
||||
* @throws \Exception 레이아웃 검증 실패 시
|
||||
*/
|
||||
protected function validateLayoutFiles(string $layoutsPath, string $identifier, string $sourceType, bool $recursive = false): array
|
||||
{
|
||||
$validatedLayouts = [];
|
||||
$errors = [];
|
||||
|
||||
if (! File::exists($layoutsPath)) {
|
||||
return $validatedLayouts;
|
||||
}
|
||||
|
||||
// 레이아웃 파일 스캔
|
||||
if ($recursive) {
|
||||
$layoutFiles = $this->scanLayoutFilesRecursively($layoutsPath);
|
||||
} else {
|
||||
// 루트 디렉토리의 JSON 파일만 스캔
|
||||
$layoutFiles = File::glob("{$layoutsPath}/*.json");
|
||||
|
||||
// errors/ 디렉토리만 추가 스캔 (에러 페이지 레이아웃용)
|
||||
$errorsPath = "{$layoutsPath}/errors";
|
||||
if (File::exists($errorsPath)) {
|
||||
$errorLayoutFiles = File::glob("{$errorsPath}/*.json");
|
||||
$layoutFiles = array_merge($layoutFiles, $errorLayoutFiles);
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($layoutFiles)) {
|
||||
return $validatedLayouts;
|
||||
}
|
||||
|
||||
foreach ($layoutFiles as $layoutFile) {
|
||||
$relativePath = str_replace(base_path().DIRECTORY_SEPARATOR, '', $layoutFile);
|
||||
// Windows/Linux 호환을 위해 슬래시로 통일
|
||||
$relativePath = str_replace('\\', '/', $relativePath);
|
||||
|
||||
// JSON 파싱 검증
|
||||
$jsonContent = File::get($layoutFile);
|
||||
$layoutData = json_decode($jsonContent, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$errors[] = $this->formatLayoutValidationError($sourceType, 'json_error', [
|
||||
'file' => $relativePath,
|
||||
'error' => json_last_error_msg(),
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// is_partial이 true면 검증 스킵 (DB 저장 안 함, partial 전용 파일)
|
||||
if (isset($layoutData['meta']['is_partial']) && $layoutData['meta']['is_partial'] === true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 템플릿의 경우 layout_name 필수 검증
|
||||
if ($sourceType === 'template' && ! isset($layoutData['layout_name'])) {
|
||||
$errors[] = $this->formatLayoutValidationError($sourceType, 'missing_name', [
|
||||
'file' => $relativePath,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 레이아웃 이름 결정
|
||||
$layoutName = $layoutData['layout_name'] ?? $this->generateLayoutNameFromPath($layoutsPath, $layoutFile, $identifier);
|
||||
|
||||
// partial 병합 검증
|
||||
$basePath = dirname($layoutFile);
|
||||
$mainDataSources = $layoutData['data_sources'] ?? [];
|
||||
|
||||
try {
|
||||
$layoutData = $this->resolveAllPartials($layoutData, $basePath, 0, $mainDataSources);
|
||||
} catch (LayoutIncludeException $e) {
|
||||
$errors[] = $this->formatLayoutValidationError($sourceType, 'partial_error', [
|
||||
'file' => $relativePath,
|
||||
'error' => $e->getMessage(),
|
||||
'partial' => $e->getIncludePath(),
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// data_sources ID 중복 검증 (현재 레이아웃 내부)
|
||||
$dataSourcesError = $this->validateDataSourceIds($layoutData['data_sources'] ?? [], $relativePath);
|
||||
if ($dataSourcesError) {
|
||||
$errors[] = $dataSourcesError;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 검증 통과한 레이아웃 저장
|
||||
$validatedLayouts[] = [
|
||||
'file' => $layoutFile,
|
||||
'data' => $layoutData,
|
||||
'layout_name' => $layoutName,
|
||||
];
|
||||
}
|
||||
|
||||
// extends 상속 관계에서 data_sources ID 중복 검증
|
||||
$extendsErrors = $this->validateExtendsDataSourceIds($validatedLayouts, $sourceType);
|
||||
$errors = array_merge($errors, $extendsErrors);
|
||||
|
||||
// 오류가 하나라도 있으면 예외 발생
|
||||
if (! empty($errors)) {
|
||||
$errorMessage = $this->formatLayoutValidationError($sourceType, 'validation_failed', [
|
||||
'identifier' => $identifier,
|
||||
'count' => count($errors),
|
||||
]);
|
||||
$errorMessage .= "\n- ".implode("\n- ", $errors);
|
||||
|
||||
throw new \Exception($errorMessage);
|
||||
}
|
||||
|
||||
return $validatedLayouts;
|
||||
}
|
||||
|
||||
/**
|
||||
* extends 상속 관계에서 data_sources ID 중복을 검증합니다.
|
||||
*
|
||||
* 부모 레이아웃과 자식 레이아웃 간의 data_sources ID 중복을 체크합니다.
|
||||
* 설치 시점에는 DB에 레이아웃이 없으므로 파일 시스템 기반으로 검증합니다.
|
||||
*
|
||||
* @param array $validatedLayouts 검증된 레이아웃 배열
|
||||
* @param string $sourceType 소스 타입 ('template' 또는 'module')
|
||||
* @return array 에러 메시지 배열
|
||||
*/
|
||||
protected function validateExtendsDataSourceIds(array $validatedLayouts, string $sourceType): array
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
// layout_name을 키로 하는 맵 생성
|
||||
$layoutMap = [];
|
||||
foreach ($validatedLayouts as $layout) {
|
||||
$layoutMap[$layout['layout_name']] = $layout;
|
||||
}
|
||||
|
||||
// 각 레이아웃의 extends 관계 검증
|
||||
foreach ($validatedLayouts as $layout) {
|
||||
$layoutData = $layout['data'];
|
||||
$layoutName = $layout['layout_name'];
|
||||
|
||||
// extends가 없으면 스킵
|
||||
if (! isset($layoutData['extends'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parentLayoutName = $layoutData['extends'];
|
||||
|
||||
// 부모 레이아웃이 같은 템플릿/모듈 내에 있는지 확인
|
||||
if (! isset($layoutMap[$parentLayoutName])) {
|
||||
// 부모가 다른 소스(DB에 이미 존재)에 있을 수 있으므로 여기서는 스킵
|
||||
// 런타임에 LayoutService에서 검증됨
|
||||
continue;
|
||||
}
|
||||
|
||||
$parentLayout = $layoutMap[$parentLayoutName];
|
||||
$parentDataSources = $parentLayout['data']['data_sources'] ?? [];
|
||||
$childDataSources = $layoutData['data_sources'] ?? [];
|
||||
|
||||
// 부모-자식 간 ID 중복 체크
|
||||
$parentIds = array_column($parentDataSources, 'id');
|
||||
$duplicates = [];
|
||||
|
||||
foreach ($childDataSources as $childDataSource) {
|
||||
if (isset($childDataSource['id']) && in_array($childDataSource['id'], $parentIds, true)) {
|
||||
$duplicates[] = $childDataSource['id'];
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($duplicates)) {
|
||||
$errors[] = __('exceptions.layout.duplicate_data_source_id_extends', [
|
||||
'ids' => implode(', ', array_unique($duplicates)),
|
||||
'child' => $layoutName,
|
||||
'parent' => $parentLayoutName,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* data_sources 배열 내 ID 중복을 검증합니다.
|
||||
*
|
||||
* @param array $dataSources data_sources 배열
|
||||
* @param string $filePath 검증 중인 파일 경로 (에러 메시지용)
|
||||
* @return string|null 에러 메시지 또는 null (중복 없음)
|
||||
*/
|
||||
protected function validateDataSourceIds(array $dataSources, string $filePath): ?string
|
||||
{
|
||||
$ids = [];
|
||||
$duplicates = [];
|
||||
|
||||
foreach ($dataSources as $dataSource) {
|
||||
if (! isset($dataSource['id'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$id = $dataSource['id'];
|
||||
if (in_array($id, $ids, true)) {
|
||||
$duplicates[] = $id;
|
||||
} else {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($duplicates)) {
|
||||
return __('exceptions.layout.duplicate_data_source_id_in_file', [
|
||||
'ids' => implode(', ', array_unique($duplicates)),
|
||||
'file' => $filePath,
|
||||
]);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 검증 에러 메시지를 포맷합니다.
|
||||
*
|
||||
* @param string $sourceType 소스 타입 ('template' 또는 'module')
|
||||
* @param string $errorType 에러 타입
|
||||
* @param array $params 에러 파라미터
|
||||
* @return string 포맷된 에러 메시지
|
||||
*/
|
||||
protected function formatLayoutValidationError(string $sourceType, string $errorType, array $params): string
|
||||
{
|
||||
$translationKey = $sourceType === 'template'
|
||||
? "templates.errors.layout_validation_{$errorType}"
|
||||
: "modules.errors.layout_validation_{$errorType}";
|
||||
|
||||
return __($translationKey, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 파일 경로에서 대상 템플릿 타입을 판별합니다.
|
||||
*
|
||||
* layouts/ 기준 상대 경로의 첫 번째 디렉토리 세그먼트로 판별합니다.
|
||||
* - admin/ → 'admin'
|
||||
* - user/ → 'user'
|
||||
* - 직접 위치한 파일 → null (경고 후 스킵)
|
||||
*
|
||||
* @param string $layoutsPath 레이아웃 기본 경로
|
||||
* @param string $layoutFile 레이아웃 파일 전체 경로
|
||||
* @return string|null 템플릿 타입 ('admin', 'user') 또는 null (스킵 대상)
|
||||
*/
|
||||
protected function getLayoutTargetType(string $layoutsPath, string $layoutFile): ?string
|
||||
{
|
||||
// 슬래시로 통일하여 상대 경로 계산
|
||||
$normalizedBase = rtrim(str_replace('\\', '/', $layoutsPath), '/').'/';
|
||||
$normalizedFile = str_replace('\\', '/', $layoutFile);
|
||||
|
||||
$relativePath = str_replace($normalizedBase, '', $normalizedFile);
|
||||
|
||||
// 첫 번째 디렉토리 세그먼트 추출
|
||||
$segments = explode('/', $relativePath);
|
||||
|
||||
if (count($segments) <= 1) {
|
||||
// 루트에 직접 위치한 파일 (디렉토리 없음)
|
||||
Log::warning("레이아웃 파일이 admin/ 또는 user/ 하위에 위치하지 않아 스킵됩니다: {$layoutFile}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$firstSegment = $segments[0];
|
||||
|
||||
if ($firstSegment === 'admin') {
|
||||
return 'admin';
|
||||
}
|
||||
|
||||
if ($firstSegment === 'user') {
|
||||
return 'user';
|
||||
}
|
||||
|
||||
// admin/user 외 디렉토리 (예: api/)
|
||||
Log::warning("레이아웃 파일이 admin/ 또는 user/ 하위에 위치하지 않아 스킵됩니다: {$layoutFile}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 디렉토리에서 모든 JSON 파일을 재귀적으로 스캔합니다.
|
||||
*
|
||||
* @param string $basePath 스캔할 기본 경로
|
||||
* @return array<string> 레이아웃 파일 경로 배열
|
||||
*/
|
||||
protected function scanLayoutFilesRecursively(string $basePath): array
|
||||
{
|
||||
$files = [];
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($basePath, \RecursiveDirectoryIterator::SKIP_DOTS),
|
||||
\RecursiveIteratorIterator::LEAVES_ONLY
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isFile() && $file->getExtension() === 'json') {
|
||||
$files[] = $file->getPathname();
|
||||
}
|
||||
}
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 경로를 기반으로 레이아웃 이름을 생성합니다.
|
||||
*
|
||||
* @param string $basePath 레이아웃 기본 경로
|
||||
* @param string $filePath 레이아웃 파일 경로
|
||||
* @param string $identifier 소스 식별자
|
||||
* @return string 생성된 레이아웃 이름
|
||||
*/
|
||||
protected function generateLayoutNameFromPath(string $basePath, string $filePath, string $identifier): string
|
||||
{
|
||||
// 상대 경로 추출 (basePath 기준)
|
||||
$relativePath = str_replace($basePath.DIRECTORY_SEPARATOR, '', $filePath);
|
||||
|
||||
// .json 확장자 제거
|
||||
$relativePath = preg_replace('/\.json$/i', '', $relativePath);
|
||||
|
||||
// 디렉토리 구분자를 언더스코어로 변환
|
||||
$layoutPath = str_replace([DIRECTORY_SEPARATOR, '/'], '_', $relativePath);
|
||||
|
||||
// 레이아웃 이름 생성: {identifier}_{path}
|
||||
return $identifier.'_'.$layoutPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 데이터 내의 모든 partial을 재귀적으로 해석합니다.
|
||||
*
|
||||
* @param array $data 레이아웃 데이터
|
||||
* @param string $basePath 기준 경로 (현재 레이아웃 파일의 디렉토리)
|
||||
* @param int $depth 현재 partial 깊이
|
||||
* @param array $dataSources 메인 레이아웃의 data_sources (partial 파일에서 참조 가능)
|
||||
* @return array partial이 모두 해석된 데이터
|
||||
*
|
||||
* @throws LayoutIncludeException
|
||||
*/
|
||||
protected function resolveAllPartials(array $data, string $basePath, int $depth = 0, array $dataSources = []): array
|
||||
{
|
||||
// 1. 깊이 제한 검증
|
||||
$maxDepth = config('template.layout.max_inheritance_depth', 10);
|
||||
if ($depth > $maxDepth) {
|
||||
throw new LayoutIncludeException(
|
||||
__('exceptions.layout.max_include_depth_exceeded', ['max' => $maxDepth]),
|
||||
null,
|
||||
$this->partialStack
|
||||
);
|
||||
}
|
||||
|
||||
// 2. partial 키가 있으면 처리 (배열 항목 치환)
|
||||
if (isset($data['partial']) && is_string($data['partial'])) {
|
||||
return $this->resolvePartial($data['partial'], $basePath, $depth, $dataSources);
|
||||
}
|
||||
|
||||
// 3. 배열의 각 요소를 재귀적으로 처리
|
||||
foreach ($data as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$data[$key] = $this->resolveAllPartials($value, $basePath, $depth, $dataSources);
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 partial을 해석하여 실제 데이터를 반환합니다.
|
||||
*
|
||||
* @param string $partialPath partial 경로
|
||||
* @param string $basePath 기준 경로
|
||||
* @param int $depth 현재 깊이
|
||||
* @param array $dataSources 메인 레이아웃의 data_sources
|
||||
* @return array 로드된 데이터
|
||||
*
|
||||
* @throws LayoutIncludeException
|
||||
*/
|
||||
protected function resolvePartial(string $partialPath, string $basePath, int $depth, array $dataSources = []): array
|
||||
{
|
||||
try {
|
||||
// 1. 상대 경로를 절대 경로로 변환
|
||||
$absolutePath = $this->resolvePartialPath($partialPath, $basePath);
|
||||
} catch (LayoutIncludeException $e) {
|
||||
// 경로 해석 실패 시 로그만 남기고 에러 표시 컴포넌트 반환
|
||||
Log::warning('Partial 경로 해석 실패', [
|
||||
'partial_path' => $partialPath,
|
||||
'base_path' => $basePath,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->createPartialErrorComponent($partialPath, $e->getMessage());
|
||||
}
|
||||
|
||||
// 2. 순환 참조 감지 (자기 자신 재귀 참조는 허용 - 대댓글 등 데이터 기반 재귀 구조 지원)
|
||||
// 자기 자신을 참조하는 경우: 이전 항목이 자신과 같으면 재귀 구조이므로 허용
|
||||
// 다른 파일을 통한 순환 참조(A→B→A)만 에러로 처리
|
||||
$stackCount = count($this->partialStack);
|
||||
$isRecursiveSelfReference = $stackCount > 0 && $this->partialStack[$stackCount - 1] === $absolutePath;
|
||||
|
||||
if (in_array($absolutePath, $this->partialStack, true) && ! $isRecursiveSelfReference) {
|
||||
$trace = implode(' → ', $this->partialStack)." → {$absolutePath}";
|
||||
$errorMessage = __('exceptions.layout.circular_include', ['trace' => $trace]);
|
||||
|
||||
Log::warning('Partial 순환 참조 감지', [
|
||||
'partial_path' => $partialPath,
|
||||
'trace' => $trace,
|
||||
]);
|
||||
|
||||
return $this->createPartialErrorComponent($partialPath, $errorMessage);
|
||||
}
|
||||
|
||||
// 자기 자신 재귀 참조인 경우: 더 이상 재귀하지 않고 partial 참조 그대로 반환
|
||||
// 런타임에 프론트엔드에서 데이터 기반으로 렌더링됨
|
||||
if ($isRecursiveSelfReference) {
|
||||
return [
|
||||
'partial' => $partialPath,
|
||||
'_recursive' => true,
|
||||
];
|
||||
}
|
||||
|
||||
// 3. 파일 존재 여부 확인
|
||||
if (! file_exists($absolutePath)) {
|
||||
$errorMessage = __('exceptions.layout.include_file_not_found', [
|
||||
'path' => $partialPath,
|
||||
'resolved' => $absolutePath,
|
||||
]);
|
||||
|
||||
Log::warning('Partial 파일을 찾을 수 없음', [
|
||||
'partial_path' => $partialPath,
|
||||
'resolved_path' => $absolutePath,
|
||||
]);
|
||||
|
||||
return $this->createPartialErrorComponent($partialPath, $errorMessage);
|
||||
}
|
||||
|
||||
// 4. 스택에 추가
|
||||
$this->partialStack[] = $absolutePath;
|
||||
|
||||
try {
|
||||
// 5. JSON 파일 로드
|
||||
$json = file_get_contents($absolutePath);
|
||||
$data = json_decode($json, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$errorMessage = __('exceptions.layout.invalid_include_json', [
|
||||
'path' => $partialPath,
|
||||
'error' => json_last_error_msg(),
|
||||
]);
|
||||
|
||||
Log::warning('Partial JSON 파싱 실패', [
|
||||
'partial_path' => $partialPath,
|
||||
'error' => json_last_error_msg(),
|
||||
]);
|
||||
|
||||
return $this->createPartialErrorComponent($partialPath, $errorMessage);
|
||||
}
|
||||
|
||||
// 6. 로드된 데이터 내부의 partial도 재귀적으로 처리
|
||||
$newBasePath = dirname($absolutePath);
|
||||
$data = $this->resolveAllPartials($data, $newBasePath, $depth + 1, $dataSources);
|
||||
|
||||
return $data;
|
||||
} finally {
|
||||
array_pop($this->partialStack);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* partial 경로를 절대 경로로 변환하고 보안 검증을 수행합니다.
|
||||
*
|
||||
* @param string $partialPath partial 경로
|
||||
* @param string $basePath 기준 경로
|
||||
* @return string 절대 경로
|
||||
*
|
||||
* @throws LayoutIncludeException
|
||||
*/
|
||||
protected function resolvePartialPath(string $partialPath, string $basePath): string
|
||||
{
|
||||
// 1. 먼저 현재 basePath 기준으로 상대 경로 시도
|
||||
$absolutePath = $basePath.DIRECTORY_SEPARATOR.$partialPath;
|
||||
|
||||
// 2. partials/로 시작하고 basePath 기준 파일이 없으면 layouts 루트 기준으로 fallback
|
||||
if (str_starts_with($partialPath, 'partials/') || str_starts_with($partialPath, 'partials\\')) {
|
||||
if (! file_exists($absolutePath)) {
|
||||
$layoutsDir = $this->getLayoutsBaseDirectory($basePath);
|
||||
$absolutePath = $layoutsDir.DIRECTORY_SEPARATOR.$partialPath;
|
||||
}
|
||||
}
|
||||
|
||||
// realpath로 실제 경로 확인
|
||||
$realPath = realpath($absolutePath);
|
||||
|
||||
// 2. realpath 실패 시 수동 정규화
|
||||
if ($realPath === false) {
|
||||
$realPath = $this->normalizeFilePath($absolutePath);
|
||||
}
|
||||
|
||||
// 3. 보안 검증: layouts 디렉토리 내부인지 확인
|
||||
$layoutsDir = $this->getLayoutsBaseDirectory($basePath);
|
||||
|
||||
// Windows/Linux 호환을 위해 경로 정규화
|
||||
$realPathNormalized = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $realPath);
|
||||
$layoutsDirNormalized = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $layoutsDir);
|
||||
|
||||
if (! str_starts_with($realPathNormalized, $layoutsDirNormalized)) {
|
||||
throw new LayoutIncludeException(
|
||||
__('exceptions.layout.include_outside_directory', [
|
||||
'path' => $partialPath,
|
||||
'allowed_dir' => $layoutsDir,
|
||||
]),
|
||||
$partialPath,
|
||||
$this->partialStack
|
||||
);
|
||||
}
|
||||
|
||||
return $realPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 경로를 정규화합니다 (.과 .. 처리).
|
||||
*
|
||||
* @param string $path 경로
|
||||
* @return string 정규화된 경로
|
||||
*/
|
||||
protected function normalizeFilePath(string $path): string
|
||||
{
|
||||
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
|
||||
$parts = [];
|
||||
$segments = explode(DIRECTORY_SEPARATOR, $path);
|
||||
|
||||
foreach ($segments as $segment) {
|
||||
if ($segment === '..' && count($parts) > 0) {
|
||||
array_pop($parts);
|
||||
} elseif ($segment !== '.' && $segment !== '') {
|
||||
$parts[] = $segment;
|
||||
}
|
||||
}
|
||||
|
||||
return implode(DIRECTORY_SEPARATOR, $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 허용된 layouts 디렉토리를 추출합니다.
|
||||
*
|
||||
* @param string $basePath 기준 경로
|
||||
* @return string layouts 디렉토리 경로
|
||||
*/
|
||||
protected function getLayoutsBaseDirectory(string $basePath): string
|
||||
{
|
||||
// layouts 디렉토리 또는 그 하위 디렉토리까지만 허용
|
||||
if (str_contains($basePath, 'modules')) {
|
||||
// modules/{name}/resources/layouts
|
||||
if (preg_match('#(.*modules[\\\\/][^\\\\/]+[\\\\/]resources[\\\\/]layouts)#', $basePath, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
} elseif (str_contains($basePath, 'plugins')) {
|
||||
// plugins/{name}/resources/layouts
|
||||
if (preg_match('#(.*plugins[\\\\/][^\\\\/]+[\\\\/]resources[\\\\/]layouts)#', $basePath, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
} elseif (str_contains($basePath, 'templates')) {
|
||||
// templates/{name}/layouts
|
||||
if (preg_match('#(.*templates[\\\\/][^\\\\/]+[\\\\/]layouts)#', $basePath, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
}
|
||||
|
||||
return $basePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Partial 파일 로드 실패 시 화면에 표시할 에러 컴포넌트를 생성합니다.
|
||||
*
|
||||
* @param string $partialPath Partial 경로
|
||||
* @param string $errorMessage 에러 메시지
|
||||
* @return array 에러 표시용 컴포넌트 배열
|
||||
*/
|
||||
protected function createPartialErrorComponent(string $partialPath, string $errorMessage): array
|
||||
{
|
||||
// 개발 환경에서만 에러 표시
|
||||
if (! config('app.debug', false)) {
|
||||
return []; // 프로덕션에서는 빈 배열 반환 (아무것도 렌더링 안 함)
|
||||
}
|
||||
|
||||
return [
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'props' => [
|
||||
'className' => 'p-4 my-2 bg-red-50 dark:bg-red-900 border-red-300 dark:border-red-600 rounded-lg',
|
||||
],
|
||||
'children' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Div',
|
||||
'props' => [
|
||||
'className' => 'flex items-center gap-2 mb-2',
|
||||
],
|
||||
'children' => [
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Span',
|
||||
'props' => [
|
||||
'className' => 'text-xl',
|
||||
],
|
||||
'text' => '⚠️',
|
||||
],
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'Span',
|
||||
'props' => [
|
||||
'className' => 'font-bold text-red-900 dark:text-red-100',
|
||||
],
|
||||
'text' => 'Partial Error',
|
||||
],
|
||||
],
|
||||
],
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'P',
|
||||
'props' => [
|
||||
'className' => 'text-sm text-red-700 dark:text-red-300 mb-1',
|
||||
],
|
||||
'text' => 'Path: '.$partialPath,
|
||||
],
|
||||
[
|
||||
'type' => 'basic',
|
||||
'name' => 'P',
|
||||
'props' => [
|
||||
'className' => 'text-sm text-red-600 dark:text-red-400',
|
||||
],
|
||||
'text' => 'Error: '.$errorMessage,
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
|
||||
/**
|
||||
* 권한 계층형 구조 검증 기능을 제공하는 트레이트.
|
||||
*
|
||||
* 모듈 및 플러그인 설치 시 getPermissions()에서 반환하는
|
||||
* 권한 구조가 올바른 계층형인지 검증합니다.
|
||||
*
|
||||
* 계층 구조: 모듈(1레벨) → 카테고리(2레벨) → 개별 권한(3레벨)
|
||||
*/
|
||||
trait ValidatesPermissionStructure
|
||||
{
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 권한 구조가 올바른 계층형인지 검증합니다.
|
||||
*
|
||||
* @param object $extension 검증할 모듈 또는 플러그인 인스턴스
|
||||
* @param string $extensionType 확장 타입 ('module' 또는 'plugin')
|
||||
*
|
||||
* @throws \Exception 권한 구조가 올바르지 않을 때
|
||||
*/
|
||||
protected function validatePermissionStructure(object $extension, string $extensionType = 'module'): void
|
||||
{
|
||||
$permissionConfig = $extension->getPermissions();
|
||||
$identifier = $extension->getIdentifier();
|
||||
|
||||
// 권한이 없으면 검증 통과
|
||||
if (empty($permissionConfig)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 계층형 구조 필수 필드 확인
|
||||
if (! isset($permissionConfig['categories'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, 'categories 필드가 필요합니다.')
|
||||
);
|
||||
}
|
||||
|
||||
if (! is_array($permissionConfig['categories'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, 'categories는 배열이어야 합니다.')
|
||||
);
|
||||
}
|
||||
|
||||
// name, description 필드 확인
|
||||
if (! isset($permissionConfig['name']) || ! is_array($permissionConfig['name'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, 'name 필드가 다국어 배열 형식이어야 합니다.')
|
||||
);
|
||||
}
|
||||
|
||||
// 각 카테고리 검증
|
||||
foreach ($permissionConfig['categories'] as $index => $category) {
|
||||
$this->validateCategoryStructure($extension, $category, $index, $extensionType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 개별 카테고리 구조를 검증합니다.
|
||||
*
|
||||
* @param object $extension 확장 인스턴스
|
||||
* @param array $category 카테고리 데이터
|
||||
* @param int $index 카테고리 인덱스
|
||||
* @param string $extensionType 확장 타입
|
||||
*
|
||||
* @throws \Exception 카테고리 구조가 올바르지 않을 때
|
||||
*/
|
||||
protected function validateCategoryStructure(object $extension, array $category, int $index, string $extensionType): void
|
||||
{
|
||||
$identifier = $extension->getIdentifier();
|
||||
|
||||
// identifier 필수
|
||||
if (! isset($category['identifier']) || empty($category['identifier'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, "categories[{$index}].identifier가 필요합니다.")
|
||||
);
|
||||
}
|
||||
|
||||
// name 필수 (다국어 배열)
|
||||
if (! isset($category['name']) || ! is_array($category['name'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, "categories[{$index}].name이 다국어 배열 형식이어야 합니다.")
|
||||
);
|
||||
}
|
||||
|
||||
// permissions 필수
|
||||
if (! isset($category['permissions']) || ! is_array($category['permissions'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, "categories[{$index}].permissions가 배열이어야 합니다.")
|
||||
);
|
||||
}
|
||||
|
||||
// 각 권한 검증
|
||||
foreach ($category['permissions'] as $permIndex => $permission) {
|
||||
$this->validateIndividualPermissionStructure($extension, $permission, $index, $permIndex, $extensionType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 개별 권한 구조를 검증합니다.
|
||||
*
|
||||
* @param object $extension 확장 인스턴스
|
||||
* @param array $permission 권한 데이터
|
||||
* @param int $categoryIndex 카테고리 인덱스
|
||||
* @param int $permIndex 권한 인덱스
|
||||
* @param string $extensionType 확장 타입
|
||||
*
|
||||
* @throws \Exception 권한 구조가 올바르지 않을 때
|
||||
*/
|
||||
protected function validateIndividualPermissionStructure(object $extension, array $permission, int $categoryIndex, int $permIndex, string $extensionType): void
|
||||
{
|
||||
$identifier = $extension->getIdentifier();
|
||||
|
||||
// action 필수
|
||||
if (! isset($permission['action']) || empty($permission['action'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, "categories[{$categoryIndex}].permissions[{$permIndex}].action이 필요합니다.")
|
||||
);
|
||||
}
|
||||
|
||||
// name 필수 (다국어 배열)
|
||||
if (! isset($permission['name']) || ! is_array($permission['name'])) {
|
||||
throw new \Exception(
|
||||
$this->formatPermissionValidationError($extensionType, $identifier, "categories[{$categoryIndex}].permissions[{$permIndex}].name이 다국어 배열 형식이어야 합니다.")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 검증 에러 메시지를 포맷합니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입 ('module' 또는 'plugin')
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param string $reason 에러 사유
|
||||
* @return string 포맷된 에러 메시지
|
||||
*/
|
||||
protected function formatPermissionValidationError(string $extensionType, string $identifier, string $reason): string
|
||||
{
|
||||
$translationKey = $extensionType === 'module'
|
||||
? 'modules.errors.invalid_permission_structure'
|
||||
: 'plugins.errors.invalid_permission_structure';
|
||||
|
||||
return __($translationKey, [
|
||||
'identifier' => $identifier,
|
||||
'reason' => $reason,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 언어 파일 경로 검증 기능을 제공하는 트레이트.
|
||||
*
|
||||
* 모듈 및 플러그인 설치 시 언어 파일이 올바른 경로에 있는지 검증합니다.
|
||||
*
|
||||
* 올바른 경로:
|
||||
* - 모듈: modules/{vendor-module}/src/lang/{locale}/*.php
|
||||
* - 플러그인: plugins/{vendor-plugin}/lang/{locale}/*.php
|
||||
*
|
||||
* 잘못된 경로:
|
||||
* - 모듈: modules/{vendor-module}/lang/ (src/lang 대신 lang 사용)
|
||||
*/
|
||||
trait ValidatesTranslationPath
|
||||
{
|
||||
/**
|
||||
* 확장의 언어 파일 경로가 올바른지 검증합니다.
|
||||
*
|
||||
* @param object $extension 검증할 모듈 또는 플러그인 인스턴스
|
||||
* @param string $extensionType 확장 타입 ('module' 또는 'plugin')
|
||||
*
|
||||
* @throws \Exception 언어 파일 경로가 올바르지 않을 때
|
||||
*/
|
||||
protected function validateTranslationPath(object $extension, string $extensionType = 'module'): void
|
||||
{
|
||||
$identifier = $extension->getIdentifier();
|
||||
|
||||
if ($extensionType === 'module') {
|
||||
$this->validateModuleTranslationPath($identifier);
|
||||
} else {
|
||||
$this->validatePluginTranslationPath($identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈의 언어 파일 경로를 검증합니다.
|
||||
*
|
||||
* 올바른 경로: modules/{identifier}/src/lang
|
||||
* 잘못된 경로: modules/{identifier}/lang
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
*
|
||||
* @throws \Exception 언어 파일 경로가 올바르지 않을 때
|
||||
*/
|
||||
protected function validateModuleTranslationPath(string $identifier): void
|
||||
{
|
||||
$basePath = base_path("modules/{$identifier}");
|
||||
$correctPath = $basePath.'/src/lang';
|
||||
$wrongPath = $basePath.'/lang';
|
||||
|
||||
// 잘못된 경로에 언어 파일이 있는지 확인
|
||||
if (File::isDirectory($wrongPath) && $this->hasTranslationFiles($wrongPath)) {
|
||||
// 올바른 경로에도 파일이 있는지 확인
|
||||
if (! File::isDirectory($correctPath) || ! $this->hasTranslationFiles($correctPath)) {
|
||||
throw new \Exception(
|
||||
__('modules.errors.invalid_translation_path', [
|
||||
'identifier' => $identifier,
|
||||
'wrong_path' => 'lang/',
|
||||
'correct_path' => 'src/lang/',
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인의 언어 파일 경로를 검증합니다.
|
||||
*
|
||||
* 올바른 경로: plugins/{identifier}/lang
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
*
|
||||
* @throws \Exception 언어 파일 경로가 올바르지 않을 때
|
||||
*/
|
||||
protected function validatePluginTranslationPath(string $identifier): void
|
||||
{
|
||||
$basePath = base_path("plugins/{$identifier}");
|
||||
$correctPath = $basePath.'/lang';
|
||||
$wrongPath = $basePath.'/src/lang';
|
||||
|
||||
// 잘못된 경로에 언어 파일이 있는지 확인
|
||||
if (File::isDirectory($wrongPath) && $this->hasTranslationFiles($wrongPath)) {
|
||||
// 올바른 경로에도 파일이 있는지 확인
|
||||
if (! File::isDirectory($correctPath) || ! $this->hasTranslationFiles($correctPath)) {
|
||||
throw new \Exception(
|
||||
__('plugins.errors.invalid_translation_path', [
|
||||
'identifier' => $identifier,
|
||||
'wrong_path' => 'src/lang/',
|
||||
'correct_path' => 'lang/',
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 디렉토리에 번역 파일이 있는지 확인합니다.
|
||||
*
|
||||
* 로케일 디렉토리(ko, en 등) 내에 .php 파일이 있는지 확인합니다.
|
||||
*
|
||||
* @param string $path 검사할 디렉토리 경로
|
||||
* @return bool 번역 파일 존재 여부
|
||||
*/
|
||||
protected function hasTranslationFiles(string $path): bool
|
||||
{
|
||||
if (! File::isDirectory($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$localeDirectories = File::directories($path);
|
||||
|
||||
foreach ($localeDirectories as $localeDir) {
|
||||
$phpFiles = File::glob($localeDir.'/*.php');
|
||||
if (! empty($phpFiles)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* 업그레이드 콜백/스텝에 전달되는 컨텍스트 객체
|
||||
*
|
||||
* 업그레이드 실행 중 필요한 버전 정보와 로거를 제공합니다.
|
||||
*
|
||||
* 정적 메뉴/권한 정리가 필요한 경우 UpgradeStep에서 아래와 같이 처리합니다:
|
||||
*
|
||||
* @example
|
||||
* // UpgradeStep에서 stale 메뉴 정리 예시
|
||||
* public function run(UpgradeContext $context): void
|
||||
* {
|
||||
* $menuHelper = app(ExtensionMenuSyncHelper::class);
|
||||
* $menuHelper->cleanupStaleMenus(
|
||||
* ExtensionOwnerType::Module,
|
||||
* 'vendor-module',
|
||||
* ['menu-slug-1', 'menu-slug-2'], // 유지할 slug 목록
|
||||
* );
|
||||
* }
|
||||
*/
|
||||
class UpgradeContext
|
||||
{
|
||||
/**
|
||||
* 업그레이드 전용 로그 채널
|
||||
*/
|
||||
public readonly LoggerInterface $logger;
|
||||
|
||||
/**
|
||||
* @param string $fromVersion 업그레이드 시작 버전 (현재 설치 버전)
|
||||
* @param string $toVersion 업그레이드 목표 버전
|
||||
* @param string $currentStep 현재 실행 중인 스텝 버전
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $fromVersion,
|
||||
public readonly string $toVersion,
|
||||
public readonly string $currentStep = '',
|
||||
) {
|
||||
$this->logger = Log::channel('upgrade');
|
||||
}
|
||||
|
||||
/**
|
||||
* 테이블명에 DB 프리픽스를 적용하여 반환합니다.
|
||||
*
|
||||
* 업그레이드 스텝에서 raw SQL 사용 시 반드시 이 메서드로 테이블명을 감싸세요.
|
||||
* Schema 파사드는 자동으로 프리픽스를 적용하지만, DB::selectOne() 등
|
||||
* raw SQL에서는 프리픽스가 적용되지 않습니다.
|
||||
*
|
||||
* @param string $table 프리픽스 없는 테이블명 (예: 'users')
|
||||
* @return string 프리픽스가 적용된 테이블명 (예: 'g7_users')
|
||||
*
|
||||
* @example
|
||||
* // raw SQL에서 사용
|
||||
* DB::selectOne("SHOW COLUMNS FROM {$context->table('users')} WHERE Field = 'uuid'");
|
||||
*
|
||||
* // DB::table()은 자동 적용되므로 불필요 (하지만 사용해도 무방)
|
||||
* DB::table('users')->where(...); // 프리픽스 자동 적용
|
||||
*/
|
||||
public function table(string $table): string
|
||||
{
|
||||
return DB::getTablePrefix().$table;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 스텝 버전을 변경한 새 컨텍스트를 반환합니다.
|
||||
*
|
||||
* @param string $stepVersion 현재 실행할 스텝 버전
|
||||
*/
|
||||
public function withCurrentStep(string $stepVersion): self
|
||||
{
|
||||
return new self(
|
||||
fromVersion: $this->fromVersion,
|
||||
toVersion: $this->toVersion,
|
||||
currentStep: $stepVersion,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user