v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -0,0 +1,177 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\CacheableExtensionInterface;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인) 서비스 프로바이더 공통 베이스.
|
||||
*
|
||||
* 모듈·플러그인이 공유하는 자동 바인딩 표면(Repository, Storage, Cache)과
|
||||
* 다국어/마이그레이션 로드 hook 을 단일 클래스에 집약합니다. 자식 베이스
|
||||
* (BaseModuleServiceProvider / BasePluginServiceProvider) 는 확장 인스턴스
|
||||
* 해석 방식만 결정합니다.
|
||||
*
|
||||
* 글로벌 컨테이너 바인딩(`$this->app->singleton(CacheInterface::class, ...)`)
|
||||
* 으로 코어 도메인을 덮어쓰는 패턴은 금지됩니다. cacheServices 배열에 클래스만
|
||||
* 등록하면 Laravel contextual binding 으로 해당 확장 도메인의 캐시 인스턴스가
|
||||
* 자동 주입됩니다.
|
||||
*/
|
||||
abstract class AbstractExtensionServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* 확장 식별자 (vendor-extension). 자식 클래스에서 반드시 정의.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $extensionIdentifier;
|
||||
|
||||
/**
|
||||
* StorageInterface 가 필요한 서비스 클래스 목록.
|
||||
*
|
||||
* 등록된 클래스의 생성자에서 StorageInterface 를 의존하면, 해당 확장
|
||||
* 도메인의 Storage 인스턴스가 contextual binding 으로 자동 주입됩니다.
|
||||
*
|
||||
* @var array<int, class-string>
|
||||
*/
|
||||
protected array $storageServices = [];
|
||||
|
||||
/**
|
||||
* CacheInterface 가 필요한 서비스 클래스 목록.
|
||||
*
|
||||
* @var array<int, class-string>
|
||||
*/
|
||||
protected array $cacheServices = [];
|
||||
|
||||
/**
|
||||
* Repository 인터페이스 ↔ 구현체 매핑.
|
||||
*
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
protected array $repositories = [];
|
||||
|
||||
/**
|
||||
* ServiceProvider 파일이 위치한 디렉토리 경로 (캐시).
|
||||
*/
|
||||
private ?string $providerPath = null;
|
||||
|
||||
/**
|
||||
* 확장 인스턴스를 해석합니다.
|
||||
*
|
||||
* BaseModuleServiceProvider 는 ModuleManager, BasePluginServiceProvider 는
|
||||
* PluginManager 를 통해 해당 식별자의 확장을 가져옵니다.
|
||||
*
|
||||
* @return CacheableExtensionInterface 캐시/스토리지 도메인을 보유한 확장
|
||||
*/
|
||||
abstract protected function resolveExtension(): CacheableExtensionInterface;
|
||||
|
||||
/**
|
||||
* 다국어 도메인 이름. 기본값은 확장 식별자이며 자식이 필요 시 오버라이드.
|
||||
*/
|
||||
protected function translationNamespace(): string
|
||||
{
|
||||
return $this->extensionIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->registerRepositories();
|
||||
$this->registerStorageBindings();
|
||||
$this->registerCacheBindings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
$this->loadExtensionMigrations();
|
||||
$this->loadExtensionTranslations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Repository 인터페이스를 구현체에 바인딩합니다.
|
||||
*/
|
||||
protected function registerRepositories(): void
|
||||
{
|
||||
foreach ($this->repositories as $interface => $implementation) {
|
||||
$this->app->bind($interface, $implementation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* StorageInterface 를 필요로 하는 서비스에 contextual binding 으로 주입합니다.
|
||||
*/
|
||||
protected function registerStorageBindings(): void
|
||||
{
|
||||
if (empty($this->storageServices)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->app->when($this->storageServices)
|
||||
->needs(StorageInterface::class)
|
||||
->give(fn () => $this->resolveExtension()->getStorage());
|
||||
}
|
||||
|
||||
/**
|
||||
* CacheInterface 를 필요로 하는 서비스에 contextual binding 으로 주입합니다.
|
||||
*/
|
||||
protected function registerCacheBindings(): void
|
||||
{
|
||||
if (empty($this->cacheServices)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->app->when($this->cacheServices)
|
||||
->needs(CacheInterface::class)
|
||||
->give(fn () => $this->resolveExtension()->getCache());
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceProvider 파일의 디렉토리 경로를 반환합니다.
|
||||
*
|
||||
* ReflectionClass 로 자식 클래스의 실제 경로를 가져옵니다 (__DIR__ 은 베이스
|
||||
* 경로를 반환하므로 사용 불가).
|
||||
*/
|
||||
protected function getProviderPath(): string
|
||||
{
|
||||
if ($this->providerPath === null) {
|
||||
$reflection = new ReflectionClass($this);
|
||||
$this->providerPath = dirname($reflection->getFileName());
|
||||
}
|
||||
|
||||
return $this->providerPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 마이그레이션 로드 hook (기본 no-op).
|
||||
*
|
||||
* 확장 마이그레이션은 ModuleManager/PluginManager::runMigrations() 가 별도로
|
||||
* 실행하므로 여기서는 loadMigrationsFrom() 을 호출하지 않습니다.
|
||||
*/
|
||||
protected function loadExtensionMigrations(): void
|
||||
{
|
||||
// no-op: ModuleManager/PluginManager::runMigrations() 에서 처리됨
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 다국어 파일을 로드합니다.
|
||||
*
|
||||
* 기본 경로: ServiceProvider 디렉토리에서 상위로 한 단계 올라간 lang/ 디렉토리.
|
||||
*/
|
||||
protected function loadExtensionTranslations(): void
|
||||
{
|
||||
$langPath = $this->getProviderPath().'/../lang';
|
||||
|
||||
if (is_dir($langPath)) {
|
||||
$this->loadTranslationsFrom($langPath, $this->translationNamespace());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\CacheableExtensionInterface;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\ModuleInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
@@ -18,7 +19,7 @@ use ReflectionClass;
|
||||
* getIdentifier(), getVendor()는 디렉토리명에서 자동 추론됩니다.
|
||||
* getName(), getVersion(), getDescription()은 module.json에서 자동 파싱됩니다.
|
||||
*/
|
||||
abstract class AbstractModule implements ModuleInterface
|
||||
abstract class AbstractModule implements CacheableExtensionInterface, ModuleInterface
|
||||
{
|
||||
/**
|
||||
* 모듈 디렉토리 경로 (캐시)
|
||||
@@ -1001,6 +1002,69 @@ abstract class AbstractModule implements ModuleInterface
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* OG 기본값 키별 데이터 출처(연결 칩) 메타 선언 — 편집기 전용
|
||||
*
|
||||
* `seoOgDefaults()` 가 반환하는 평문값은 운영 렌더링에 그대로 쓰이지만, 어느 데이터에서
|
||||
* 왔는지(`{{product.data.name}}`)는 평문으로 resolve 되며 정보가 소실됩니다. 편집기
|
||||
* [검색엔진] 탭은 자동값을 "상품 이름" 같은 **연결 칩**으로 보여주고 사용자가 다른
|
||||
* 데이터로 교체할 수 있어야 하므로, 본 메서드가 키별 데이터 경로(표현식)와
|
||||
* 사용자용 라벨을 함께 제공합니다.
|
||||
*
|
||||
* 운영 렌더링(`SeoRenderer`)은 본 메서드를 호출하지 않습니다 — 편집기 미리보기
|
||||
* (`SeoOgPreviewService`)만 소비합니다. 미오버라이드(빈 배열)면 편집기는 종전대로
|
||||
* resolve 된 평문을 보여줍니다(하위호환·평문 폴백).
|
||||
*
|
||||
* `label` 은 **번역 키 문자열**(`'sirsoft-ecommerce::seo.auto_value.product_name'`)로 선언하는 것을
|
||||
* 권장합니다 — 편집기가 `__()` 로 해석하므로 모듈 lang 파일(+번들 언어팩)이 그 키를 번역하면
|
||||
* 추가 언어(ja 등)에 자동 대응합니다. 인라인 다국어 맵(`['ko' => ..., 'en' => ...]`)도 허용하나
|
||||
* 그 외 로케일은 en 폴백이라 언어팩에 대응하지 못합니다(하위호환용).
|
||||
*
|
||||
* @param string $pageType 레이아웃 meta.seo.page_type
|
||||
* @return array<string, array{expr: string, label: string|array<string, string>}>
|
||||
* 키별 데이터 경로 메타 — 예:
|
||||
* [
|
||||
* 'image' => ['expr' => '{{product.data.thumbnail_url}}', 'label' => 'vendor-module::seo.auto_value.product_image'],
|
||||
* 'image_alt' => ['expr' => '{{product.data.name}}', 'label' => 'vendor-module::seo.auto_value.product_name'],
|
||||
* ]
|
||||
*/
|
||||
public function seoOgDefaultMeta(string $pageType): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Twitter 카드 기본값 키별 데이터 출처(연결 칩) 메타 선언 — 편집기 전용
|
||||
*
|
||||
* @param string $pageType 페이지 타입
|
||||
* @return array<string, array{expr: string, label: string|array<string, string>}> 키별 데이터 경로 메타
|
||||
* (label = 번역 키 권장 — seoOgDefaultMeta 참조)
|
||||
*/
|
||||
public function seoTwitterDefaultMeta(string $pageType): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 구조화 데이터 속성별 데이터 출처(연결 칩) 메타 선언 — 편집기 전용
|
||||
*
|
||||
* `seoStructuredData()` 의 중첩 객체를 점 경로 키로 평탄화한 기준으로 선언합니다
|
||||
* (예: `offers.price`). 편집기가 자동 블록을 평탄 행으로 보여줄 때 각 값을 연결 칩으로
|
||||
* 표시하는 근거입니다.
|
||||
*
|
||||
* @param string $pageType 페이지 타입
|
||||
* @return array<string, array{expr: string, label: string|array<string, string>}>
|
||||
* 점 경로 키별 데이터 경로 메타 (label = 번역 키 권장 — seoOgDefaultMeta 참조) — 예:
|
||||
* [
|
||||
* 'name' => ['expr' => '{{product.data.name}}', 'label' => 'vendor-module::seo.auto_value.product_name'],
|
||||
* 'offers.price' => ['expr' => '{{product.data.selling_price}}', 'label' => 'vendor-module::seo.auto_value.product_price'],
|
||||
* ]
|
||||
*/
|
||||
public function seoStructuredDataMeta(string $pageType): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 그누보드7 코어 요구 버전 제약 반환
|
||||
*
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\CacheableExtensionInterface;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\PluginInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
@@ -20,7 +21,7 @@ use ReflectionClass;
|
||||
*
|
||||
* 참고: 플러그인은 모듈과 달리 관리자 메뉴(getAdminMenus)를 추가할 수 없습니다.
|
||||
*/
|
||||
abstract class AbstractPlugin implements PluginInterface
|
||||
abstract class AbstractPlugin implements CacheableExtensionInterface, PluginInterface
|
||||
{
|
||||
/**
|
||||
* 플러그인 디렉토리 경로 (캐시)
|
||||
@@ -845,6 +846,46 @@ abstract class AbstractPlugin implements PluginInterface
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* OG 기본값 키별 데이터 출처(연결 칩) 메타 선언 — 편집기 전용
|
||||
*
|
||||
* `seoOgDefaults()` 의 평문값이 어느 데이터에서 왔는지(`{{...}}`)를 편집기 [검색엔진] 탭이
|
||||
* 연결 칩으로 보여주고 교체할 수 있도록, 키별 데이터 경로(표현식)와 사용자용 라벨을 제공합니다.
|
||||
* 운영 렌더링은 본 메서드를 호출하지 않습니다 — 편집기 미리보기만 소비. 미오버라이드면
|
||||
* 종전대로 resolve 된 평문을 보여줍니다(하위호환·평문 폴백). 상세: AbstractModule 동명 메서드.
|
||||
*
|
||||
* @param string $pageType 페이지 타입
|
||||
* @return array<string, array{expr: string, label: string|array<string, string>}> 키별 데이터 경로 메타 (label = 번역 키 권장)
|
||||
*/
|
||||
public function seoOgDefaultMeta(string $pageType): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Twitter 카드 기본값 키별 데이터 출처(연결 칩) 메타 선언 — 편집기 전용
|
||||
*
|
||||
* @param string $pageType 페이지 타입
|
||||
* @return array<string, array{expr: string, label: string|array<string, string>}> 키별 데이터 경로 메타 (label = 번역 키 권장)
|
||||
*/
|
||||
public function seoTwitterDefaultMeta(string $pageType): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 구조화 데이터 속성별 데이터 출처(연결 칩) 메타 선언 — 편집기 전용
|
||||
*
|
||||
* `seoStructuredData()` 중첩 객체를 점 경로 키로 평탄화한 기준으로 선언합니다(예: `offers.price`).
|
||||
*
|
||||
* @param string $pageType 페이지 타입
|
||||
* @return array<string, array{expr: string, label: array<string, string>|string}> 점 경로 키별 데이터 경로 메타
|
||||
*/
|
||||
public function seoStructuredDataMeta(string $pageType): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 그누보드7 코어 요구 버전 제약 반환
|
||||
*
|
||||
|
||||
@@ -2,71 +2,57 @@
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\CacheableExtensionInterface;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use ReflectionClass;
|
||||
use App\Extension\Cache\ModuleCacheDriver;
|
||||
use App\Extension\Storage\ModuleStorageDriver;
|
||||
|
||||
/**
|
||||
* 모듈 서비스 프로바이더 베이스 클래스
|
||||
* 모듈 서비스 프로바이더 베이스 클래스.
|
||||
*
|
||||
* 모든 모듈의 ServiceProvider가 상속받는 추상 클래스입니다.
|
||||
* 공통 기능을 자동화하여 코드 중복을 제거하고 일관성을 확보합니다.
|
||||
* 공통 자동 바인딩 로직은 AbstractExtensionServiceProvider 가 보유하며,
|
||||
* 본 클래스는 ModuleManager 를 통한 확장 해석만 담당합니다. 기존 자식
|
||||
* 클래스는 `$moduleIdentifier` 속성을 그대로 사용할 수 있으며, 부모의
|
||||
* `$extensionIdentifier` 에 자동 미러링됩니다.
|
||||
*/
|
||||
abstract class BaseModuleServiceProvider extends ServiceProvider
|
||||
abstract class BaseModuleServiceProvider extends AbstractExtensionServiceProvider
|
||||
{
|
||||
/**
|
||||
* 모듈 식별자 (자식 클래스에서 반드시 정의)
|
||||
* 모듈 식별자 (하위 호환 alias).
|
||||
*
|
||||
* @var string
|
||||
* 기존 자식 클래스가 이 속성으로 지정한 값을 부모의
|
||||
* `$extensionIdentifier` 로 미러링합니다.
|
||||
*/
|
||||
protected string $moduleIdentifier;
|
||||
|
||||
/**
|
||||
* StorageInterface가 필요한 서비스 클래스 목록
|
||||
* 모듈 인스턴스를 해석합니다.
|
||||
*
|
||||
* 이 배열에 정의된 서비스들은 자동으로 StorageInterface가 주입됩니다.
|
||||
* 정상 경로: ModuleManager 가 활성 모듈 인스턴스를 반환합니다.
|
||||
*
|
||||
* @var array<int, class-string>
|
||||
* Fallback: 테스트 격리 / 모듈 디스커버리 이전 시점에서는 ModuleCacheDriver /
|
||||
* ModuleStorageDriver 를 식별자만으로 직접 생성한 어댑터를 반환합니다.
|
||||
*/
|
||||
protected array $storageServices = [];
|
||||
protected function resolveExtension(): CacheableExtensionInterface
|
||||
{
|
||||
$module = $this->app->make(ModuleManager::class)
|
||||
->getModule($this->extensionIdentifier);
|
||||
|
||||
/**
|
||||
* CacheInterface가 필요한 서비스 클래스 목록
|
||||
*
|
||||
* 이 배열에 정의된 서비스들은 자동으로 CacheInterface가 주입됩니다.
|
||||
*
|
||||
* @var array<int, class-string>
|
||||
*/
|
||||
protected array $cacheServices = [];
|
||||
if ($module !== null) {
|
||||
return $module;
|
||||
}
|
||||
|
||||
/**
|
||||
* Repository 인터페이스와 구현체 매핑
|
||||
*
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
protected array $repositories = [];
|
||||
|
||||
/**
|
||||
* ServiceProvider 파일이 위치한 디렉토리 경로 (캐시)
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
private ?string $providerPath = null;
|
||||
return new InlineModuleExtensionAdapter($this->extensionIdentifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
// Repository 바인딩
|
||||
$this->registerRepositories();
|
||||
|
||||
// StorageInterface 바인딩
|
||||
$this->registerStorageBindings();
|
||||
|
||||
// CacheInterface 바인딩
|
||||
$this->registerCacheBindings();
|
||||
$this->ensureIdentifierAlias();
|
||||
parent::register();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,110 +60,83 @@ abstract class BaseModuleServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
// 마이그레이션 자동 로드
|
||||
$this->loadModuleMigrations();
|
||||
|
||||
// 다국어 자동 로드
|
||||
$this->loadModuleTranslations();
|
||||
$this->ensureIdentifierAlias();
|
||||
parent::boot();
|
||||
}
|
||||
|
||||
/**
|
||||
* Repository 인터페이스를 구현체에 바인딩합니다.
|
||||
* `$moduleIdentifier` 값을 부모의 `$extensionIdentifier` 로 미러링합니다.
|
||||
*/
|
||||
protected function registerRepositories(): void
|
||||
private function ensureIdentifierAlias(): void
|
||||
{
|
||||
foreach ($this->repositories as $interface => $implementation) {
|
||||
$this->app->bind($interface, $implementation);
|
||||
if (isset($this->moduleIdentifier) && ! isset($this->extensionIdentifier)) {
|
||||
$this->extensionIdentifier = $this->moduleIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* CacheInterface를 필요로 하는 서비스에 자동 바인딩합니다.
|
||||
*
|
||||
* 각 서비스의 생성자에서 CacheInterface를 주입받으면,
|
||||
* 해당 모듈의 Cache 인스턴스가 자동으로 주입됩니다.
|
||||
*/
|
||||
protected function registerCacheBindings(): void
|
||||
{
|
||||
if (empty($this->cacheServices)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->app->when($this->cacheServices)
|
||||
->needs(CacheInterface::class)
|
||||
->give(function () {
|
||||
return $this->app->make(ModuleManager::class)
|
||||
->getModule($this->moduleIdentifier)
|
||||
->getCache();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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()로 실행됩니다.
|
||||
* @deprecated 7.0.0-beta.7 부모 `loadExtensionMigrations()` 사용 권장.
|
||||
*/
|
||||
protected function loadModuleMigrations(): void
|
||||
{
|
||||
// 모듈 마이그레이션은 loadMigrationsFrom()으로 등록하지 않음
|
||||
// 대신 ModuleManager::runMigrations()에서 별도로 실행됨
|
||||
$this->loadExtensionMigrations();
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈의 다국어 파일을 로드합니다.
|
||||
*
|
||||
* 기본 경로: {module}/src/lang
|
||||
* 자식 클래스는 {module}/src/Providers에 위치해야 합니다.
|
||||
* @deprecated 7.0.0-beta.7 부모 `loadExtensionTranslations()` 사용 권장.
|
||||
*/
|
||||
protected function loadModuleTranslations(): void
|
||||
{
|
||||
$langPath = $this->getProviderPath().'/../lang';
|
||||
$this->loadExtensionTranslations();
|
||||
}
|
||||
}
|
||||
|
||||
if (is_dir($langPath)) {
|
||||
$this->loadTranslationsFrom($langPath, $this->moduleIdentifier);
|
||||
}
|
||||
/**
|
||||
* ModuleManager 가 식별자 매핑을 보유하지 않는 컨텍스트에서 사용되는 어댑터.
|
||||
*
|
||||
* AbstractModule::getCache() / getStorage() 와 동일한 키 prefix·디스크 정책을
|
||||
* 따르도록 ModuleCacheDriver / ModuleStorageDriver 를 직접 생성합니다.
|
||||
*
|
||||
* @internal BaseModuleServiceProvider 의 fallback 전용.
|
||||
*/
|
||||
final class InlineModuleExtensionAdapter implements CacheableExtensionInterface
|
||||
{
|
||||
private ?CacheInterface $cache = null;
|
||||
|
||||
private ?StorageInterface $storage = null;
|
||||
|
||||
/**
|
||||
* @param string $identifier 모듈 식별자 (vendor-module)
|
||||
*/
|
||||
public function __construct(private readonly string $identifier) {}
|
||||
|
||||
/**
|
||||
* 모듈 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 모듈 식별자
|
||||
*/
|
||||
public function getIdentifier(): string
|
||||
{
|
||||
return $this->identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 도메인 캐시 드라이버를 반환합니다.
|
||||
*
|
||||
* @return CacheInterface ModuleCacheDriver 인스턴스
|
||||
*/
|
||||
public function getCache(): CacheInterface
|
||||
{
|
||||
return $this->cache ??= new ModuleCacheDriver($this->identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 도메인 스토리지 드라이버를 반환합니다.
|
||||
*
|
||||
* @return StorageInterface ModuleStorageDriver 인스턴스
|
||||
*/
|
||||
public function getStorage(): StorageInterface
|
||||
{
|
||||
return $this->storage ??= new ModuleStorageDriver($this->identifier);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\CacheableExtensionInterface;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Extension\Cache\PluginCacheDriver;
|
||||
use App\Extension\Storage\PluginStorageDriver;
|
||||
|
||||
/**
|
||||
* 플러그인 서비스 프로바이더 베이스 클래스.
|
||||
*
|
||||
* 공통 자동 바인딩 로직은 AbstractExtensionServiceProvider 가 보유하며,
|
||||
* 본 클래스는 PluginManager 를 통한 확장 해석만 담당합니다. 자식 클래스는
|
||||
* `$pluginIdentifier` 속성으로 플러그인 식별자를 지정합니다.
|
||||
*
|
||||
* 글로벌 컨테이너 바인딩으로 코어 `CacheInterface` 를 덮어쓰는 패턴은
|
||||
* 금지됩니다. 캐시·스토리지가 필요한 서비스 클래스명을 `$cacheServices`
|
||||
* / `$storageServices` 배열에 등록하면 Laravel contextual binding 으로
|
||||
* 해당 플러그인 도메인의 인스턴스가 자동 주입됩니다.
|
||||
*/
|
||||
abstract class BasePluginServiceProvider extends AbstractExtensionServiceProvider
|
||||
{
|
||||
/**
|
||||
* 플러그인 식별자 (vendor-plugin). 자식 클래스에서 반드시 정의.
|
||||
*/
|
||||
protected string $pluginIdentifier;
|
||||
|
||||
/**
|
||||
* 플러그인 인스턴스를 해석합니다.
|
||||
*
|
||||
* 정상 경로: PluginManager 가 활성 플러그인 인스턴스를 반환합니다.
|
||||
*
|
||||
* Fallback: 테스트 격리 환경 / 플러그인이 PluginManager 에 등록되기 전 시점
|
||||
* (ServiceProvider 의 register 단계가 PluginManager 의 디스커버리보다 앞서 호출되는
|
||||
* 컨테이너 해석 등) 에는 PluginCacheDriver / PluginStorageDriver 를 식별자만으로
|
||||
* 직접 생성한 in-memory 어댑터를 반환합니다. AbstractPlugin::getCache() /
|
||||
* getStorage() 의 기본 구현과 동일한 키 prefix 와 디스크를 사용하므로 운영
|
||||
* 동작은 보존됩니다.
|
||||
*/
|
||||
protected function resolveExtension(): CacheableExtensionInterface
|
||||
{
|
||||
$plugin = $this->app->make(PluginManager::class)
|
||||
->getPlugin($this->extensionIdentifier);
|
||||
|
||||
if ($plugin !== null) {
|
||||
return $plugin;
|
||||
}
|
||||
|
||||
return new InlinePluginExtensionAdapter($this->extensionIdentifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->ensureIdentifierAlias();
|
||||
parent::register();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
$this->ensureIdentifierAlias();
|
||||
parent::boot();
|
||||
}
|
||||
|
||||
/**
|
||||
* `$pluginIdentifier` 값을 부모의 `$extensionIdentifier` 로 미러링합니다.
|
||||
*/
|
||||
private function ensureIdentifierAlias(): void
|
||||
{
|
||||
if (isset($this->pluginIdentifier) && ! isset($this->extensionIdentifier)) {
|
||||
$this->extensionIdentifier = $this->pluginIdentifier;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PluginManager 가 식별자에 해당하는 플러그인 인스턴스를 보유하지 않는 컨텍스트
|
||||
* (테스트 격리 / 플러그인 디스커버리 이전 컨테이너 해석 등) 에서 사용되는 어댑터.
|
||||
*
|
||||
* AbstractPlugin::getCache() / getStorage() 의 기본 구현과 동일한 키 prefix 와
|
||||
* 디스크 정책을 따르도록 PluginCacheDriver / PluginStorageDriver 를 식별자만으로
|
||||
* 직접 생성합니다.
|
||||
*
|
||||
* @internal BasePluginServiceProvider 의 fallback 전용. 외부에서 직접 참조하지 마세요.
|
||||
*/
|
||||
final class InlinePluginExtensionAdapter implements CacheableExtensionInterface
|
||||
{
|
||||
private ?CacheInterface $cache = null;
|
||||
|
||||
private ?StorageInterface $storage = null;
|
||||
|
||||
/**
|
||||
* @param string $identifier 플러그인 식별자 (vendor-plugin)
|
||||
*/
|
||||
public function __construct(private readonly string $identifier) {}
|
||||
|
||||
/**
|
||||
* 플러그인 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 플러그인 식별자
|
||||
*/
|
||||
public function getIdentifier(): string
|
||||
{
|
||||
return $this->identifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 도메인 캐시 드라이버를 반환합니다.
|
||||
*
|
||||
* @return CacheInterface PluginCacheDriver 인스턴스
|
||||
*/
|
||||
public function getCache(): CacheInterface
|
||||
{
|
||||
return $this->cache ??= new PluginCacheDriver($this->identifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 도메인 스토리지 드라이버를 반환합니다.
|
||||
*
|
||||
* @return StorageInterface PluginStorageDriver 인스턴스
|
||||
*/
|
||||
public function getStorage(): StorageInterface
|
||||
{
|
||||
return $this->storage ??= new PluginStorageDriver($this->identifier);
|
||||
}
|
||||
}
|
||||
@@ -33,9 +33,20 @@ class CoreBackupHelper
|
||||
public static function createBackup(array $targets, ?\Closure $onProgress = null, array $excludes = []): string
|
||||
{
|
||||
$timestamp = date('Ymd_His');
|
||||
$backupPath = storage_path("app/core_backups/core_{$timestamp}");
|
||||
$backupRoot = storage_path('app/core_backups');
|
||||
$backupPath = $backupRoot.DIRECTORY_SEPARATOR."core_{$timestamp}";
|
||||
|
||||
File::ensureDirectoryExists($backupPath, 0770, true);
|
||||
// 백업 루트(core_backups)를 php-fpm 그룹이 쓸 수 있도록 보장한 뒤 타임스탬프
|
||||
// 디렉토리를 만든다. sudo 업데이트가 core_backups 를 root/운영자 소유 + g-w(0755)
|
||||
// 로 만들어 두면 이후 www-data 가 그 안에 mkdir 하지 못해 백업 생성이 실패한다
|
||||
// (mkdir(): Permission denied). 루트를 g+w(0775) 로 정상화하고 소유권을 부모에서
|
||||
// 상속한다(소유자 아님 → chmod 불가 환경은 silent no-op, 멱등).
|
||||
File::ensureDirectoryExists($backupRoot, 0775);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($backupRoot);
|
||||
FilePermissionHelper::syncGroupWritability($backupRoot);
|
||||
|
||||
File::ensureDirectoryExists($backupPath, 0775, true);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($backupPath);
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$sourcePath = base_path($target);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* editor-spec.json 합본 헬퍼.
|
||||
*
|
||||
* editor-spec.json 이 과대해져(admin 18k 줄) 상위 블록 단위로 분할되었다. 분할
|
||||
* 형식은 manifest(`editor-spec.json`)에 메타 + 소형 블록을 인라인으로 두고, 대형
|
||||
* 블록은 `$include` 맵으로 `editor-spec/{block}.json` 을 참조하는 구조다.
|
||||
*
|
||||
* 서빙 4개 사이트는 활성 디렉토리만 기준으로 합본한다 — `_bundled` 폴백은 없다
|
||||
* `_bundled` 작업분은 `{module,plugin,template}:update` 로 활성 디렉토리에
|
||||
* 반영된 뒤에만 런타임에 보인다. 다음 형태의 manifest 를 받는다:
|
||||
*
|
||||
* {
|
||||
* "templateId": "...", "version": "...", "darkMode": { ... },
|
||||
* "$include": {
|
||||
* "componentPalette": "editor-spec/componentPalette.json",
|
||||
* "controls": "editor-spec/controls.json"
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* 본 헬퍼는 manifest 의 `$include` 를 manifest 디렉토리 기준으로 해석해 단일
|
||||
* 병합 spec(top-level merge)으로 합본한다. 런타임 API 응답은 분할 전 단일 파일과
|
||||
* 동일한 형태(`array<string,mixed>`)를 유지하므로 프론트엔드 로더는 무영향이다.
|
||||
*
|
||||
* `$include` 가 없는 구버전/미분할 editor-spec.json 은 manifest 원본을 그대로
|
||||
* 반환한다(하위 호환). include 파일 미존재/파싱 실패 시 해당 키만 누락하고 경고를
|
||||
* 남긴다(무손실 디그레이드).
|
||||
*
|
||||
*/
|
||||
class EditorSpecAssembler
|
||||
{
|
||||
/**
|
||||
* manifest 파일을 디코드하고 `$include` 블록을 합본한 단일 spec 을 반환합니다.
|
||||
*
|
||||
* `$include` 부재 시 manifest 원본을 그대로 반환합니다(하위 호환). include 경로는
|
||||
* manifest 가 위치한 디렉토리 기준 상대 경로로 해석합니다.
|
||||
*
|
||||
* @param string $manifestPath editor-spec.json manifest 의 절대 경로
|
||||
* @return array<string, mixed>|null 합본 spec, 디코드 실패 시 null
|
||||
*/
|
||||
public static function assemble(string $manifestPath): ?array
|
||||
{
|
||||
$manifest = self::decodeJsonFile($manifestPath);
|
||||
if ($manifest === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$includes = $manifest['$include'] ?? null;
|
||||
unset($manifest['$include']);
|
||||
|
||||
if (! is_array($includes) || $includes === []) {
|
||||
// 미분할(구버전) editor-spec.json — manifest 원본 그대로 반환.
|
||||
return $manifest;
|
||||
}
|
||||
|
||||
$baseDir = \dirname($manifestPath);
|
||||
|
||||
foreach ($includes as $key => $relative) {
|
||||
if (! is_string($key) || ! is_string($relative) || $relative === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$blockPath = $baseDir.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
|
||||
$block = self::decodeJsonFile($blockPath);
|
||||
|
||||
if ($block === null) {
|
||||
// include 파일 미존재/파싱 실패 — 해당 키 누락(무손실 디그레이드) + 경고.
|
||||
Log::warning('EditorSpecAssembler: include 블록 로드 실패', [
|
||||
'manifest' => $manifestPath,
|
||||
'block' => $key,
|
||||
'path' => $blockPath,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// top-level merge — include 결과가 해당 key 의 값이 된다.
|
||||
// manifest 인라인 값이 있으면 include 가 덮어쓴다(분할본이 정본).
|
||||
$manifest[$key] = $block;
|
||||
}
|
||||
|
||||
return $manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 파일을 읽어 배열로 디코드합니다. 미존재/비배열/파싱 실패 시 null.
|
||||
*
|
||||
* @param string $path 절대 경로
|
||||
* @return array<string, mixed>|null 디코드된 배열, 실패 시 null
|
||||
*/
|
||||
private static function decodeJsonFile(string $path): ?array
|
||||
{
|
||||
if (! file_exists($path) || ! is_file($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decoded = json_decode((string) file_get_contents($path), true);
|
||||
|
||||
return is_array($decoded) ? $decoded : null;
|
||||
}
|
||||
}
|
||||
@@ -33,9 +33,22 @@ class ExtensionBackupHelper
|
||||
}
|
||||
|
||||
$timestamp = date('Ymd_His');
|
||||
$backupRoot = storage_path('app/extension_backups');
|
||||
$backupTypeDir = storage_path("app/extension_backups/{$type}");
|
||||
$backupPath = storage_path("app/extension_backups/{$type}/{$identifier}_{$timestamp}");
|
||||
|
||||
File::ensureDirectoryExists(dirname($backupPath));
|
||||
// 백업 부모 체인(extension_backups → {type})을 php-fpm 그룹이 쓸 수 있도록 보장한다.
|
||||
//
|
||||
// sudo 업데이트가 이 디렉토리들을 root/운영자 소유 + g-w(0755) 로 만들어 두면, 이후
|
||||
// www-data(php-fpm) 가 그 안에 백업 디렉토리를 mkdir 하지 못해 "mkdir(): Permission
|
||||
// denied" 로 실패한다(백업 생성 단계 중단). 디렉토리를 g+w(0775) 로 생성하고, 이미
|
||||
// 존재하면 부모 소유권 상속 + g+w 승격으로 정상화한다. 소유자가 아니라 chmod 가
|
||||
// 불가한 환경에서는 silent no-op(멱등) — 운영자가 디렉토리 권한을 직접 부여한다.
|
||||
foreach ([$backupRoot, $backupTypeDir] as $dir) {
|
||||
File::ensureDirectoryExists($dir, 0775);
|
||||
FilePermissionHelper::inheritOwnershipFromParent($dir);
|
||||
FilePermissionHelper::syncGroupWritability($dir);
|
||||
}
|
||||
|
||||
// 파일별 복사로 진행 상세 보고
|
||||
self::copyDirectoryWithProgress($sourcePath, $backupPath, $sourcePath, $onProgress);
|
||||
@@ -58,6 +71,8 @@ class ExtensionBackupHelper
|
||||
?\Closure $onProgress = null
|
||||
): void {
|
||||
File::ensureDirectoryExists($dest, 0775);
|
||||
// 백업 디렉토리 트리도 부모 소유권을 상속해 sudo update 후 root 소유 잔존을 차단한다.
|
||||
FilePermissionHelper::inheritOwnershipFromParent($dest);
|
||||
$items = new \FilesystemIterator($source, \FilesystemIterator::SKIP_DOTS);
|
||||
|
||||
foreach ($items as $item) {
|
||||
|
||||
@@ -126,7 +126,17 @@ class ExtensionMenuSyncHelper
|
||||
$updateData['url'] = $newAttributes['url'] ?? null;
|
||||
}
|
||||
|
||||
$this->menuRepository->update($existing, $updateData);
|
||||
// user_overrides 자동 마킹 비활성화 — 시스템 sync 컨텍스트는 사용자 변경이 아님.
|
||||
// HasUserOverrides::bootHasUserOverrides 의 updating 이벤트 hook 이 'seeding' 플래그를
|
||||
// 보고 자동 마킹을 건너뛴다. 미설정 시 동일한 module.php 정의값을 적용해도 icon/name/order
|
||||
// 등 trackable 필드가 dirty 로 잡혀 user_overrides 에 자동 추가되어, 이후 sync 가 차단되는
|
||||
// 결함이 발생한다.
|
||||
app()->instance('user_overrides.seeding', true);
|
||||
try {
|
||||
$this->menuRepository->update($existing, $updateData);
|
||||
} finally {
|
||||
app()->forgetInstance('user_overrides.seeding');
|
||||
}
|
||||
|
||||
return $existing->fresh();
|
||||
}
|
||||
|
||||
@@ -87,7 +87,17 @@ class ExtensionRoleSyncHelper
|
||||
// 기타 속성 병합
|
||||
$updateData = array_merge($updateData, $otherAttributes);
|
||||
|
||||
$this->roleRepository->update($existing, $updateData);
|
||||
// user_overrides 자동 마킹 비활성화 — 시스템 sync 컨텍스트는 사용자 변경이 아님.
|
||||
// ExtensionMenuSyncHelper 와 동일 패턴 (HasUserOverrides::bootHasUserOverrides 의
|
||||
// updating 이벤트 hook 이 'seeding' 플래그를 보고 자동 마킹을 건너뛴다).
|
||||
// 미설정 시 동일한 정의값을 적용해도 name/description 등 trackable 필드가 dirty 로
|
||||
// 잡혀 user_overrides 에 자동 추가되어 이후 sync 가 차단되는 결함이 발생한다.
|
||||
app()->instance('user_overrides.seeding', true);
|
||||
try {
|
||||
$this->roleRepository->update($existing, $updateData);
|
||||
} finally {
|
||||
app()->forgetInstance('user_overrides.seeding');
|
||||
}
|
||||
|
||||
return $existing->fresh();
|
||||
}
|
||||
|
||||
@@ -16,20 +16,24 @@ class FilePermissionHelper
|
||||
* - 신규 파일: 부모 디렉토리의 소유자/그룹 상속 (퍼미션은 PHP 기본 umask)
|
||||
* - removeOrphans=false: 소스에 없고 대상에만 있는 파일 유지 (사용자 추가 파일 보호)
|
||||
* - removeOrphans=true: 소스에 없고 대상에만 있는 파일/디렉토리 삭제 (excludes 제외)
|
||||
* - preserveTopLevelOrphans=true: removeOrphans=true 라도 *최상위 한 레벨* 에서 소스에
|
||||
* 없는 항목(디렉토리/파일)은 삭제하지 않는다. 소스에 존재하는 디렉토리 내부의
|
||||
* orphan 정리는 그대로 수행된다. 코어 업데이트가 `{domain}/_bundled` 를 sync 할 때
|
||||
* 사용자가 `_bundled/` 바로 아래에 직접 만든 커스텀 확장 디렉토리를 보존하기 위함.
|
||||
*
|
||||
* 신규 항목의 소유권 상속은 sudo 로 실행된 업데이트 프로세스가 root 소유로 파일을
|
||||
* 생성하는 것을 방지한다. vendor/ 처럼 cleanDirectory 후 재생성되는 디렉토리 구조
|
||||
* 전체가 기존 부모(= vendor/) 의 소유권을 승계하도록 보장한다.
|
||||
*
|
||||
* @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
|
||||
* @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 소스에 없는 대상 파일/디렉토리 삭제 여부
|
||||
* @param bool $preserveTopLevelOrphans 최상위 한 레벨의 orphan 보존 여부
|
||||
*/
|
||||
public static function copyDirectory(string $source, string $destination, ?\Closure $onProgress = null, array $excludes = [], string $relativePath = '', bool $removeOrphans = false): void
|
||||
public static function copyDirectory(string $source, string $destination, ?\Closure $onProgress = null, array $excludes = [], string $relativePath = '', bool $removeOrphans = false, bool $preserveTopLevelOrphans = false): void
|
||||
{
|
||||
if (! File::isDirectory($destination)) {
|
||||
// 신규 디렉토리: 부모 디렉토리의 퍼미션/소유권 상속
|
||||
@@ -61,7 +65,8 @@ class FilePermissionHelper
|
||||
}
|
||||
|
||||
if ($item->isDir()) {
|
||||
static::copyDirectory($item->getPathname(), $destPath, $onProgress, $excludes, $itemRelativePath, $removeOrphans);
|
||||
// preserveTopLevelOrphans 는 최상위 한 레벨 한정 — 자식 재귀에는 항상 false 전달.
|
||||
static::copyDirectory($item->getPathname(), $destPath, $onProgress, $excludes, $itemRelativePath, $removeOrphans, preserveTopLevelOrphans: false);
|
||||
} else {
|
||||
static::copyFile($item->getPathname(), $destPath);
|
||||
}
|
||||
@@ -69,7 +74,7 @@ class FilePermissionHelper
|
||||
|
||||
// 소스에 없는 대상 파일/디렉토리 삭제
|
||||
if ($removeOrphans && File::isDirectory($destination)) {
|
||||
static::removeOrphanItems($source, $destination, $excludes, $relativePath);
|
||||
static::removeOrphanItems($source, $destination, $excludes, $relativePath, $preserveTopLevelOrphans);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +91,7 @@ class FilePermissionHelper
|
||||
*
|
||||
* @param string $source 소스 symlink 경로
|
||||
* @param string $destination 대상 symlink 경로
|
||||
* @return bool symlink 복원 성공 여부 (false 면 호출자가 일반 복사로 폴백)
|
||||
* @return bool symlink 복원 성공 여부 (false 면 호출자가 일반 복사로 폴백)
|
||||
*/
|
||||
protected static function copySymlink(string $source, string $destination): bool
|
||||
{
|
||||
@@ -122,14 +127,21 @@ class FilePermissionHelper
|
||||
*
|
||||
* excludes 목록에 해당하는 항목은 삭제하지 않습니다.
|
||||
*
|
||||
* @param string $source 소스 디렉토리 경로
|
||||
* @param string $destination 대상 디렉토리 경로
|
||||
* @param array $excludes 제외할 이름 또는 경로 목록
|
||||
* @param string $relativePath 현재 상대 경로
|
||||
* @return void
|
||||
* @param string $source 소스 디렉토리 경로
|
||||
* @param string $destination 대상 디렉토리 경로
|
||||
* @param array $excludes 제외할 이름 또는 경로 목록
|
||||
* @param string $relativePath 현재 상대 경로
|
||||
* @param bool $preserveTopLevelOrphans 최상위 한 레벨의 orphan 보존 여부
|
||||
*/
|
||||
protected static function removeOrphanItems(string $source, string $destination, array $excludes, string $relativePath): void
|
||||
protected static function removeOrphanItems(string $source, string $destination, array $excludes, string $relativePath, bool $preserveTopLevelOrphans = false): void
|
||||
{
|
||||
// 최상위 한 레벨에서 소스에 없는 항목(사용자 추가) 보존 — `_bundled/my-project` 등.
|
||||
// 호출자(copyDirectory)는 최상위 진입 시에만 relativePath='' + 플래그 true 로 들어오며,
|
||||
// 자식 재귀에는 항상 false 가 전달되므로 본 분기는 최상위에서만 활성화된다.
|
||||
if ($preserveTopLevelOrphans && $relativePath === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$destItems = new \FilesystemIterator($destination, \FilesystemIterator::SKIP_DOTS);
|
||||
|
||||
foreach ($destItems as $destItem) {
|
||||
@@ -165,9 +177,9 @@ class FilePermissionHelper
|
||||
* - 단순 이름 (슬래시 미포함): 모든 레벨에서 해당 이름과 매칭
|
||||
* - 경로 패턴 (슬래시 포함): 상대 경로와 정확히 매칭
|
||||
*
|
||||
* @param string $itemName 현재 항목의 파일/디렉토리 이름
|
||||
* @param string $itemRelativePath 루트로부터의 상대 경로
|
||||
* @param array $excludes 제외 목록
|
||||
* @param string $itemName 현재 항목의 파일/디렉토리 이름
|
||||
* @param string $itemRelativePath 루트로부터의 상대 경로
|
||||
* @param array $excludes 제외 목록
|
||||
* @return bool 제외 대상 여부
|
||||
*/
|
||||
public static function isExcluded(string $itemName, string $itemRelativePath, array $excludes): bool
|
||||
@@ -199,9 +211,8 @@ class FilePermissionHelper
|
||||
* 파일을 생성하는 문제를 방지하기 위함이다. vendor/ 내부처럼 cleanDirectory 후
|
||||
* 전량 재생성되는 경로에서 필요하다.
|
||||
*
|
||||
* @param string $source 소스 파일
|
||||
* @param string $destination 대상 파일
|
||||
* @return void
|
||||
* @param string $source 소스 파일
|
||||
* @param string $destination 대상 파일
|
||||
*/
|
||||
public static function copyFile(string $source, string $destination): void
|
||||
{
|
||||
@@ -239,8 +250,7 @@ class FilePermissionHelper
|
||||
/**
|
||||
* 부모 디렉토리의 퍼미션·소유자·그룹을 상속하여 신규 디렉토리를 생성합니다.
|
||||
*
|
||||
* @param string $path 생성할 디렉토리 경로
|
||||
* @return void
|
||||
* @param string $path 생성할 디렉토리 경로
|
||||
*/
|
||||
protected static function createDirectoryInheritingParent(string $path): void
|
||||
{
|
||||
@@ -262,7 +272,6 @@ class FilePermissionHelper
|
||||
* 외부 호출처(예: `SettingsMigrator::writeJsonFile`) 가 직접 호출 가능하도록 public.
|
||||
*
|
||||
* @param string $path 소유권을 상속받을 파일 또는 디렉토리
|
||||
* @return void
|
||||
*/
|
||||
public static function inheritOwnershipFromParent(string $path): void
|
||||
{
|
||||
@@ -277,10 +286,9 @@ class FilePermissionHelper
|
||||
/**
|
||||
* 소유자·그룹을 적용합니다. sudo 없이 실행 시 silent fail 로 현행 동작 유지.
|
||||
*
|
||||
* @param string $path 대상 경로
|
||||
* @param int|false $owner fileowner() 반환값 (false 허용)
|
||||
* @param int|false $group filegroup() 반환값 (false 허용)
|
||||
* @return void
|
||||
* @param string $path 대상 경로
|
||||
* @param int|false $owner fileowner() 반환값 (false 허용)
|
||||
* @param int|false $group filegroup() 반환값 (false 허용)
|
||||
*/
|
||||
protected static function applyOwnership(string $path, int|false $owner, int|false $group): void
|
||||
{
|
||||
@@ -303,7 +311,7 @@ class FilePermissionHelper
|
||||
* - sudo 실행된 업데이트가 원본 스냅샷을 수집하지 못한 경우의 fallback
|
||||
* - 외부 프로세스(composer 등) 가 root 로 오염시킨 경로의 원본 추정
|
||||
*
|
||||
* @return array{0: int|false, 1: int|false, 2: string} [owner, group, source]
|
||||
* @return array{0: int|false, 1: int|false, 2: string} [owner, group, source]
|
||||
*/
|
||||
public static function inferWebServerOwnership(): array
|
||||
{
|
||||
@@ -345,9 +353,9 @@ class FilePermissionHelper
|
||||
* 처리하고 대상은 따라가지 않는다. @chown/@chgrp suppress 로 권한 부족 / chown 미지원
|
||||
* 환경에서도 silent fail.
|
||||
*
|
||||
* @param string $path 대상 경로 (파일 또는 디렉토리)
|
||||
* @param int $owner 기준 소유자 UID
|
||||
* @param int|false $group 기준 그룹 GID (false = 그룹 유지)
|
||||
* @param string $path 대상 경로 (파일 또는 디렉토리)
|
||||
* @param int $owner 기준 소유자 UID
|
||||
* @param int|false $group 기준 그룹 GID (false = 그룹 유지)
|
||||
* @return int 실제 소유권을 변경한 항목 수
|
||||
*/
|
||||
public static function chownRecursive(string $path, int $owner, int|false $group): int
|
||||
@@ -421,7 +429,7 @@ class FilePermissionHelper
|
||||
* - silent fail — 권한 부족·chmod 미지원 환경에서도 예외 미발생
|
||||
*
|
||||
* @param string $root 대상 루트 (재귀 순회)
|
||||
* @return int 실제 chmod 한 항목 수
|
||||
* @return int 실제 chmod 한 항목 수
|
||||
*/
|
||||
public static function syncGroupWritability(string $root): int
|
||||
{
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use App\Contracts\Repositories\IdentityPolicyRepositoryInterface;
|
||||
use App\Listeners\Identity\EnforceIdentityPolicyListener;
|
||||
use App\Models\IdentityPolicy;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -18,6 +20,13 @@ use Illuminate\Support\Facades\Log;
|
||||
*/
|
||||
class IdentityPolicySyncHelper
|
||||
{
|
||||
/**
|
||||
* @param IdentityPolicyRepositoryInterface $repository 정책 데이터 접근 Repository
|
||||
*/
|
||||
public function __construct(
|
||||
protected IdentityPolicyRepositoryInterface $repository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 정책을 동기화합니다 (user_overrides 보존 upsert).
|
||||
*
|
||||
@@ -29,7 +38,7 @@ class IdentityPolicySyncHelper
|
||||
*/
|
||||
public function syncPolicy(array $data): IdentityPolicy
|
||||
{
|
||||
return IdentityPolicy::syncOrCreateFromUpgrade(
|
||||
$policy = IdentityPolicy::syncOrCreateFromUpgrade(
|
||||
['key' => $data['key']],
|
||||
[
|
||||
'scope' => $data['scope'] ?? 'route',
|
||||
@@ -46,6 +55,15 @@ class IdentityPolicySyncHelper
|
||||
'fail_mode' => $data['fail_mode'] ?? 'block',
|
||||
]
|
||||
);
|
||||
|
||||
// scope=hook 정책이 새로 적재되면 그 target 에 enforce 구독을 멱등 (재)바인딩한다.
|
||||
// 코어 리스너 자동발견은 부팅 전반부에 1회만 일어나 그 시점에 없던 모듈 hook target 을
|
||||
// 놓치므로, 정책이 DB 에 적재되는 이 시점에 보충한다(이미 바인딩된 target 은 멱등 스킵).
|
||||
if (($policy->scope instanceof \BackedEnum ? $policy->scope->value : $policy->scope) === 'hook') {
|
||||
EnforceIdentityPolicyListener::syncDynamicHookSubscriptions();
|
||||
}
|
||||
|
||||
return $policy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,16 +81,9 @@ class IdentityPolicySyncHelper
|
||||
string $sourceIdentifier,
|
||||
array $currentKeys,
|
||||
): int {
|
||||
$query = IdentityPolicy::query()
|
||||
->where('source_type', $sourceType)
|
||||
->where('source_identifier', $sourceIdentifier);
|
||||
|
||||
if (! empty($currentKeys)) {
|
||||
$query->whereNotIn('key', $currentKeys);
|
||||
}
|
||||
|
||||
$targets = $query->get(['id', 'key']);
|
||||
$targets = $this->repository->findStale($sourceType, $sourceIdentifier, $currentKeys);
|
||||
foreach ($targets as $policy) {
|
||||
// per-model delete — deleted 이벤트로 라우트 스코프 캐시가 flush 된다(bulk delete 와 차이).
|
||||
$policy->delete();
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ class HookListenerRegistrar
|
||||
*
|
||||
* 모듈 install/uninstall 시나리오에서 재등록이 필요하면 clear() 사용.
|
||||
*
|
||||
* @var array<string, true> key: "{source}::{listenerClass}"
|
||||
* @var array<string, true> key: "{source}::{listenerClass}"
|
||||
*/
|
||||
private static array $registered = [];
|
||||
|
||||
@@ -38,7 +38,6 @@ class HookListenerRegistrar
|
||||
*
|
||||
* @param string $listenerClass HookListenerInterface 구현 클래스의 FQCN
|
||||
* @param string|null $source 등록 출처 (로그용: 'core', 모듈/플러그인 식별자)
|
||||
* @return void
|
||||
*/
|
||||
public static function register(string $listenerClass, ?string $source = null): void
|
||||
{
|
||||
@@ -80,18 +79,8 @@ class HookListenerRegistrar
|
||||
app($listenerClass)->{$method}(...$args);
|
||||
}, $priority);
|
||||
} else {
|
||||
// Action 기본: 큐 디스패치
|
||||
// 큐 드라이버가 sync이면 Laravel이 즉시 실행 → 하위호환 보장
|
||||
// HookContextCapture::capture()로 Auth/Request/Locale 스냅샷을 함께 전달하여
|
||||
// 큐 워커에서 리스너가 평소처럼 사용자 컨텍스트를 사용할 수 있도록 한다.
|
||||
HookManager::addAction($hookName, function (...$args) use ($listenerClass, $method) {
|
||||
dispatch(new DispatchHookListenerJob(
|
||||
$listenerClass,
|
||||
$method,
|
||||
HookArgumentSerializer::serialize($args),
|
||||
HookContextCapture::capture(),
|
||||
));
|
||||
}, $priority);
|
||||
// Action 기본: 큐 디스패치 (큐 드라이버가 sync 면 Laravel 이 즉시 실행 → 하위호환)
|
||||
self::addQueuedAction($hookName, $listenerClass, $method, $priority);
|
||||
}
|
||||
|
||||
Log::info('훅 리스너 등록 완료', [
|
||||
@@ -106,13 +95,79 @@ class HookListenerRegistrar
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DB 기반 동적 훅을 큐 디스패치 정책에 맞춰 등록합니다.
|
||||
*
|
||||
* 정적 getSubscribedHooks() 으로 표현할 수 없는 동적 구독(DB 정의에 따라 훅 대상이
|
||||
* 런타임에 결정되는 경우, 예: NotificationHookListener::registerDynamicHooks)을 위한 진입점.
|
||||
* register() 의 Action 기본 동작과 동일하게 DispatchHookListenerJob 으로 큐 디스패치한다 —
|
||||
* 리스너가 직접 dispatch(new DispatchHookListenerJob(...)) 를 작성하지 않고 이 헬퍼에 위임하여,
|
||||
* 큐 래핑 로직의 소유권을 Registrar 한 곳에 유지한다(정적/동적 일관).
|
||||
*
|
||||
* $boundArgs 로 훅 발화 인자 앞에 고정 인자(예: NotificationDefinition)를 붙일 수 있다.
|
||||
* 워커는 listenerClass::method(...$boundArgs, ...$hookArgs) 형태로 복원 호출한다.
|
||||
*
|
||||
* @param string $hookName 구독할 훅 이름
|
||||
* @param string $listenerClass 리스너 FQCN
|
||||
* @param string $method 큐 워커에서 호출할 public 메서드명
|
||||
* @param array<int, mixed> $boundArgs 훅 발화 인자 앞에 고정으로 붙일 인자 (직렬화 가능해야 함)
|
||||
* @param int $priority 실행 우선순위
|
||||
* @param bool $sync true 면 큐 래핑 없이 즉시 동기 실행 (큐 드라이버 무관)
|
||||
*/
|
||||
public static function registerDynamicAction(
|
||||
string $hookName,
|
||||
string $listenerClass,
|
||||
string $method,
|
||||
array $boundArgs = [],
|
||||
int $priority = 10,
|
||||
bool $sync = false,
|
||||
): void {
|
||||
if ($sync) {
|
||||
HookManager::addAction($hookName, function (...$args) use ($listenerClass, $method, $boundArgs) {
|
||||
app($listenerClass)->{$method}(...$boundArgs, ...$args);
|
||||
}, $priority);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
self::addQueuedAction($hookName, $listenerClass, $method, $priority, $boundArgs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 훅에 큐 디스패치(DispatchHookListenerJob) 콜백을 등록합니다 (정적/동적 공통).
|
||||
*
|
||||
* 큐 드라이버가 sync 면 Laravel 이 즉시 실행하므로 하위호환은 그대로 유지된다.
|
||||
* HookContextCapture::capture() 로 Auth/Request/Locale 스냅샷을 함께 전달하여
|
||||
* 큐 워커에서 리스너가 평소처럼 사용자 컨텍스트를 사용할 수 있도록 한다.
|
||||
*
|
||||
* @param string $hookName 구독할 훅 이름
|
||||
* @param string $listenerClass 리스너 FQCN
|
||||
* @param string $method 큐 워커에서 호출할 메서드명
|
||||
* @param int $priority 실행 우선순위
|
||||
* @param array<int, mixed> $boundArgs 훅 발화 인자 앞에 고정으로 붙일 인자
|
||||
*/
|
||||
private static function addQueuedAction(
|
||||
string $hookName,
|
||||
string $listenerClass,
|
||||
string $method,
|
||||
int $priority,
|
||||
array $boundArgs = [],
|
||||
): void {
|
||||
HookManager::addAction($hookName, function (...$args) use ($listenerClass, $method, $boundArgs) {
|
||||
dispatch(new DispatchHookListenerJob(
|
||||
$listenerClass,
|
||||
$method,
|
||||
HookArgumentSerializer::serialize([...$boundArgs, ...$args]),
|
||||
HookContextCapture::capture(),
|
||||
));
|
||||
}, $priority);
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록 이력 캐시를 비웁니다.
|
||||
*
|
||||
* 모듈 install/uninstall 시나리오 또는 테스트 격리가 필요할 때 호출.
|
||||
* 캐시 비운 후 register() 호출하면 listener 가 다시 HookManager 에 추가됨.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function clear(): void
|
||||
{
|
||||
|
||||
@@ -23,6 +23,7 @@ final class VerificationChallenge
|
||||
* @param string|null $redirectUrl external_redirect 일 때 이동할 외부 URL
|
||||
* @param array $publicPayload 프론트에 내려줄 공개 페이로드 (민감정보 제외)
|
||||
* @param array $metadata 서버 내부 참조용 데이터
|
||||
* @param int $maxAttempts 허용 최대 시도 횟수 (0 = 무제한, popup/SDK 형 provider 가 사용)
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $id,
|
||||
@@ -35,6 +36,7 @@ final class VerificationChallenge
|
||||
public readonly ?string $redirectUrl = null,
|
||||
public readonly array $publicPayload = [],
|
||||
public readonly array $metadata = [],
|
||||
public readonly int $maxAttempts = 0,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -53,6 +55,7 @@ final class VerificationChallenge
|
||||
'redirect_url' => $this->redirectUrl,
|
||||
'expires_at' => $this->expiresAt->toIso8601String(),
|
||||
'public_payload' => $this->publicPayload,
|
||||
'max_attempts' => $this->maxAttempts,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,18 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
return ['email'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 채널 키 → 다국어 표시 라벨 맵을 반환합니다.
|
||||
*
|
||||
* @return array<string, string> 채널 키 → 라벨 맵
|
||||
*/
|
||||
public function getChannelLabels(): array
|
||||
{
|
||||
return [
|
||||
'email' => __('identity.channels.email'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본 렌더 힌트를 반환합니다.
|
||||
*
|
||||
@@ -193,6 +205,7 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
renderHint: $renderHint,
|
||||
publicPayload: $publicPayload,
|
||||
metadata: [],
|
||||
maxAttempts: $maxAttempts,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -244,10 +257,16 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
]);
|
||||
|
||||
if ($storedHash === null || ! Hash::check($provided, $storedHash)) {
|
||||
// 이번 오답으로 max_attempts 에 도달하면 잠금(Failed)으로 전환하고, 사용자에게
|
||||
// 일반 오답 안내 대신 "최대 시도 초과 + 재요청" 안내(MAX_ATTEMPTS)를 반환한다.
|
||||
// 프론트 모달은 도달 즉시 확인 버튼을 비활성화하므로 추가 시도를 기대할 수 없어,
|
||||
// 막 소진된 이 응답에서 안내하지 않으면 max_attempts 문구가 사용자에게 영영 도달하지 못한다.
|
||||
if (($log->attempts + 1) >= $log->max_attempts) {
|
||||
$this->logRepository->updateById($log->id, [
|
||||
'status' => IdentityVerificationStatus::Failed->value,
|
||||
]);
|
||||
|
||||
return VerificationResult::failure($challengeId, self::ID, 'MAX_ATTEMPTS', 'identity.errors.max_attempts');
|
||||
}
|
||||
|
||||
return VerificationResult::failure($challengeId, self::ID, 'INVALID_CODE', 'identity.errors.invalid_code');
|
||||
@@ -349,15 +368,9 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
/**
|
||||
* IDV 전용 메시지 디스패처를 통해 메일을 발송합니다.
|
||||
*
|
||||
* @param string $email
|
||||
* @param string $purpose
|
||||
* @param string $renderHint text_code | link
|
||||
* @param string $challengeId
|
||||
* @param string|null $policyKey
|
||||
* @param string|null $code text_code 흐름 시 평문 인증 코드
|
||||
* @param string|null $linkToken link 흐름 시 서명 링크용 raw 토큰
|
||||
* @param int $ttlMinutes
|
||||
* @param Carbon $expiresAt
|
||||
* @return bool 발송 성공 여부
|
||||
*/
|
||||
protected function dispatchMessage(
|
||||
@@ -411,11 +424,6 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
|
||||
/**
|
||||
* link 흐름용 서명 링크를 생성합니다.
|
||||
*
|
||||
* @param string $challengeId
|
||||
* @param string $linkToken
|
||||
* @param Carbon $expiresAt
|
||||
* @return string
|
||||
*/
|
||||
protected function buildSignedLink(string $challengeId, string $linkToken, Carbon $expiresAt): string
|
||||
{
|
||||
@@ -433,9 +441,6 @@ class MailIdentityProvider implements IdentityVerificationInterface
|
||||
|
||||
/**
|
||||
* purpose 라벨(다국어)을 현재 로케일 문자열로 해석합니다.
|
||||
*
|
||||
* @param string $purpose
|
||||
* @return string
|
||||
*/
|
||||
protected function resolvePurposeLabel(string $purpose): string
|
||||
{
|
||||
|
||||
@@ -18,6 +18,7 @@ use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
|
||||
use App\Extension\Helpers\DependencyEnricher;
|
||||
use App\Extension\Helpers\ExtensionBackupHelper;
|
||||
use App\Extension\Helpers\ExtensionMenuSyncHelper;
|
||||
@@ -26,8 +27,6 @@ use App\Extension\Helpers\ExtensionRoleSyncHelper;
|
||||
use App\Extension\Helpers\ExtensionStatusGuard;
|
||||
use App\Extension\Helpers\ExtensionUpgradeGuardHelper;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Providers\CoreServiceProvider;
|
||||
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
use App\Extension\Helpers\NotificationSyncHelper;
|
||||
@@ -36,9 +35,11 @@ use App\Extension\Vendor\VendorInstallContext;
|
||||
use App\Extension\Vendor\VendorInstallResult;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use App\Extension\Vendor\VendorResolver;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\Module;
|
||||
use App\Models\Plugin;
|
||||
use App\Models\Template;
|
||||
use App\Providers\CoreServiceProvider;
|
||||
use App\Services\LayoutExtensionService;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
@@ -424,6 +425,14 @@ class ModuleManager implements ModuleManagerInterface
|
||||
$name = $this->convertToMultilingual($module->getName());
|
||||
$description = $this->convertToMultilingual($module->getDescription());
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
|
||||
$manifest = HookManager::applyFilters(
|
||||
"module.{$module->getIdentifier()}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
|
||||
// 데이터베이스에 모듈 정보 저장
|
||||
$this->moduleRepository->updateOrCreate(
|
||||
['identifier' => $module->getIdentifier()],
|
||||
@@ -536,7 +545,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
);
|
||||
}
|
||||
|
||||
// 코어 버전 호환성 사전 검증 (#306 sync 훅보다 앞쪽)
|
||||
// 코어 버전 호환성 사전 검증
|
||||
if (! $force && ! CoreServiceProvider::isCoreUpdateInProgress()) {
|
||||
CoreVersionChecker::validateExtension(
|
||||
$module->getRequiredCoreVersion(),
|
||||
@@ -635,6 +644,10 @@ class ModuleManager implements ModuleManagerInterface
|
||||
|
||||
// 모듈 상태 캐시 무효화
|
||||
self::invalidateModuleStatusCache();
|
||||
|
||||
// 본인인증 route scope 캐시 무효화 — 재활성화 시 이 모듈이 선언한 정책이
|
||||
// 다시 enforce 대상에 포함되도록 한다 (applyActiveExtensionScope 재평가).
|
||||
IdentityPolicy::flushRouteScopeCache();
|
||||
}
|
||||
|
||||
// 훅 발행: 모듈 활성화 완료
|
||||
@@ -773,6 +786,11 @@ class ModuleManager implements ModuleManagerInterface
|
||||
// 모듈 상태 캐시 무효화
|
||||
self::invalidateModuleStatusCache();
|
||||
|
||||
// 본인인증 route scope 캐시 무효화 — 비활성 모듈이 선언한 정책이 enforce 대상에서
|
||||
// 즉시 제외되도록 한다. 정책 행 자체는 변경하지 않으므로(enabled 운영자 설정 보존)
|
||||
// IdentityPolicy 모델 이벤트가 발화하지 않아, 라이프사이클에서 명시적으로 호출한다.
|
||||
IdentityPolicy::flushRouteScopeCache();
|
||||
|
||||
// 요구사항 #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
|
||||
HookManager::doAction('core.modules.after_deactivate', $module->getIdentifier());
|
||||
}
|
||||
@@ -1498,7 +1516,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
* 중첩 구조 의존성 배열을 순회하며 (identifier => declaredType) 를 yield 합니다.
|
||||
*
|
||||
* @param array $dependencies ['modules' => [...], 'plugins' => [...]] 형식
|
||||
* @return \Generator<string, string> identifier => 'module'|'plugin'
|
||||
* @return \Generator<string, string> identifier => 'module'|'plugin'
|
||||
*/
|
||||
private function iterateNestedDependencies(array $dependencies): \Generator
|
||||
{
|
||||
@@ -1892,7 +1910,6 @@ class ModuleManager implements ModuleManagerInterface
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 단일 마이그레이션 파일을 롤백합니다.
|
||||
*
|
||||
@@ -2520,10 +2537,6 @@ class ModuleManager implements ModuleManagerInterface
|
||||
|
||||
/**
|
||||
* 해당 source 가 기존에 등록한 IDV 정책이 있는지 확인합니다.
|
||||
*
|
||||
* @param string $sourceType
|
||||
* @param string $sourceIdentifier
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasExistingIdentityPolicies(string $sourceType, string $sourceIdentifier): bool
|
||||
{
|
||||
@@ -2587,9 +2600,6 @@ class ModuleManager implements ModuleManagerInterface
|
||||
*
|
||||
* `$module` 에서 현재 정의된 식별자/slug 를 수집하여 helper 의 `cleanupStale*` 호출.
|
||||
* user_overrides 보존 및 `users.role_id` 참조 역할 삭제 차단은 helper 가 담당.
|
||||
*
|
||||
* @param ModuleInterface $module
|
||||
* @return void
|
||||
*/
|
||||
protected function cleanupStaleModuleEntries(ModuleInterface $module): void
|
||||
{
|
||||
@@ -3274,7 +3284,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
*
|
||||
* @param string $moduleName 모듈명
|
||||
* @param bool $preserveModified true 시 사용자가 UI에서 수정한 레이아웃은 덮어쓰지 않음
|
||||
* (original_content_hash 와 현재 content hash 비교)
|
||||
* (original_content_hash 와 현재 content hash 비교)
|
||||
* @return array{success: bool, layouts_refreshed: int} 갱신 결과 및 갱신된 레이아웃 개수
|
||||
*
|
||||
* @throws \Exception 모듈을 찾을 수 없거나 레이아웃 갱신 실패 시
|
||||
@@ -3446,7 +3456,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
// 레이아웃 확장(extension)은 모든 활성 템플릿에 적용될 수 있으므로
|
||||
// admin 템플릿뿐만 아니라 모든 활성 템플릿에 대해 갱신
|
||||
$allActiveTemplates = $this->templateRepository->getActive();
|
||||
$extensionStats = $this->refreshLayoutExtensions($module, $allActiveTemplates);
|
||||
$extensionStats = $this->refreshLayoutExtensions($module, $allActiveTemplates, $preserveModified);
|
||||
|
||||
// 레이아웃 또는 레이아웃 확장이 실제로 변경된 경우에만 캐시 버전 증가
|
||||
$extensionChanged = ($extensionStats['created'] ?? 0) > 0 || ($extensionStats['updated'] ?? 0) > 0;
|
||||
@@ -3474,11 +3484,12 @@ class ModuleManager implements ModuleManagerInterface
|
||||
*
|
||||
* @param ModuleInterface $module 모듈 인스턴스
|
||||
* @param Collection $adminTemplates admin 템플릿 컬렉션
|
||||
* @return array{refreshed: int, created: int, updated: int, deleted: int} 갱신 통계
|
||||
* @param bool $preserveModified 관리자가 편집한 확장을 보존할지 여부 (--layout-strategy=keep)
|
||||
* @return array{refreshed: int, created: int, updated: int, deleted: int, skipped: int} 갱신 통계
|
||||
*/
|
||||
protected function refreshLayoutExtensions(ModuleInterface $module, $adminTemplates): array
|
||||
protected function refreshLayoutExtensions(ModuleInterface $module, $adminTemplates, bool $preserveModified = false): array
|
||||
{
|
||||
return $this->refreshExtensionLayoutExtensions($module, $adminTemplates, LayoutSourceType::Module);
|
||||
return $this->refreshExtensionLayoutExtensions($module, $adminTemplates, LayoutSourceType::Module, $preserveModified);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4032,9 +4043,13 @@ class ModuleManager implements ModuleManagerInterface
|
||||
// 버전순 정렬
|
||||
uksort($filteredSteps, 'version_compare');
|
||||
|
||||
// 확장 업그레이드는 코어(sudo/root)와 다른 실행 주체(php-fpm/www-data)로 실행되므로
|
||||
// 코어 'upgrade' 채널과 로그 파일을 분리한다. 같은 파일 공유 시 root 소유 파일에
|
||||
// www-data 가 append 하지 못해 Permission denied 로 실패하던 결함을 원천 차단.
|
||||
$context = new UpgradeContext(
|
||||
fromVersion: $fromVersion,
|
||||
toVersion: $toVersion,
|
||||
logChannel: 'extension-upgrade',
|
||||
);
|
||||
|
||||
foreach ($filteredSteps as $stepVersion => $step) {
|
||||
@@ -4083,7 +4098,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
{
|
||||
$layouts = $this->layoutRepository->getBySourceIdentifier(
|
||||
$identifier,
|
||||
\App\Enums\LayoutSourceType::Module,
|
||||
LayoutSourceType::Module,
|
||||
);
|
||||
|
||||
$modifiedLayouts = $layouts->filter(function ($layout) {
|
||||
@@ -4146,8 +4161,7 @@ class ModuleManager implements ModuleManagerInterface
|
||||
?\Closure $onUpgradeStep = null,
|
||||
?string $sourceOverride = null,
|
||||
?string $zipPath = null,
|
||||
): array
|
||||
{
|
||||
): array {
|
||||
$record = $this->moduleRepository->findByIdentifier($identifier);
|
||||
if (! $record) {
|
||||
throw new \RuntimeException(__('modules.not_found', ['module' => $identifier]));
|
||||
@@ -4351,6 +4365,16 @@ class ModuleManager implements ModuleManagerInterface
|
||||
$name = $module ? $this->convertToMultilingual($module->getName()) : $record->name;
|
||||
$description = $module ? $this->convertToMultilingual($module->getDescription()) : $record->description;
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입 (install 경로와 동일)
|
||||
if ($module) {
|
||||
$manifest = HookManager::applyFilters(
|
||||
"module.{$identifier}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
}
|
||||
|
||||
$this->moduleRepository->updateByIdentifier($identifier, [
|
||||
'version' => $toVersion,
|
||||
'latest_version' => $toVersion,
|
||||
|
||||
@@ -18,26 +18,27 @@ use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Exceptions\LayoutIncludeException;
|
||||
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
|
||||
use App\Extension\Helpers\DependencyEnricher;
|
||||
use App\Extension\Helpers\ExtensionBackupHelper;
|
||||
use App\Extension\Helpers\ExtensionPendingHelper;
|
||||
use App\Extension\Helpers\ExtensionRoleSyncHelper;
|
||||
use App\Extension\Concerns\ResolvesExtensionSharedRecords;
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
use App\Extension\Helpers\NotificationSyncHelper;
|
||||
use App\Extension\Helpers\ExtensionStatusGuard;
|
||||
use App\Extension\Helpers\ExtensionUpgradeGuardHelper;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Providers\CoreServiceProvider;
|
||||
use App\Extension\Helpers\IdentityMessageSyncHelper;
|
||||
use App\Extension\Helpers\IdentityPolicySyncHelper;
|
||||
use App\Extension\Helpers\NotificationSyncHelper;
|
||||
use App\Extension\Vendor\Exceptions\VendorInstallException;
|
||||
use App\Extension\Vendor\VendorInstallContext;
|
||||
use App\Extension\Vendor\VendorInstallResult;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use App\Extension\Vendor\VendorResolver;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\Module;
|
||||
use App\Models\Plugin;
|
||||
use App\Models\Template;
|
||||
use App\Providers\CoreServiceProvider;
|
||||
use App\Services\DriverRegistryService;
|
||||
use App\Services\LayoutExtensionService;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -405,6 +406,14 @@ class PluginManager implements PluginManagerInterface
|
||||
$name = $this->convertToMultilingual($plugin->getName());
|
||||
$description = $this->convertToMultilingual($plugin->getDescription());
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
|
||||
$manifest = HookManager::applyFilters(
|
||||
"plugin.{$plugin->getIdentifier()}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
|
||||
// 데이터베이스에 플러그인 정보 저장
|
||||
$this->pluginRepository->updateOrCreate(
|
||||
['identifier' => $plugin->getIdentifier()],
|
||||
@@ -514,7 +523,7 @@ class PluginManager implements PluginManagerInterface
|
||||
);
|
||||
}
|
||||
|
||||
// 코어 버전 호환성 사전 검증 (#306 sync 훅보다 앞쪽)
|
||||
// 코어 버전 호환성 사전 검증
|
||||
// - force=true 시 우회 (CLI/웹 모두)
|
||||
// - 코어 업데이트 spawn 컨텍스트에서는 매니페스트와 코어 버전이 일시적으로
|
||||
// 어긋날 수 있어 자동 비활성화 가드와 동일 정책으로 스킵
|
||||
@@ -616,6 +625,10 @@ class PluginManager implements PluginManagerInterface
|
||||
|
||||
// 플러그인 상태 캐시 무효화
|
||||
self::invalidatePluginStatusCache();
|
||||
|
||||
// 본인인증 route scope 캐시 무효화 — 재활성화 시 이 플러그인이 선언한 정책이
|
||||
// 다시 enforce 대상에 포함되도록 한다 (applyActiveExtensionScope 재평가).
|
||||
IdentityPolicy::flushRouteScopeCache();
|
||||
}
|
||||
|
||||
// 훅 발행: 플러그인 활성화 완료
|
||||
@@ -757,6 +770,11 @@ class PluginManager implements PluginManagerInterface
|
||||
// 플러그인 상태 캐시 무효화
|
||||
self::invalidatePluginStatusCache();
|
||||
|
||||
// 본인인증 route scope 캐시 무효화 — 비활성 플러그인이 선언한 정책이 enforce
|
||||
// 대상에서 즉시 제외되도록 한다. 정책 행은 변경하지 않으므로(enabled 보존)
|
||||
// IdentityPolicy 모델 이벤트가 발화하지 않아, 라이프사이클에서 명시적으로 호출한다.
|
||||
IdentityPolicy::flushRouteScopeCache();
|
||||
|
||||
// 요구사항 #6: 비활성화 후 훅 발행 — 언어팩 cascade 등 후속 처리
|
||||
HookManager::doAction('core.plugins.after_deactivate', $plugin->getIdentifier());
|
||||
}
|
||||
@@ -893,7 +911,7 @@ class PluginManager implements PluginManagerInterface
|
||||
$this->removePluginPermissions($plugin);
|
||||
|
||||
// IDV 정책도 data 옵션 선택 시 제거 (user_overrides 손실 허용)
|
||||
if (\Illuminate\Support\Facades\Schema::hasTable('identity_policies')) {
|
||||
if (Schema::hasTable('identity_policies')) {
|
||||
try {
|
||||
app(IdentityPolicySyncHelper::class)
|
||||
->cleanupStalePolicies('plugin', $plugin->getIdentifier(), []);
|
||||
@@ -906,7 +924,7 @@ class PluginManager implements PluginManagerInterface
|
||||
}
|
||||
|
||||
// IDV 메시지 정의/템플릿도 data 옵션 선택 시 제거 (FK cascade 로 templates 자동 정리)
|
||||
if (\Illuminate\Support\Facades\Schema::hasTable('identity_message_definitions')) {
|
||||
if (Schema::hasTable('identity_message_definitions')) {
|
||||
try {
|
||||
app(IdentityMessageSyncHelper::class)
|
||||
->cleanupStaleDefinitions('plugin', $plugin->getIdentifier(), []);
|
||||
@@ -919,7 +937,7 @@ class PluginManager implements PluginManagerInterface
|
||||
}
|
||||
|
||||
// 알림 정의/템플릿도 data 옵션 선택 시 제거 (FK cascade 로 templates 자동 정리)
|
||||
if (\Illuminate\Support\Facades\Schema::hasTable('notification_definitions')) {
|
||||
if (Schema::hasTable('notification_definitions')) {
|
||||
try {
|
||||
app(NotificationSyncHelper::class)
|
||||
->cleanupStaleDefinitions('plugin', $plugin->getIdentifier(), []);
|
||||
@@ -1499,7 +1517,7 @@ class PluginManager implements PluginManagerInterface
|
||||
* 중첩 구조 의존성 배열을 순회하며 (identifier => declaredType) 를 yield 합니다.
|
||||
*
|
||||
* @param array $dependencies ['modules' => [...], 'plugins' => [...]] 형식
|
||||
* @return \Generator<string, string> identifier => 'module'|'plugin'
|
||||
* @return \Generator<string, string> identifier => 'module'|'plugin'
|
||||
*/
|
||||
private function iterateNestedDependencies(array $dependencies): \Generator
|
||||
{
|
||||
@@ -1960,9 +1978,6 @@ class PluginManager implements PluginManagerInterface
|
||||
*
|
||||
* 플러그인은 메뉴(getAdminMenus) 를 지원하지 않으므로 권한·역할만 대상.
|
||||
* user_overrides 보존 및 `users.role_id` 참조 역할 삭제 차단은 helper 가 담당.
|
||||
*
|
||||
* @param PluginInterface $plugin
|
||||
* @return void
|
||||
*/
|
||||
protected function cleanupStalePluginEntries(PluginInterface $plugin): void
|
||||
{
|
||||
@@ -2132,7 +2147,7 @@ class PluginManager implements PluginManagerInterface
|
||||
return;
|
||||
}
|
||||
|
||||
if (! \Illuminate\Support\Facades\Schema::hasTable('identity_policies')) {
|
||||
if (! Schema::hasTable('identity_policies')) {
|
||||
return; // 마이그레이션 미실행 환경 보호
|
||||
}
|
||||
|
||||
@@ -2178,7 +2193,7 @@ class PluginManager implements PluginManagerInterface
|
||||
return;
|
||||
}
|
||||
|
||||
if (! \Illuminate\Support\Facades\Schema::hasTable('identity_message_definitions')) {
|
||||
if (! Schema::hasTable('identity_message_definitions')) {
|
||||
return; // 마이그레이션 미실행 환경 보호
|
||||
}
|
||||
|
||||
@@ -2244,7 +2259,7 @@ class PluginManager implements PluginManagerInterface
|
||||
return;
|
||||
}
|
||||
|
||||
if (! \Illuminate\Support\Facades\Schema::hasTable('notification_definitions')) {
|
||||
if (! Schema::hasTable('notification_definitions')) {
|
||||
return; // 마이그레이션 미실행 환경 보호
|
||||
}
|
||||
|
||||
@@ -2290,15 +2305,11 @@ class PluginManager implements PluginManagerInterface
|
||||
|
||||
/**
|
||||
* 해당 source 가 기존에 등록한 IDV 정책이 있는지 확인합니다.
|
||||
*
|
||||
* @param string $sourceType
|
||||
* @param string $sourceIdentifier
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasExistingIdentityPolicies(string $sourceType, string $sourceIdentifier): bool
|
||||
{
|
||||
try {
|
||||
return \Illuminate\Support\Facades\DB::table('identity_policies')
|
||||
return DB::table('identity_policies')
|
||||
->where('source_type', $sourceType)
|
||||
->where('source_identifier', $sourceIdentifier)
|
||||
->exists();
|
||||
@@ -2313,7 +2324,7 @@ class PluginManager implements PluginManagerInterface
|
||||
protected function hasExistingIdentityMessageDefinitions(string $extensionType, string $extensionIdentifier): bool
|
||||
{
|
||||
try {
|
||||
return \Illuminate\Support\Facades\DB::table('identity_message_definitions')
|
||||
return DB::table('identity_message_definitions')
|
||||
->where('extension_type', $extensionType)
|
||||
->where('extension_identifier', $extensionIdentifier)
|
||||
->exists();
|
||||
@@ -2328,7 +2339,7 @@ class PluginManager implements PluginManagerInterface
|
||||
protected function hasExistingNotificationDefinitions(string $extensionType, string $extensionIdentifier): bool
|
||||
{
|
||||
try {
|
||||
return \Illuminate\Support\Facades\DB::table('notification_definitions')
|
||||
return DB::table('notification_definitions')
|
||||
->where('extension_type', $extensionType)
|
||||
->where('extension_identifier', $extensionIdentifier)
|
||||
->exists();
|
||||
@@ -3758,7 +3769,7 @@ class PluginManager implements PluginManagerInterface
|
||||
// 레이아웃 확장(extension)은 모든 활성 템플릿에 적용될 수 있으므로
|
||||
// admin 템플릿뿐만 아니라 모든 활성 템플릿에 대해 갱신
|
||||
$allActiveTemplates = $this->templateRepository->getActive();
|
||||
$extensionStats = $this->refreshLayoutExtensions($plugin, $allActiveTemplates);
|
||||
$extensionStats = $this->refreshLayoutExtensions($plugin, $allActiveTemplates, $preserveModified);
|
||||
|
||||
// 레이아웃 또는 레이아웃 확장이 실제로 변경된 경우에만 캐시 버전 증가
|
||||
$extensionChanged = ($extensionStats['created'] ?? 0) > 0 || ($extensionStats['updated'] ?? 0) > 0;
|
||||
@@ -3786,11 +3797,12 @@ class PluginManager implements PluginManagerInterface
|
||||
*
|
||||
* @param PluginInterface $plugin 플러그인 인스턴스
|
||||
* @param Collection $adminTemplates admin 템플릿 컬렉션
|
||||
* @return array{refreshed: int, created: int, updated: int, deleted: int} 갱신 통계
|
||||
* @param bool $preserveModified 관리자가 편집한 확장을 보존할지 여부 (--layout-strategy=keep)
|
||||
* @return array{refreshed: int, created: int, updated: int, deleted: int, skipped: int} 갱신 통계
|
||||
*/
|
||||
protected function refreshLayoutExtensions(PluginInterface $plugin, $adminTemplates): array
|
||||
protected function refreshLayoutExtensions(PluginInterface $plugin, $adminTemplates, bool $preserveModified = false): array
|
||||
{
|
||||
return $this->refreshExtensionLayoutExtensions($plugin, $adminTemplates, LayoutSourceType::Plugin);
|
||||
return $this->refreshExtensionLayoutExtensions($plugin, $adminTemplates, LayoutSourceType::Plugin, $preserveModified);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4209,14 +4221,18 @@ class PluginManager implements PluginManagerInterface
|
||||
|
||||
if (empty($filteredSteps)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 버전순 정렬
|
||||
uksort($filteredSteps, 'version_compare');
|
||||
|
||||
// 확장 업그레이드는 코어(sudo/root)와 다른 실행 주체(php-fpm/www-data)로 실행되므로
|
||||
// 코어 'upgrade' 채널과 로그 파일을 분리한다. 같은 파일 공유 시 root 소유 파일에
|
||||
// www-data 가 append 하지 못해 Permission denied 로 실패하던 결함을 원천 차단.
|
||||
$context = new UpgradeContext(
|
||||
fromVersion: $fromVersion,
|
||||
toVersion: $toVersion,
|
||||
logChannel: 'extension-upgrade',
|
||||
);
|
||||
|
||||
foreach ($filteredSteps as $stepVersion => $step) {
|
||||
@@ -4262,7 +4278,7 @@ class PluginManager implements PluginManagerInterface
|
||||
{
|
||||
$layouts = $this->layoutRepository->getBySourceIdentifier(
|
||||
$identifier,
|
||||
\App\Enums\LayoutSourceType::Plugin,
|
||||
LayoutSourceType::Plugin,
|
||||
);
|
||||
|
||||
$modifiedLayouts = $layouts->filter(function ($layout) {
|
||||
@@ -4325,8 +4341,7 @@ class PluginManager implements PluginManagerInterface
|
||||
?\Closure $onUpgradeStep = null,
|
||||
?string $sourceOverride = null,
|
||||
?string $zipPath = null,
|
||||
): array
|
||||
{
|
||||
): array {
|
||||
$record = $this->pluginRepository->findByIdentifier($identifier);
|
||||
if (! $record) {
|
||||
throw new \RuntimeException(__('plugins.not_found', ['plugin' => $identifier]));
|
||||
@@ -4530,6 +4545,16 @@ class PluginManager implements PluginManagerInterface
|
||||
$name = $plugin ? $this->convertToMultilingual($plugin->getName()) : $record->name;
|
||||
$description = $plugin ? $this->convertToMultilingual($plugin->getDescription()) : $record->description;
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입 (install 경로와 동일)
|
||||
if ($plugin) {
|
||||
$manifest = HookManager::applyFilters(
|
||||
"plugin.{$identifier}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
}
|
||||
|
||||
$this->pluginRepository->updateByIdentifier($identifier, [
|
||||
'version' => $toVersion,
|
||||
'latest_version' => $toVersion,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Extension;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\LayoutRepositoryInterface;
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
@@ -10,6 +11,7 @@ use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Enums\DeactivationReason;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use App\Extension\Helpers\ExtensionBackupHelper;
|
||||
use App\Extension\Helpers\ExtensionPendingHelper;
|
||||
use App\Extension\Helpers\ExtensionStatusGuard;
|
||||
@@ -20,8 +22,6 @@ use App\Services\LayoutService;
|
||||
use App\Services\TemplateService;
|
||||
use Composer\Semver\Semver;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Extension\Cache\CoreCacheDriver;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -85,15 +85,17 @@ class TemplateManager implements TemplateManagerInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 캐시 드라이버를 lazy 조회합니다.
|
||||
* 코어 캐시 드라이버를 반환합니다.
|
||||
*
|
||||
* 이 메서드가 다루는 키(`template.*`, `layout.*`)는 모두 코어 소유이므로
|
||||
* 항상 `g7:core:` 네임스페이스를 써야 한다. 컨테이너의 `CacheInterface`
|
||||
* 바인딩(모듈/플러그인 테스트가 일시적으로 `PluginCacheDriver` 등으로
|
||||
* 재바인딩할 수 있음)에 의존하면 누수된 바인딩 때문에 forget/remember 가
|
||||
* `g7:plugin.*` 네임스페이스로 빗나가므로, 항상 CoreCacheDriver 를 직접 생성한다.
|
||||
*/
|
||||
private function cache(): CacheInterface
|
||||
{
|
||||
try {
|
||||
return app(CacheInterface::class);
|
||||
} catch (\Throwable $e) {
|
||||
return new CoreCacheDriver(config('cache.default', 'array'));
|
||||
}
|
||||
return new CoreCacheDriver(config('cache.default', 'array'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -424,6 +426,14 @@ class TemplateManager implements TemplateManagerInterface
|
||||
$name = $this->convertToMultilingual($template['name']);
|
||||
$description = $this->convertToMultilingual($template['description'] ?? '');
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입
|
||||
$manifest = HookManager::applyFilters(
|
||||
"template.{$templateName}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
|
||||
// 3. DB 등록
|
||||
$onProgress?->__invoke('db', 'DB 등록 중...');
|
||||
|
||||
@@ -921,6 +931,7 @@ class TemplateManager implements TemplateManagerInterface
|
||||
|
||||
return $installedTemplates;
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 식별자에 대한 메타데이터(다국어 치환 + 활성 상태 포함)를 조회합니다.
|
||||
*
|
||||
@@ -968,6 +979,7 @@ class TemplateManager implements TemplateManagerInterface
|
||||
'github_changelog_url' => $template['github_changelog_url'] ?? null,
|
||||
'requires_core' => $template['g7_version'] ?? null,
|
||||
'dependencies' => $template['dependencies'] ?? [],
|
||||
'externals' => $template['externals'] ?? [],
|
||||
'locales' => $template['locales'] ?? [],
|
||||
'layouts_count' => $layoutsCount,
|
||||
'components' => $components,
|
||||
@@ -1015,6 +1027,7 @@ class TemplateManager implements TemplateManagerInterface
|
||||
'github_changelog_url' => $metadata['github_changelog_url'] ?? null,
|
||||
'requires_core' => $metadata['g7_version'] ?? null,
|
||||
'dependencies' => $metadata['dependencies'] ?? [],
|
||||
'externals' => $metadata['externals'] ?? [],
|
||||
'locales' => $metadata['locales'] ?? [],
|
||||
'layouts_count' => 0,
|
||||
'components' => $metadata['components'] ?? [],
|
||||
@@ -1187,11 +1200,12 @@ class TemplateManager implements TemplateManagerInterface
|
||||
);
|
||||
}
|
||||
|
||||
// 레이아웃 이름 (숫자 또는 문자열 키)
|
||||
// 레이아웃 이름 (숫자 또는 문자열 키) — 다른 모든 카테고리(auth/, board/) 와
|
||||
// 동일하게 디렉토리 접두사 포함된 식별자를 그대로 사용한다 (예: "errors/404").
|
||||
$layoutName = $errorLayouts[$code] ?? $errorLayouts[(string) $code];
|
||||
|
||||
// 3. 레이아웃 파일 실제 존재 확인 (errors/ 디렉토리 내)
|
||||
$layoutFilePath = $templatePath.'/layouts/errors/'.$layoutName.'.json';
|
||||
// 3. 레이아웃 파일 실제 존재 확인 — layout_name 그대로 layouts/ 하위 파일 경로로 사용
|
||||
$layoutFilePath = $templatePath.'/layouts/'.$layoutName.'.json';
|
||||
if (! File::exists($layoutFilePath)) {
|
||||
throw new \Exception(
|
||||
__('templates.errors.error_layout_not_found', [
|
||||
@@ -3007,6 +3021,16 @@ class TemplateManager implements TemplateManagerInterface
|
||||
$name = $template ? $this->convertToMultilingual($template['name']) : $record->name;
|
||||
$description = $template ? $this->convertToMultilingual($template['description'] ?? '') : $record->description;
|
||||
|
||||
// 활성 언어팩의 manifest seed(ja 등)를 name/description 다국어 필드에 주입 (install 경로와 동일)
|
||||
if ($template) {
|
||||
$manifest = HookManager::applyFilters(
|
||||
"template.{$identifier}.manifest.translations",
|
||||
['name' => $name, 'description' => $description]
|
||||
);
|
||||
$name = $manifest['name'] ?? $name;
|
||||
$description = $manifest['description'] ?? $description;
|
||||
}
|
||||
|
||||
$this->templateRepository->updateByIdentifier($identifier, [
|
||||
'version' => $toVersion,
|
||||
'latest_version' => $toVersion,
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Testing;
|
||||
|
||||
/**
|
||||
* 테스트 환경 확장 로딩 allowlist
|
||||
*
|
||||
* PHPUnit 환경에서 테스트 클래스가 명시한 확장만 ServiceProvider / route /
|
||||
* hook listener 등록 대상으로 허용합니다. allowlist 밖 확장은 테스트 앱에
|
||||
* 영향을 주지 않습니다 (예: GDPR 플러그인의 전역 미들웨어).
|
||||
*
|
||||
* provider register() 는 앱 부팅 단계라 테스트 인스턴스 메서드보다 먼저
|
||||
* 실행되므로, 인스턴스 프로퍼티 대신 static 컨텍스트로 allowlist 를 공유합니다.
|
||||
* 테스트 클래스의 setUp() 최상단(앱 생성 전)에서 set() 을 호출합니다.
|
||||
*
|
||||
* isActive() 가 false 인 환경(비-testing, 또는 allowlist 미설정)에서는
|
||||
* 가드가 동작하지 않으므로 운영/개발 환경의 확장 로딩은 영향을 받지 않습니다.
|
||||
*/
|
||||
class ExtensionTestAllowlist
|
||||
{
|
||||
/**
|
||||
* 허용된 플러그인 디렉토리명 목록 (예: 'sirsoft-gdpr')
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
private static array $plugins = [];
|
||||
|
||||
/**
|
||||
* 허용된 모듈 디렉토리명 목록 (예: 'sirsoft-ecommerce')
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
private static array $modules = [];
|
||||
|
||||
/**
|
||||
* allowlist 가 명시적으로 설정되었는지 여부
|
||||
*
|
||||
* 빈 배열로 set() 된 경우(= core-only 테스트)와
|
||||
* 한 번도 set() 되지 않은 경우(= 비-테스트 부팅)를 구분합니다.
|
||||
*/
|
||||
private static bool $configured = false;
|
||||
|
||||
/**
|
||||
* allowlist 를 설정합니다.
|
||||
*
|
||||
* requiredExtensions 형식의 상대 경로 문자열을 받아
|
||||
* 'plugins/' / 'modules/' 프리픽스로 분류하고 디렉토리명만 추출합니다.
|
||||
*
|
||||
* @param array<string> $extensions 'plugins/sirsoft-gdpr' 형식의 확장 경로 배열
|
||||
*/
|
||||
public static function set(array $extensions): void
|
||||
{
|
||||
self::$plugins = [];
|
||||
self::$modules = [];
|
||||
self::$configured = true;
|
||||
|
||||
foreach ($extensions as $extension) {
|
||||
$extension = trim($extension, '/');
|
||||
|
||||
if (str_starts_with($extension, 'plugins/')) {
|
||||
self::$plugins[] = basename($extension);
|
||||
} elseif (str_starts_with($extension, 'modules/')) {
|
||||
self::$modules[] = basename($extension);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* allowlist 를 초기화합니다.
|
||||
*
|
||||
* 테스트 종료 시 호출하여 프로세스 내 테스트 클래스 간 누수를 방지합니다.
|
||||
*/
|
||||
public static function reset(): void
|
||||
{
|
||||
self::$plugins = [];
|
||||
self::$modules = [];
|
||||
self::$configured = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 가드 활성 여부를 반환합니다.
|
||||
*
|
||||
* testing 환경이면서 allowlist 가 명시적으로 설정된 경우에만 true.
|
||||
* false 이면 provider 는 기존과 동일하게 전수 등록합니다.
|
||||
*
|
||||
* @return bool 가드 활성 여부
|
||||
*/
|
||||
public static function isActive(): bool
|
||||
{
|
||||
return self::$configured && app()->environment('testing');
|
||||
}
|
||||
|
||||
/**
|
||||
* 해당 확장이 allowlist 에 포함되어 있는지 반환합니다.
|
||||
*
|
||||
* @param string $type 확장 유형 ('plugin' | 'module')
|
||||
* @param string $name 확장 디렉토리명 (예: 'sirsoft-gdpr')
|
||||
* @return bool allowlist 포함 여부
|
||||
*/
|
||||
public static function isAllowed(string $type, string $name): bool
|
||||
{
|
||||
return match ($type) {
|
||||
'plugin' => in_array($name, self::$plugins, true),
|
||||
'module' => in_array($name, self::$modules, true),
|
||||
default => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,13 @@ trait ClearsTemplateCaches
|
||||
*/
|
||||
private static string $extensionCacheVersionKey = 'ext.cache_version';
|
||||
|
||||
/**
|
||||
* 프로세스 1회 메모이즈된 확장 좌표 캐시 스토어 이름 (write/read 스토어 일관성).
|
||||
* `extensionCacheStore()` 가 최초 1회 채우며, 테스트는 `resetExtensionCacheStoreMemo()`
|
||||
* 로 초기화한다. null = 미해소.
|
||||
*/
|
||||
private static ?string $extensionCacheStore = null;
|
||||
|
||||
/**
|
||||
* 확장 기능 캐시 버전을 증가시킵니다.
|
||||
*
|
||||
@@ -46,11 +53,56 @@ trait ClearsTemplateCaches
|
||||
/**
|
||||
* 현재 확장 기능 캐시 버전을 반환합니다.
|
||||
*
|
||||
* @return int 캐시 버전 (타임스탬프) 또는 0 (미설정 시)
|
||||
* 키가 없거나 무효값(0)이면 — `php artisan cache:clear` 로 `ext.cache_version`
|
||||
* 키가 소실된 경우 — 그 자리에서 새 `time()` 버전을 생성·저장하고 그 값을 반환한다.
|
||||
* 0 을 그대로 내려보내면 모든 자원 URL 이 `?v=0` 으로 수렴하고, 과거 `?v=0` 에
|
||||
* 1년 immutable 로 박힌 구버전 에셋을 브라우저가 재검증 없이 영구 사용한다
|
||||
* (cache:clear 후 구버전 모듈 JS 가 고착되어 "Unknown action handler" 회귀).
|
||||
* 유효한 새 버전을 내려주면 프론트가 새 URL(`?v={새값}`)로 요청해 자동 해소된다.
|
||||
*
|
||||
* 읽기 메서드에 쓰기 부수효과가 생기지만 호출처는 모두 "현재 유효 버전 1개" 를
|
||||
* 원하므로 의미상 정확하다. cache:clear 직후 동시 요청 경합은 (a) 같은 초면 동일
|
||||
* `time()`, (b) 달라도 둘 다 유효하고 다음 요청에 수렴 → 0 붕괴보다 명백히 안전하다.
|
||||
*
|
||||
* @return int 캐시 버전 (타임스탬프). 키 부재/무효 시 새로 생성된 유효 버전.
|
||||
*/
|
||||
public static function getExtensionCacheVersion(): int
|
||||
{
|
||||
return (int) self::resolveExtensionCache()->get(self::$extensionCacheVersionKey, 0);
|
||||
$version = (int) self::resolveExtensionCache()->get(self::$extensionCacheVersionKey, 0);
|
||||
|
||||
if ($version > 0) {
|
||||
return $version;
|
||||
}
|
||||
|
||||
return self::regenerateExtensionCacheVersion();
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 버전 키 부재/무효 시 새 유효 버전을 생성·저장하고 반환합니다.
|
||||
*
|
||||
* static 컨텍스트에서 호출되므로 인스턴스 메서드(incrementExtensionCacheVersion)
|
||||
* 대신 동일 로직을 직접 수행한다. 저장 실패 시에도 0 으로 붕괴하지 않도록
|
||||
* 생성한 `time()` 값을 반환한다(다음 요청이 다시 생성·저장 시도).
|
||||
*
|
||||
* @return int 새로 생성된 유효 캐시 버전 (타임스탬프)
|
||||
*/
|
||||
private static function regenerateExtensionCacheVersion(): int
|
||||
{
|
||||
$newVersion = time();
|
||||
|
||||
try {
|
||||
self::resolveExtensionCache()->put(self::$extensionCacheVersionKey, $newVersion);
|
||||
|
||||
Log::info('확장 기능 캐시 버전 재생성 (키 부재/무효)', [
|
||||
'new_version' => $newVersion,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('확장 기능 캐시 버전 재생성 중 오류', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $newVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,17 +142,63 @@ trait ClearsTemplateCaches
|
||||
}
|
||||
|
||||
/**
|
||||
* CacheInterface 인스턴스를 컨테이너에서 lazy 조회합니다.
|
||||
* 확장 기능 캐시 버전 저장에 사용할 코어 캐시 드라이버를 반환합니다.
|
||||
*
|
||||
* 컨테이너 미구성 환경(예: 일부 단위 테스트)에서도 동작하도록
|
||||
* fallback 으로 직접 CoreCacheDriver 를 생성합니다.
|
||||
* 확장 기능 캐시 버전(`ext.cache_version`)은 코어 소유 키이므로 항상
|
||||
* `g7:core:` 접두사 네임스페이스에 저장/조회되어야 한다. 따라서
|
||||
* 컨테이너의 `CacheInterface` 바인딩(모듈/플러그인 테스트가 일시적으로
|
||||
* `PluginCacheDriver` 등으로 재바인딩할 수 있음)에 의존하지 않고
|
||||
* 항상 CoreCacheDriver 를 직접 생성한다.
|
||||
*
|
||||
* 스토어는 **고정 결정적 스토어**(`extensionCacheStore()`)를 쓴다 —
|
||||
* `config('cache.default')` 를 직접 쓰면 `SettingsServiceProvider::applyCacheConfig`
|
||||
* 가 부팅 중 admin 설정(`g7_core_settings('cache.driver')`)으로 `cache.default` 를
|
||||
* 런타임 오버라이드하므로, settings 로드 타이밍/컨텍스트(웹 vs CLI vs 큐, 설정
|
||||
* 미시드 환경)에 따라 write 와 read 가 **서로 다른 스토어**를 가리킬 수 있다.
|
||||
* 그 경우 bump 한 버전이 read 경로에서 보이지 않아 프론트엔드가 영구 stale
|
||||
* 캐시를 받는다(편집기 데이터소스 명칭/레이아웃 변경 미반영 — 반복 회귀).
|
||||
* 접두사가 코어 고정이듯 스토어도 코어 고정으로 일관시킨다.
|
||||
*/
|
||||
private static function resolveExtensionCache(): CacheInterface
|
||||
{
|
||||
try {
|
||||
return app(CacheInterface::class);
|
||||
} catch (\Throwable $e) {
|
||||
return new CoreCacheDriver(config('cache.default', 'array'));
|
||||
return new CoreCacheDriver(self::extensionCacheStore());
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 좌표 키(`ext.cache_version`)의 고정 캐시 스토어 이름을 반환합니다.
|
||||
*
|
||||
* **프로세스 1회 메모이즈** — 최초 호출 시점의 스토어를 캡처해 같은 프로세스 안에서
|
||||
* write 와 read 가 항상 동일 스토어를 쓰도록 고정한다. `SettingsServiceProvider::
|
||||
* applyCacheConfig` 가 부팅 중 `cache.default` 를 admin 설정으로 오버라이드하므로,
|
||||
* 메모이즈 없이 매번 `config('cache.default')` 를 읽으면 settings 적용 전/후 호출이
|
||||
* 서로 다른 스토어를 가리켜 bump 가 read 에서 안 보이는 회귀가 난다(편집기 명칭/
|
||||
* 레이아웃 변경 미반영 — 반복 제보).
|
||||
*
|
||||
* 비영속 `array` 스토어는 명시 회피(프로세스 경계에서 유실 → CLI write/웹 read
|
||||
* 불일치). `array` 만 가용한 환경(일부 테스트)에서는 그대로 array 를 쓰되, 그 경우
|
||||
* 동일 프로세스 안에서는 일관되므로 단위 테스트 격리에는 영향 없다.
|
||||
*
|
||||
* @return string 캐시 스토어 이름
|
||||
*/
|
||||
private static function extensionCacheStore(): string
|
||||
{
|
||||
if (self::$extensionCacheStore !== null) {
|
||||
return self::$extensionCacheStore;
|
||||
}
|
||||
|
||||
$configured = config('cache.default');
|
||||
self::$extensionCacheStore = is_string($configured) && $configured !== ''
|
||||
? $configured
|
||||
: 'file';
|
||||
|
||||
return self::$extensionCacheStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트 격리용 — 메모이즈된 스토어를 초기화한다(setUp/tearDown 에서 호출 가능).
|
||||
*/
|
||||
public static function resetExtensionCacheStoreMemo(): void
|
||||
{
|
||||
self::$extensionCacheStore = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Traits;
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인) 컴포넌트 매니페스트(components.json) 생성 트레이트
|
||||
*
|
||||
* `module:build` / `plugin:build` 의 빌드 성공 직후 호출되어, 그 확장의 컴포넌트
|
||||
* 소스를 스캔해 `{ identifier, version, components: { basic[], composite[], layout[] } }`
|
||||
* 매니페스트를 빌드 경로 루트에 작성한다.
|
||||
*
|
||||
* 편집 모드 부팅 시 코어 `ComponentRegistry` 가 활성 확장의 components.json 을
|
||||
* 네임스페이스 병합해 자동 컨트롤 생성(props 메타)의 입력으로 쓴다. 본 매니페스트가
|
||||
* 없으면 그 확장 컴포넌트는 메타데이터 없이 무손실 보존만 된다(원칙 4.6 디그레이드).
|
||||
*
|
||||
* 스캔 규칙:
|
||||
* - 컴포넌트 소스는 확장의 `resources/js/components/{basic,composite,layout}/` 하위
|
||||
* `*.tsx` / `*.ts` 파일로 본다. 하위 분류 디렉토리 이름이 type(basic/composite/layout).
|
||||
* - 분류 디렉토리 밖의 컴포넌트는 `composite` 로 분류(보수적 기본값).
|
||||
* - 컴포넌트 name = 파일명(확장자 제외). props 정밀 추출은 본 S6-1 범위 밖 —
|
||||
* `props: {}` 빈 메타로 둔다(코어 ComponentRegistry 가 런타임 props 메타로 보강).
|
||||
* - 컴포넌트 소스 디렉토리가 없으면 빈 매니페스트를 작성한다(핸들러 전용 확장 등).
|
||||
*
|
||||
* 본 트레이트는 도메인-특화 컴포넌트 구조를 가정하지 않는다 — 디렉토리 컨벤션만으로
|
||||
* 분류하고, 컨벤션 밖 구조는 composite 로 보존한다.
|
||||
*
|
||||
* @since engine-v1.54.0
|
||||
*/
|
||||
trait GeneratesComponentManifest
|
||||
{
|
||||
/**
|
||||
* 확장 빌드 경로의 컴포넌트 소스를 스캔해 components.json 을 작성합니다.
|
||||
*
|
||||
* @param string $buildPath 빌드 경로 (확장 루트 — _bundled 또는 활성)
|
||||
* @param string $identifier 확장 식별자 (vendor-extension 형식)
|
||||
* @return array{written: bool, count: int, path: string} 작성 결과
|
||||
*/
|
||||
protected function generateComponentManifest(string $buildPath, string $identifier): array
|
||||
{
|
||||
$version = $this->readManifestVersion($buildPath);
|
||||
$components = $this->scanComponentSources($buildPath);
|
||||
|
||||
$manifest = [
|
||||
'$schema' => 'https://json-schema.org/draft/2020-12/schema',
|
||||
'identifier' => $identifier,
|
||||
'version' => $version,
|
||||
'components' => $components,
|
||||
];
|
||||
|
||||
$outputPath = $buildPath.'/components.json';
|
||||
$json = json_encode(
|
||||
$manifest,
|
||||
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
|
||||
);
|
||||
|
||||
$written = $json !== false && file_put_contents($outputPath, $json.PHP_EOL) !== false;
|
||||
|
||||
$count = count($components['basic']) + count($components['composite']) + count($components['layout']);
|
||||
|
||||
return ['written' => $written, 'count' => $count, 'path' => $outputPath];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 매니페스트(module.json/plugin.json)에서 version 을 읽습니다.
|
||||
*
|
||||
* @param string $buildPath 빌드 경로
|
||||
* @return string version 문자열 (미확인 시 '0.0.0')
|
||||
*/
|
||||
private function readManifestVersion(string $buildPath): string
|
||||
{
|
||||
foreach (['module.json', 'plugin.json'] as $file) {
|
||||
$path = $buildPath.'/'.$file;
|
||||
if (file_exists($path)) {
|
||||
$decoded = json_decode((string) file_get_contents($path), true);
|
||||
if (is_array($decoded) && isset($decoded['version']) && is_string($decoded['version'])) {
|
||||
return $decoded['version'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
/**
|
||||
* 컴포넌트 소스 디렉토리를 스캔해 type 별 컴포넌트 목록을 구성합니다.
|
||||
*
|
||||
* @param string $buildPath 빌드 경로
|
||||
* @return array{basic: list<array<string, mixed>>, composite: list<array<string, mixed>>, layout: list<array<string, mixed>>}
|
||||
*/
|
||||
private function scanComponentSources(string $buildPath): array
|
||||
{
|
||||
$result = ['basic' => [], 'composite' => [], 'layout' => []];
|
||||
|
||||
$componentsRoot = $buildPath.'/resources/js/components';
|
||||
if (! is_dir($componentsRoot)) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($componentsRoot, \FilesystemIterator::SKIP_DOTS)
|
||||
);
|
||||
|
||||
foreach ($iterator as $file) {
|
||||
/** @var \SplFileInfo $file */
|
||||
if (! $file->isFile()) {
|
||||
continue;
|
||||
}
|
||||
$ext = strtolower($file->getExtension());
|
||||
if (! in_array($ext, ['ts', 'tsx'], true)) {
|
||||
continue;
|
||||
}
|
||||
$name = $file->getBasename('.'.$file->getExtension());
|
||||
// index/엔트리 파일·테스트 파일은 컴포넌트로 보지 않는다
|
||||
if (in_array(strtolower($name), ['index', 'main', 'entry'], true)) {
|
||||
continue;
|
||||
}
|
||||
if (str_contains(strtolower($file->getFilename()), '.test.')
|
||||
|| str_contains($file->getPathname(), DIRECTORY_SEPARATOR.'__tests__'.DIRECTORY_SEPARATOR)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = $this->classifyComponentByPath($componentsRoot, $file->getPathname());
|
||||
$relativePath = ltrim(
|
||||
str_replace(
|
||||
[base_path().DIRECTORY_SEPARATOR, '\\'],
|
||||
['', '/'],
|
||||
$file->getPathname()
|
||||
),
|
||||
'/'
|
||||
);
|
||||
|
||||
$result[$type][] = [
|
||||
'name' => $name,
|
||||
'type' => $type,
|
||||
'path' => $relativePath,
|
||||
'props' => new \stdClass,
|
||||
];
|
||||
}
|
||||
|
||||
// 결정적 순서 — name 기준 정렬 (빌드 재현성)
|
||||
foreach ($result as $type => $list) {
|
||||
usort($result[$type], fn ($a, $b) => strcmp($a['name'], $b['name']));
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 경로의 분류 디렉토리(basic/composite/layout)로 컴포넌트 type 을 판정합니다.
|
||||
*
|
||||
* @param string $componentsRoot components 디렉토리 절대 경로
|
||||
* @param string $filePath 컴포넌트 파일 절대 경로
|
||||
* @return 'basic'|'composite'|'layout' 컴포넌트 type (컨벤션 밖이면 composite)
|
||||
*/
|
||||
private function classifyComponentByPath(string $componentsRoot, string $filePath): string
|
||||
{
|
||||
$relative = str_replace('\\', '/', substr($filePath, strlen($componentsRoot)));
|
||||
$segments = array_values(array_filter(explode('/', $relative)));
|
||||
$firstDir = $segments[0] ?? '';
|
||||
|
||||
return match (strtolower($firstDir)) {
|
||||
'basic' => 'basic',
|
||||
'layout' => 'layout',
|
||||
default => 'composite',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ use Illuminate\Support\Facades\Log;
|
||||
*
|
||||
* 버전 포함 캐시 (layout.{identifier}.{name}.v{version})는
|
||||
* incrementExtensionCacheVersion() + TTL로 무효화됩니다.
|
||||
* 레이아웃 내용 편집 시에만 현재 버전 키를 능동 삭제합니다.
|
||||
* 레이아웃 내용 편집 시에만 현재 버전 키를 능동 삭제합니다 — 일반 응답 키와
|
||||
* 레이아웃 편집기 응답 키(`.meta` 접미사, `with_source_meta=1`) 두 가지 모두.
|
||||
*
|
||||
* 이 Trait를 사용하는 클래스는 반드시 다음 속성/메서드를 제공해야 합니다:
|
||||
* - $layoutRepository: LayoutRepositoryInterface 인스턴스
|
||||
@@ -105,24 +106,32 @@ trait InvalidatesLayoutCache
|
||||
$cache->forget("template.{$layout->template_id}.layout.{$layout->name}.{$sourceHash}");
|
||||
}
|
||||
|
||||
// 3. PublicLayoutController 캐시 (버전 포함)
|
||||
// 레이아웃 내용 편집 시 현재 버전 키 삭제 (버전 변경 없이 내용만 바뀜)
|
||||
// 3. PublicLayoutController 캐시 (버전 포함) — 일반 응답 + 편집기(`.meta`) 응답 두 키 모두.
|
||||
// PublicLayoutController::serve() 가 `with_source_meta=1`(레이아웃 편집기) 응답을 `.meta`
|
||||
// 접미사 별도 키로 캐싱하므로, 그 키를 함께 삭제하지 않으면 템플릿/레이아웃 상태 변화
|
||||
// (refresh-layout / activate / deactivate / uninstall 등) 후에도 편집기가 stale 캐시를
|
||||
// 받는다. 레이아웃
|
||||
// 저장 경로(LayoutService::clearPublicServingCache)는 이미 두 키를 지우므로 정합을 맞춘다.
|
||||
if ($templateIdentifier) {
|
||||
$cacheVersion = (int) $cache->get('ext.cache_version', 0);
|
||||
$cache->forget("layout.{$templateIdentifier}.{$layout->name}.v{$cacheVersion}");
|
||||
$cache->forget("layout.{$templateIdentifier}.{$layout->name}.v{$cacheVersion}.meta");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CacheInterface 인스턴스를 lazy 조회합니다.
|
||||
* 레이아웃 캐시 무효화에 사용할 코어 캐시 드라이버를 반환합니다.
|
||||
*
|
||||
* 레이아웃 캐시 키(`template.*.layout.*`, `layout.*` 등)는 모두 코어 소유
|
||||
* 키이므로 항상 `g7:core:` 접두사 네임스페이스에서 저장/삭제되어야 한다.
|
||||
* 따라서 컨테이너의 `CacheInterface` 바인딩(모듈/플러그인 테스트가 일시적으로
|
||||
* `PluginCacheDriver` 등으로 재바인딩할 수 있음)에 의존하지 않고 항상
|
||||
* CoreCacheDriver 를 직접 생성한다. 의존 시 누수된 바인딩 때문에
|
||||
* `g7:plugin.*` 네임스페이스로 forget 이 빗나가 캐시가 실제로 삭제되지 않는다.
|
||||
*/
|
||||
private function resolveLayoutCache(): CacheInterface
|
||||
{
|
||||
try {
|
||||
return app(CacheInterface::class);
|
||||
} catch (\Throwable $e) {
|
||||
return new CoreCacheDriver(config('cache.default', 'array'));
|
||||
}
|
||||
return new CoreCacheDriver(config('cache.default', 'array'));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,17 +29,19 @@ trait RefreshesLayoutExtensions
|
||||
* @param ModuleInterface|PluginInterface $extension 모듈 또는 플러그인 인스턴스
|
||||
* @param Collection $adminTemplates admin 템플릿 컬렉션
|
||||
* @param LayoutSourceType $sourceType 소스 타입 (Module 또는 Plugin)
|
||||
* @return array{refreshed: int, created: int, updated: int, deleted: int} 갱신 통계
|
||||
* @param bool $preserveModified 관리자가 편집한 확장을 보존할지 여부 (--layout-strategy=keep)
|
||||
* @return array{refreshed: int, created: int, updated: int, deleted: int, skipped: int} 갱신 통계
|
||||
*/
|
||||
protected function refreshExtensionLayoutExtensions(
|
||||
ModuleInterface|PluginInterface $extension,
|
||||
Collection $adminTemplates,
|
||||
LayoutSourceType $sourceType
|
||||
LayoutSourceType $sourceType,
|
||||
bool $preserveModified = false
|
||||
): array {
|
||||
$extensionFiles = $extension->getLayoutExtensions();
|
||||
$identifier = $extension->getIdentifier();
|
||||
$extensionType = $sourceType === LayoutSourceType::Module ? 'module' : 'plugin';
|
||||
$stats = ['refreshed' => 0, 'created' => 0, 'updated' => 0, 'deleted' => 0];
|
||||
$stats = ['refreshed' => 0, 'created' => 0, 'updated' => 0, 'deleted' => 0, 'skipped' => 0];
|
||||
|
||||
if ($adminTemplates->isEmpty()) {
|
||||
return $stats;
|
||||
@@ -79,17 +81,37 @@ trait RefreshesLayoutExtensions
|
||||
// 파일에서 읽은 확장 등록/업데이트
|
||||
foreach ($fileExtensions as $targetKey => $extensionData) {
|
||||
try {
|
||||
// 대상(target_layout / extension_point)이 이 템플릿에 존재하지 않으면 등록하지 않는다.
|
||||
// 모든 활성 템플릿에 일괄 적용 시, admin 레이아웃 대상 확장이 user 템플릿에
|
||||
// (또는 그 반대로) 잘못 등록되는 것을 방지한다.
|
||||
if (! $this->layoutExtensionService->isExtensionApplicableToTemplate($extensionData, $template->id)) {
|
||||
// 과거 무차별 등록으로 잘못 생성된 행이 있으면 정리
|
||||
if ($this->layoutExtensionService->removeInapplicableExtension(
|
||||
$extensionData,
|
||||
$sourceType,
|
||||
$identifier,
|
||||
$template->id
|
||||
)) {
|
||||
$stats['deleted']++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $this->layoutExtensionService->registerExtension(
|
||||
$extensionData,
|
||||
$sourceType,
|
||||
$identifier,
|
||||
$template->id
|
||||
$template->id,
|
||||
$preserveModified
|
||||
);
|
||||
|
||||
if ($result === 'created') {
|
||||
$stats['created']++;
|
||||
} elseif ($result === 'updated') {
|
||||
$stats['updated']++;
|
||||
} elseif ($result === 'skipped') {
|
||||
$stats['skipped']++;
|
||||
}
|
||||
$stats['refreshed']++;
|
||||
} catch (\Exception $e) {
|
||||
|
||||
@@ -36,13 +36,20 @@ class UpgradeContext
|
||||
* @param string $fromVersion 업그레이드 시작 버전 (현재 설치 버전)
|
||||
* @param string $toVersion 업그레이드 목표 버전
|
||||
* @param string $currentStep 현재 실행 중인 스텝 버전
|
||||
* @param string $logChannel 로그 채널명 — 코어 업그레이드는 'upgrade'(기본), 확장
|
||||
* (모듈/플러그인) 업그레이드는 'extension-upgrade'. 실행
|
||||
* 주체가 다른(root vs www-data) 두 흐름이 같은 로그 파일을
|
||||
* 공유하여 발생하던 소유권 충돌(Permission denied)을 파일
|
||||
* 분리로 원천 차단한다. step 작성자 인터페이스($context->logger)
|
||||
* 는 채널과 무관하게 동일하다.
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $fromVersion,
|
||||
public readonly string $toVersion,
|
||||
public readonly string $currentStep = '',
|
||||
public readonly string $logChannel = 'upgrade',
|
||||
) {
|
||||
$this->logger = Log::channel('upgrade');
|
||||
$this->logger = Log::channel($logChannel);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,6 +78,7 @@ class UpgradeContext
|
||||
* 현재 스텝 버전을 변경한 새 컨텍스트를 반환합니다.
|
||||
*
|
||||
* @param string $stepVersion 현재 실행할 스텝 버전
|
||||
* @return self 스텝 버전만 교체하고 나머지(버전·로그 채널)를 승계한 새 컨텍스트
|
||||
*/
|
||||
public function withCurrentStep(string $stepVersion): self
|
||||
{
|
||||
@@ -78,6 +86,7 @@ class UpgradeContext
|
||||
fromVersion: $this->fromVersion,
|
||||
toVersion: $this->toVersion,
|
||||
currentStep: $stepVersion,
|
||||
logChannel: $this->logChannel,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user