v7.0.0-beta.2 release

This commit is contained in:
HeuJung committed 2026-04-20 20:37:49 +09:00
1 parent 6595fd0eb5
commit fa8eba7a0d
1165 files changed
+107118 -762127

No files matched your search

+167 -8
View File
@@ -2,10 +2,13 @@
namespace App\Extension;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\ModuleInterface;
use App\Contracts\Extension\StorageInterface;
use App\Contracts\Extension\UpgradeStepInterface;
use App\Extension\Cache\ModuleCacheDriver;
use App\Extension\Storage\ModuleStorageDriver;
use Illuminate\Database\Seeder;
use ReflectionClass;
/**
@@ -32,6 +35,11 @@ abstract class AbstractModule implements ModuleInterface
*/
private ?StorageInterface $storage = null;
/**
* 캐시 드라이버 인스턴스 (캐시)
*/
private ?CacheInterface $cache = null;
/**
* manifest JSON 캐시
*/
@@ -121,14 +129,22 @@ abstract class AbstractModule implements ModuleInterface
}
/**
* 벤더명 반환 (디렉토리명에서 자동 추론)
* 벤더명 반환
*
* 디렉토리명이 'sirsoft-sample'이면 벤더명은 'sirsoft'
* module.json 의 vendor 필드를 우선 사용합니다.
* 값이 없으면 디렉토리명의 첫 단어(예: 'sirsoft-sample' → 'sirsoft')로 폴백합니다.
*
* @return string 사람이 읽는 벤더/개발자명 또는 폴백으로 얻은 식별자 prefix
*/
final public function getVendor(): string
{
$identifier = $this->getIdentifier();
$parts = explode('-', $identifier);
$manifestVendor = $this->loadManifest()['vendor'] ?? null;
if (is_string($manifestVendor) && $manifestVendor !== '') {
return $manifestVendor;
}
$parts = explode('-', $this->getIdentifier());
return $parts[0];
}
@@ -361,6 +377,52 @@ abstract class AbstractModule implements ModuleInterface
return [];
}
/**
* 런타임에 동적으로 생성되는 권한 식별자 목록을 반환합니다.
*
* `getPermissions()` 는 모듈 정의 시점의 **정적** 권한 구조를 반환하지만,
* 일부 모듈(예: sirsoft-board — 게시판 slug 당 권한 세트)은 런타임에 권한을
* 동적으로 생성합니다. 이런 권한은 저장 시 `extension_type=module` +
* `extension_identifier={module}` 로 기록되므로, `ModuleManager::cleanupStaleModuleEntries()`
* 가 **정적 정의에 없다는 이유로 전부 stale 로 오판해 삭제** 하는 회귀가 일어납니다.
*
* 동적 권한을 보유한 모듈은 본 메서드를 override 해 현재 DB/설정에 존재해야 하는
* 동적 권한 식별자(카테고리 + 액션 전체)를 flat 배열로 반환하세요. 반환값은
* cleanup 대상에서 자동 제외됩니다.
*
* @return array<int, string>
*/
public function getDynamicPermissionIdentifiers(): array
{
return [];
}
/**
* 런타임에 동적으로 생성되는 역할 식별자 목록을 반환합니다.
*
* `getRoles()` 정적 정의 외에 런타임에 추가되는 역할(예: 게시판 별 manager/step)이
* 있을 때 override 하세요. 반환된 식별자는 stale cleanup 대상에서 제외됩니다.
*
* @return array<int, string>
*/
public function getDynamicRoleIdentifiers(): array
{
return [];
}
/**
* 런타임에 동적으로 생성되는 메뉴 slug 목록을 반환합니다.
*
* `getAdminMenus()` 정적 정의 외에 런타임에 추가되는 메뉴(예: 게시판 별 메뉴)가
* 있을 때 override 하세요. 반환된 slug 는 stale cleanup 대상에서 제외됩니다.
*
* @return array<int, string>
*/
public function getDynamicMenuSlugs(): array
{
return [];
}
/**
* 모듈 설정 정보 반환
*
@@ -419,6 +481,27 @@ abstract class AbstractModule implements ModuleInterface
return [];
}
/**
* 브로드캐스트 채널 정의를 반환합니다.
*
* 모듈에서 WebSocket 실시간 채널이 필요한 경우 오버라이드합니다.
* 반환된 채널은 ModuleManager가 자동으로 Broadcast::channel()에 등록합니다.
*
* 네이밍 규칙: module.{identifier}.{resource}.{param}
*
* @return array<string, array{permission?: string, type?: string}>
* [
* 'module.vendor-module.orders.{id}' => [
* 'permission' => 'vendor-module.orders.read', // 권한 체크 (선택)
* 'type' => 'private', // 채널 타입 (기본: private)
* ],
* ]
*/
public function getChannels(): array
{
return [];
}
/**
* 스케줄 작업 목록 반환
*
@@ -453,7 +536,7 @@ abstract class AbstractModule implements ModuleInterface
* 빈 배열 반환 시 database/seeders/ 디렉토리의 모든 시더를 자동 검색합니다. (역호환)
* 오버라이드하여 실행할 시더와 순서를 명시적으로 정의하세요.
*
* @return array<class-string<\Illuminate\Database\Seeder>> 시더 클래스명 배열 (FQCN)
* @return array<class-string<Seeder>> 시더 클래스명 배열 (FQCN)
*/
public function getSeeders(): array
{
@@ -463,12 +546,19 @@ abstract class AbstractModule implements ModuleInterface
/**
* 모듈 의존성 반환
*
* 기본적으로 빈 배열 반환
* 모듈 개발자가 의존성이 필요한 경우 오버라이드
* module.json 의 dependencies 필드를 반환합니다.
* 중첩 구조 형식: ['modules' => [identifier => version, ...], 'plugins' => [...]]
*
* 기본 구현은 manifest JSON 파싱 결과를 그대로 반환하므로 모듈 개발자는
* module.json 에 의존성을 정의하면 되고 PHP 오버라이드는 권장하지 않습니다.
*
* @return array 중첩 구조 의존성 배열
*/
public function getDependencies(): array
{
return [];
$dependencies = $this->loadManifest()['dependencies'] ?? [];
return is_array($dependencies) ? $dependencies : [];
}
/**
@@ -624,6 +714,43 @@ abstract class AbstractModule implements ModuleInterface
return is_array($config) ? $config : [];
}
/**
* SEO 변수 메타데이터를 반환합니다.
*
* 모듈이 SEO 렌더링에 제공하는 변수를 page_type별로 선언합니다.
* SeoRenderer가 이 메서드를 호출하여 변수를 수집하고 자동 해석합니다.
*
* 각 변수는 source 타입에 따라 해석 방식이 결정됩니다:
* - setting: 모듈 환경설정 값 (엔진 자동 해석)
* - core_setting: 코어 설정 값 (엔진 자동 해석)
* - query: URL 쿼리 파라미터 (엔진 자동 해석)
* - route: 라우트 파라미터 (엔진 자동 해석)
* - data: 데이터소스 응답 필드 (템플릿 개발자가 vars에서 매핑)
*
* 기본적으로 빈 배열 반환.
* 모듈 개발자가 SEO 변수가 필요한 경우 오버라이드하세요.
*
* @return array page_type별 변수 정의 배열
* [
* 'product' => [
* 'product_name' => [
* 'description' => '상품명',
* 'source' => 'data',
* 'required' => true,
* ],
* 'commerce_name' => [
* 'description' => '쇼핑몰명',
* 'source' => 'setting',
* 'key' => 'basic_info.shop_name',
* ],
* ],
* ]
*/
public function seoVariables(): array
{
return [];
}
/**
* 그누보드7 코어 요구 버전 제약 반환
*
@@ -782,6 +909,38 @@ abstract class AbstractModule implements ModuleInterface
return 'modules';
}
/**
* 모듈 캐시 드라이버 인스턴스 반환
*
* 모듈별로 격리된 캐시를 제공합니다.
* 접두사 패턴: g7:module.{identifier}:{key}
*
* @return CacheInterface 캐시 드라이버 인스턴스
*/
public function getCache(): CacheInterface
{
if ($this->cache === null) {
$this->cache = new ModuleCacheDriver(
$this->getIdentifier(),
$this->getCacheStore()
);
}
return $this->cache;
}
/**
* 모듈에서 사용할 캐시 스토어 이름 반환
*
* 기본값은 환경설정 캐시 드라이버이며, 모듈 개발자가 다른 스토어를 사용하려면 오버라이드합니다.
*
* @return string 캐시 스토어 이름
*/
public function getCacheStore(): string
{
return config('cache.default');
}
/**
* 카테고리별 스토리지 기본 경로 반환
*
+144 -8
View File
@@ -2,10 +2,13 @@
namespace App\Extension;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\PluginInterface;
use App\Contracts\Extension\StorageInterface;
use App\Contracts\Extension\UpgradeStepInterface;
use App\Extension\Cache\PluginCacheDriver;
use App\Extension\Storage\PluginStorageDriver;
use Illuminate\Database\Seeder;
use ReflectionClass;
/**
@@ -34,6 +37,11 @@ abstract class AbstractPlugin implements PluginInterface
*/
private ?StorageInterface $storage = null;
/**
* 캐시 드라이버 인스턴스 (캐시)
*/
private ?CacheInterface $cache = null;
/**
* manifest JSON 캐시
*/
@@ -123,14 +131,22 @@ abstract class AbstractPlugin implements PluginInterface
}
/**
* 벤더명 반환 (디렉토리명에서 자동 추론)
* 벤더명 반환
*
* 디렉토리명이 'sirsoft-sample'이면 벤더명은 'sirsoft'
* plugin.json 의 vendor 필드를 우선 사용합니다.
* 값이 없으면 디렉토리명의 첫 단어(예: 'sirsoft-sample' → 'sirsoft')로 폴백합니다.
*
* @return string 사람이 읽는 벤더/개발자명 또는 폴백으로 얻은 식별자 prefix
*/
final public function getVendor(): string
{
$identifier = $this->getIdentifier();
$parts = explode('-', $identifier);
$manifestVendor = $this->loadManifest()['vendor'] ?? null;
if (is_string($manifestVendor) && $manifestVendor !== '') {
return $manifestVendor;
}
$parts = explode('-', $this->getIdentifier());
return $parts[0];
}
@@ -353,6 +369,29 @@ abstract class AbstractPlugin implements PluginInterface
return [];
}
/**
* 런타임에 동적으로 생성되는 권한 식별자 목록을 반환합니다.
*
* 동적 권한(예: 사용자 입력에 따라 생성되는 권한)을 보유한 플러그인이 override.
* `PluginManager::cleanupStalePluginEntries()` 가 정의 기반 stale 판정에서 이들을 제외합니다.
*
* @return array<int, string>
*/
public function getDynamicPermissionIdentifiers(): array
{
return [];
}
/**
* 런타임에 동적으로 생성되는 역할 식별자 목록을 반환합니다.
*
* @return array<int, string>
*/
public function getDynamicRoleIdentifiers(): array
{
return [];
}
/**
* 플러그인 설정 파일 경로 반환
*
@@ -401,6 +440,27 @@ abstract class AbstractPlugin implements PluginInterface
return [];
}
/**
* 브로드캐스트 채널 정의를 반환합니다.
*
* 플러그인에서 WebSocket 실시간 채널이 필요한 경우 오버라이드합니다.
* 반환된 채널은 PluginManager가 자동으로 Broadcast::channel()에 등록합니다.
*
* 네이밍 규칙: plugin.{identifier}.{resource}.{param}
*
* @return array<string, array{permission?: string, type?: string}>
* [
* 'plugin.vendor-plugin.status.{id}' => [
* 'permission' => 'vendor-plugin.status.read',
* 'type' => 'private',
* ],
* ]
*/
public function getChannels(): array
{
return [];
}
/**
* 스케줄 작업 목록 반환
*
@@ -435,7 +495,7 @@ abstract class AbstractPlugin implements PluginInterface
* 빈 배열 반환 시 database/seeders/ 디렉토리의 모든 시더를 자동 검색합니다. (역호환)
* 오버라이드하여 실행할 시더와 순서를 명시적으로 정의하세요.
*
* @return array<class-string<\Illuminate\Database\Seeder>> 시더 클래스명 배열 (FQCN)
* @return array<class-string<Seeder>> 시더 클래스명 배열 (FQCN)
*/
public function getSeeders(): array
{
@@ -445,12 +505,19 @@ abstract class AbstractPlugin implements PluginInterface
/**
* 플러그인 의존성 반환
*
* 기본적으로 빈 배열 반환
* 플러그인 개발자가 의존성이 필요한 경우 오버라이드
* plugin.json 의 dependencies 필드를 반환합니다.
* 중첩 구조 형식: ['modules' => [identifier => version, ...], 'plugins' => [...]]
*
* 기본 구현은 manifest JSON 파싱 결과를 그대로 반환하므로 플러그인 개발자는
* plugin.json 에 의존성을 정의하면 되고 PHP 오버라이드는 권장하지 않습니다.
*
* @return array 중첩 구조 의존성 배열
*/
public function getDependencies(): array
{
return [];
$dependencies = $this->loadManifest()['dependencies'] ?? [];
return is_array($dependencies) ? $dependencies : [];
}
/**
@@ -542,6 +609,43 @@ abstract class AbstractPlugin implements PluginInterface
return is_array($config) ? $config : [];
}
/**
* SEO 변수 메타데이터를 반환합니다.
*
* 플러그인이 SEO 렌더링에 제공하는 변수를 page_type별로 선언합니다.
* SeoRenderer가 이 메서드를 호출하여 변수를 수집하고 자동 해석합니다.
*
* 각 변수는 source 타입에 따라 해석 방식이 결정됩니다:
* - setting: 플러그인 환경설정 값 (엔진 자동 해석)
* - core_setting: 코어 설정 값 (엔진 자동 해석)
* - query: URL 쿼리 파라미터 (엔진 자동 해석)
* - route: 라우트 파라미터 (엔진 자동 해석)
* - data: 데이터소스 응답 필드 (템플릿 개발자가 vars에서 매핑)
*
* 기본적으로 빈 배열 반환.
* 플러그인 개발자가 SEO 변수가 필요한 경우 오버라이드하세요.
*
* @return array page_type별 변수 정의 배열
* [
* 'product' => [
* 'product_name' => [
* 'description' => '상품명',
* 'source' => 'data',
* 'required' => true,
* ],
* 'commerce_name' => [
* 'description' => '쇼핑몰명',
* 'source' => 'setting',
* 'key' => 'basic_info.shop_name',
* ],
* ],
* ]
*/
public function seoVariables(): array
{
return [];
}
/**
* 그누보드7 코어 요구 버전 제약 반환
*
@@ -773,6 +877,38 @@ abstract class AbstractPlugin implements PluginInterface
return 'plugins';
}
/**
* 플러그인 캐시 드라이버 인스턴스 반환
*
* 플러그인별로 격리된 캐시를 제공합니다.
* 접두사 패턴: g7:plugin.{identifier}:{key}
*
* @return CacheInterface 캐시 드라이버 인스턴스
*/
public function getCache(): CacheInterface
{
if ($this->cache === null) {
$this->cache = new PluginCacheDriver(
$this->getIdentifier(),
$this->getCacheStore()
);
}
return $this->cache;
}
/**
* 플러그인에서 사용할 캐시 스토어 이름 반환
*
* 기본값은 환경설정 캐시 드라이버이며, 플러그인 개발자가 다른 스토어를 사용하려면 오버라이드합니다.
*
* @return string 캐시 스토어 이름
*/
public function getCacheStore(): string
{
return config('cache.default');
}
/**
* 카테고리별 스토리지 기본 경로 반환
*
@@ -2,6 +2,7 @@
namespace App\Extension;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Extension\StorageInterface;
use Illuminate\Support\ServiceProvider;
use ReflectionClass;
@@ -30,6 +31,15 @@ abstract class BaseModuleServiceProvider extends ServiceProvider
*/
protected array $storageServices = [];
/**
* CacheInterface가 필요한 서비스 클래스 목록
*
* 이 배열에 정의된 서비스들은 자동으로 CacheInterface가 주입됩니다.
*
* @var array<int, class-string>
*/
protected array $cacheServices = [];
/**
* Repository 인터페이스와 구현체 매핑
*
@@ -54,6 +64,9 @@ abstract class BaseModuleServiceProvider extends ServiceProvider
// StorageInterface 바인딩
$this->registerStorageBindings();
// CacheInterface 바인딩
$this->registerCacheBindings();
}
/**
@@ -99,6 +112,27 @@ abstract class BaseModuleServiceProvider extends ServiceProvider
});
}
/**
* 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 파일의 디렉토리 경로 반환
*
+366
View File
@@ -0,0 +1,366 @@
<?php
namespace App\Extension\Cache;
use App\Contracts\Extension\CacheInterface;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
/**
* 캐시 드라이버 추상 클래스
*
* CoreCacheDriver, ModuleCacheDriver, PluginCacheDriver의 공통 구현을 제공합니다.
* 접두사 기반 키 분리, 태그 지원/미지원 드라이버 호환, 키 인덱스 기반 flush를 포함합니다.
*
* @since engine-v1.18.0
*/
abstract class AbstractCacheDriver implements CacheInterface
{
/**
* 사용할 캐시 스토어 이름
*/
protected string $store;
/**
* 서브클래스에서 접두사를 반환합니다.
*
* @return string 접두사 (예: 'g7:core', 'g7:module.sirsoft-ecommerce')
*/
abstract protected function getPrefix(): string;
/**
* 기본 TTL을 반환합니다.
*
* g7_core_settings 중앙 관리를 통해 기본값을 결정합니다.
*
* @return int 기본 TTL (초)
*/
protected function getDefaultTtl(): int
{
return (int) g7_core_settings('cache.default_ttl', 86400);
}
/**
* 접두사가 적용된 전체 캐시 키를 반환합니다.
*
* @param string $key 캐시 키
* @return string 접두사가 포함된 전체 키
*/
public function resolveKey(string $key): string
{
return $this->getPrefix() . ':' . $key;
}
/**
* Laravel Cache 스토어 인스턴스를 반환합니다.
*
* @return \Illuminate\Cache\Repository 캐시 스토어 인스턴스
*/
protected function store(): \Illuminate\Cache\Repository
{
return Cache::store($this->store);
}
/**
* 현재 캐시 스토어가 태그를 지원하는지 확인합니다.
*
* @return bool 태그 지원 여부
*/
public function supportsTags(): bool
{
return method_exists($this->store()->getStore(), 'tags');
}
/**
* 현재 사용 중인 캐시 스토어 이름을 반환합니다.
*
* @return string 스토어 이름
*/
public function getStore(): string
{
return $this->store;
}
/**
* 사용할 캐시 스토어를 변경한 새 인스턴스를 반환합니다.
*
* @param string $store 캐시 스토어 이름
* @return static 새 스토어를 사용하는 인스턴스
*/
public function withStore(string $store): static
{
$clone = clone $this;
$clone->store = $store;
return $clone;
}
// === 기본 CRUD ===
/**
* 캐시에서 값을 조회합니다.
*
* @param string $key 캐시 키
* @param mixed $default 기본값
* @return mixed 캐시된 값 또는 기본값
*/
public function get(string $key, mixed $default = null): mixed
{
return $this->store()->get($this->resolveKey($key), $default);
}
/**
* 캐시에 값을 저장합니다.
*
* @param string $key 캐시 키
* @param mixed $value 저장할 값
* @param int|null $ttl TTL (초), null이면 기본값 사용
* @return bool 저장 성공 여부
*/
public function put(string $key, mixed $value, ?int $ttl = null): bool
{
$resolvedKey = $this->resolveKey($key);
$ttl = $ttl ?? $this->getDefaultTtl();
return $this->store()->put($resolvedKey, $value, $ttl);
}
/**
* 캐시 키가 존재하는지 확인합니다.
*
* @param string $key 캐시 키
* @return bool 존재 여부
*/
public function has(string $key): bool
{
return $this->store()->has($this->resolveKey($key));
}
/**
* 캐시 키를 삭제합니다.
*
* @param string $key 캐시 키
* @return bool 삭제 성공 여부
*/
public function forget(string $key): bool
{
return $this->store()->forget($this->resolveKey($key));
}
// === Remember 패턴 ===
/**
* 캐시에서 값을 조회하거나 콜백 결과를 캐시합니다.
*
* 소속 태그(확장 접두사)를 항상 포함하여 flush() 시 일괄 삭제가 가능합니다.
*
* @param string $key 캐시 키
* @param callable $callback 캐시 미스 시 실행할 콜백
* @param int|null $ttl TTL (초), null이면 기본값 사용
* @param array $tags 캐시 태그 (무효화용)
* @return mixed 캐시된 값 또는 콜백 결과
*/
public function remember(string $key, callable $callback, ?int $ttl = null, array $tags = []): mixed
{
$resolvedKey = $this->resolveKey($key);
$ttl = $ttl ?? $this->getDefaultTtl();
// 소속 태그(확장 접두사)를 항상 포함 → flush() 시 일괄 삭제 가능
$allTags = array_values(array_unique(array_merge([$this->getPrefix()], $tags)));
// 항상 일반 remember + 키 인덱스에 태그 매핑 기록
// Laravel 네이티브 태그 저장은 사용하지 않음 (get/has와의 일관성 보장)
$result = $this->store()->remember($resolvedKey, $ttl, $callback);
$this->recordKeyTags($resolvedKey, $allTags);
return $result;
}
/**
* 쿼리 해시 기반 캐싱을 수행합니다.
*
* @param string $queryHash 쿼리 해시
* @param callable $callback 캐시 미스 시 실행할 콜백
* @param int|null $ttl TTL (초), null이면 기본값 사용
* @param array $tags 캐시 태그 (무효화용)
* @return mixed 캐시된 값 또는 콜백 결과
*/
public function rememberQuery(string $queryHash, callable $callback, ?int $ttl = null, array $tags = []): mixed
{
return $this->remember('query:' . $queryHash, $callback, $ttl, $tags);
}
// === 벌크 연산 ===
/**
* 여러 캐시 키를 한 번에 조회합니다.
*
* @param array $keys 캐시 키 배열
* @return array 키 => 값 배열
*/
public function many(array $keys): array
{
$resolvedKeys = [];
$keyMap = [];
foreach ($keys as $key) {
$resolved = $this->resolveKey($key);
$resolvedKeys[] = $resolved;
$keyMap[$resolved] = $key;
}
$results = $this->store()->many($resolvedKeys);
// 원래 키로 매핑하여 반환
$mapped = [];
foreach ($results as $resolvedKey => $value) {
$originalKey = $keyMap[$resolvedKey] ?? $resolvedKey;
$mapped[$originalKey] = $value;
}
return $mapped;
}
/**
* 여러 캐시 키-값을 한 번에 저장합니다.
*
* @param array $values 키 => 값 배열
* @param int|null $ttl TTL (초), null이면 기본값 사용
* @return bool 저장 성공 여부
*/
public function putMany(array $values, ?int $ttl = null): bool
{
$ttl = $ttl ?? $this->getDefaultTtl();
$resolved = [];
foreach ($values as $key => $value) {
$resolved[$this->resolveKey($key)] = $value;
}
return $this->store()->putMany($resolved, $ttl);
}
// === 무효화 ===
/**
* 이 드라이버 소속 전체 캐시를 삭제합니다.
*
* 태그 지원 드라이버에서는 소속 태그로 삭제하고,
* 미지원 드라이버에서는 키 인덱스를 기반으로 삭제합니다.
*
* @return bool 삭제 성공 여부
*/
public function flush(): bool
{
if ($this->supportsTags()) {
return $this->flushTags([$this->getPrefix()]);
}
return $this->flushByIndex();
}
/**
* 특정 태그의 캐시를 삭제합니다.
*
* @param array $tags 삭제할 태그 배열
* @return bool 삭제 성공 여부
*/
public function flushTags(array $tags): bool
{
// 항상 키 인덱스 기반으로 태그 삭제 (get/has와의 일관성 보장)
return $this->flushTagsByIndex($tags);
}
// === 리프레시 ===
/**
* 캐시를 무효화하고 새로고침합니다.
*
* @param string $key 캐시 키
* @param callable $callback 새 값을 생성할 콜백
* @param int|null $ttl TTL (초), null이면 기본값 사용
* @param array $tags 캐시 태그 (무효화용)
* @return mixed 새로 캐시된 값
*/
public function refresh(string $key, callable $callback, ?int $ttl = null, array $tags = []): mixed
{
$this->forget($key);
return $this->remember($key, $callback, $ttl, $tags);
}
// === 키 인덱스 (태그 미지원 드라이버용) ===
/**
* 키-태그 매핑을 인덱스에 기록합니다.
*
* file/database 드라이버처럼 태그를 지원하지 않는 경우,
* flush()와 flushTags()를 위해 키-태그 매핑을 별도 캐시 키에 기록합니다.
*
* @param string $resolvedKey 접두사 적용된 전체 키
* @param array $tags 태그 배열
* @return void
*/
private function recordKeyTags(string $resolvedKey, array $tags): void
{
$indexKey = $this->getIndexKey();
$index = $this->store()->get($indexKey, []);
$index[$resolvedKey] = array_values(array_unique(
array_merge($index[$resolvedKey] ?? [], $tags)
));
$this->store()->put($indexKey, $index, 86400 * 30); // 30일
}
/**
* 키 인덱스 기반으로 전체 캐시를 삭제합니다.
*
* @return bool 삭제 성공 여부
*/
private function flushByIndex(): bool
{
$indexKey = $this->getIndexKey();
$index = $this->store()->get($indexKey, []);
foreach (array_keys($index) as $key) {
$this->store()->forget($key);
}
$this->store()->forget($indexKey);
return true;
}
/**
* 키 인덱스 기반으로 특정 태그의 캐시를 삭제합니다.
*
* @param array $tags 삭제할 태그 배열
* @return bool 삭제 성공 여부
*/
private function flushTagsByIndex(array $tags): bool
{
$indexKey = $this->getIndexKey();
$index = $this->store()->get($indexKey, []);
$tagsSet = array_flip($tags);
foreach ($index as $key => $keyTags) {
if (array_intersect_key(array_flip($keyTags), $tagsSet)) {
$this->store()->forget($key);
unset($index[$key]);
}
}
$this->store()->put($indexKey, $index, 86400 * 30);
return true;
}
/**
* 키 인덱스의 캐시 키를 반환합니다.
*
* @return string 인덱스 캐시 키
*/
private function getIndexKey(): string
{
return 'g7:_idx:' . $this->getPrefix();
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Extension\Cache;
/**
* 코어 캐시 드라이버
*
* 코어 서비스(LayoutService, SeoCacheManager, SettingsService 등)에서 사용하는
* 캐시를 관리합니다. 접두사 패턴: g7:core:{key}
*
* @since engine-v1.18.0
*/
class CoreCacheDriver extends AbstractCacheDriver
{
/**
* CoreCacheDriver 생성자
*
* @param string $store 캐시 스토어 이름 (빈 문자열이면 기본 스토어)
*/
public function __construct(string $store = '')
{
$this->store = $store ?: config('cache.default');
}
/**
* 코어 캐시 접두사를 반환합니다.
*
* @return string 접두사
*/
protected function getPrefix(): string
{
return 'g7:core';
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Extension\Cache;
/**
* 모듈 캐시 드라이버
*
* 각 모듈에서 사용하는 캐시를 관리합니다.
* 접두사 패턴: g7:module.{identifier}:{key}
*
* @since engine-v1.18.0
*/
class ModuleCacheDriver extends AbstractCacheDriver
{
/**
* 모듈 식별자
*/
private string $identifier;
/**
* ModuleCacheDriver 생성자
*
* @param string $identifier 모듈 식별자 (예: sirsoft-ecommerce)
* @param string $store 캐시 스토어 이름 (빈 문자열이면 기본 스토어)
*/
public function __construct(string $identifier, string $store = '')
{
$this->identifier = $identifier;
$this->store = $store ?: config('cache.default');
}
/**
* 모듈 캐시 접두사를 반환합니다.
*
* @return string 접두사
*/
protected function getPrefix(): string
{
return 'g7:module.' . $this->identifier;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Extension\Cache;
/**
* 플러그인 캐시 드라이버
*
* 각 플러그인에서 사용하는 캐시를 관리합니다.
* 접두사 패턴: g7:plugin.{identifier}:{key}
*
* @since engine-v1.18.0
*/
class PluginCacheDriver extends AbstractCacheDriver
{
/**
* 플러그인 식별자
*/
private string $identifier;
/**
* PluginCacheDriver 생성자
*
* @param string $identifier 플러그인 식별자 (예: sirsoft-payment)
* @param string $store 캐시 스토어 이름 (빈 문자열이면 기본 스토어)
*/
public function __construct(string $identifier, string $store = '')
{
$this->identifier = $identifier;
$this->store = $store ?: config('cache.default');
}
/**
* 플러그인 캐시 접두사를 반환합니다.
*
* @return string 접두사
*/
protected function getPrefix(): string
{
return 'g7:plugin.' . $this->identifier;
}
}
+52 -9
View File
@@ -2,9 +2,10 @@
namespace App\Extension;
use App\Contracts\Extension\CacheInterface;
use App\Extension\Cache\CoreCacheDriver;
use Composer\Semver\Semver;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
/**
@@ -16,9 +17,9 @@ use Illuminate\Support\Facades\Log;
class CoreVersionChecker
{
/**
* 캐시 키 접두사
* 캐시 키 접두사 (드라이버 접두사 `g7:core:` 다음에 붙음)
*/
private const CACHE_PREFIX = 'core_version_check.';
private const CACHE_PREFIX = 'ext.version_check.';
/**
* 캐시 유효 시간 (초)
@@ -28,11 +29,35 @@ class CoreVersionChecker
/**
* 현재 설치된 그누보드7 코어 버전 반환
*
* @return string 코어 버전
* 반환 우선순위:
* 1. 환경변수 `APP_VERSION` (getenv / $_ENV / $_SERVER)
* 2. `config('app.version')`
*
* 왜 env 를 우선 읽는가:
* 코어 업그레이드 중 `core:update` 는 `core:execute-upgrade-steps` / 각 업그레이드 스텝의
* inline 스크립트를 `proc_open` 으로 spawn 한다. 디스크 `.env` 의 `APP_VERSION` 은
* `updateVersionInEnv()` 가 최종 단계(Step 11)에서 기록하므로, spawn 이 부팅되는
* Step 10 시점에는 여전히 이전 버전이 남아있다. 이를 회피하기 위해 spawn 호출부는
* `APP_VERSION={toVersion}` 를 `proc_open` 의 `$env` 로 주입하지만, `bootstrap/cache/config.php`
* 가 생성되어 있으면 `LoadConfiguration` 부트스트랩이 **캐시된 리터럴** 을 사용해
* env 오버라이드가 반영되지 않는 회귀가 있었다 (확장이 `>= 신버전` 요구 시
* `validateAndDeactivateIncompatibleExtensions` 가 전 확장을 자동 비활성화).
*
* env 를 우선 읽는 본 구현은 config cache 유무와 무관하게 spawn 이 전달한 버전을 그대로
* 신뢰한다. 일반 요청 경로에서는 `APP_VERSION` 이 `.env` 에 기록된 값 그대로이므로
* 동작에 차이가 없다.
*
* 규정 예외: "env() 는 config 파일에서만 사용" 규칙의 본문 예외. 정당성은 버전 판정이
* config cache 우회를 요구하기 때문이다.
*/
public static function getCoreVersion(): string
{
return config('app.version', '7.0.0-alpha.1');
$envVersion = $_ENV['APP_VERSION'] ?? $_SERVER['APP_VERSION'] ?? getenv('APP_VERSION');
if (is_string($envVersion) && $envVersion !== '') {
return $envVersion;
}
return config('app.version');
}
/**
@@ -117,9 +142,27 @@ class CoreVersionChecker
*/
public static function clearCache(): void
{
Cache::forget(self::getCacheKey('modules'));
Cache::forget(self::getCacheKey('plugins'));
Cache::forget(self::getCacheKey('templates'));
$cache = self::resolveCache();
$cache->forget(self::getCacheKey('modules'));
$cache->forget(self::getCacheKey('plugins'));
$cache->forget(self::getCacheKey('templates'));
}
/**
* CacheInterface 인스턴스를 컨테이너에서 lazy 조회합니다.
*
* 컨테이너 미구성 환경(예: 일부 단위 테스트)에서도 동작하도록
* fallback 으로 직접 CoreCacheDriver 를 생성합니다.
*
* @return CacheInterface
*/
private static function resolveCache(): CacheInterface
{
try {
return app(CacheInterface::class);
} catch (\Throwable $e) {
return new CoreCacheDriver(config('cache.default', 'array'));
}
}
/**
@@ -129,6 +172,6 @@ class CoreVersionChecker
*/
public static function getCacheTtl(): int
{
return self::CACHE_TTL;
return (int) g7_core_settings('cache.version_check_ttl', self::CACHE_TTL);
}
}
+207 -110
View File
@@ -4,6 +4,7 @@ namespace App\Extension;
use App\Contracts\Repositories\ModuleRepositoryInterface;
use App\Contracts\Repositories\PluginRepositoryInterface;
use App\Extension\Helpers\GithubHelper;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
@@ -53,6 +54,47 @@ class ExtensionManager
}
$this->generateAutoloadFile();
// 현재 프로세스의 Composer ClassLoader 에도 갱신된 PSR-4 를 즉시 반영.
// 파일 쓰기만으로는 다음 요청 부트스트랩 시점부터 적용되므로, 업데이트 실행
// 흐름(copyToActive → updateComposerAutoload → runUpgradeSteps) 내에서
// 신규 네임스페이스(beta 업그레이드로 추가된 Seeder/Model 등) 의 autoload 가
// 실패하지 않도록 런타임 재등록을 수행한다.
$this->reregisterRuntimeAutoload();
}
/**
* 현재 프로세스의 Composer ClassLoader 에 갱신된 PSR-4 매핑을 재등록합니다.
*
* `generateAutoloadFile()` 은 autoload-extensions.php 를 디스크에 다시 쓰지만,
* 이 파일은 CoreServiceProvider::register() / public/index.php 진입점에서만
* 로드되므로, 동일 프로세스 내부에서 PSR-4 네임스페이스가 추가·변경된 경우
* 다음 부트스트랩 이전까지 신규 매핑이 반영되지 않는다.
*
* 본 메서드는 `Composer\Autoload\ClassLoader::getRegisteredLoaders()` 로 현재
* 프로세스에 등록된 ClassLoader 를 조회하여 `addPsr4()` 를 다시 호출해 신규
* 매핑을 즉시 유효화한다. 기존 매핑에 경로가 추가되거나 새 네임스페이스가
* 등록되며, 동일 매핑은 중복 없이 merge 된다.
*/
protected function reregisterRuntimeAutoload(): void
{
if (! class_exists(\Composer\Autoload\ClassLoader::class, false)) {
return;
}
if (! file_exists($this->autoloadFilePath)) {
return;
}
$loaders = \Composer\Autoload\ClassLoader::getRegisteredLoaders();
if (empty($loaders)) {
return;
}
foreach ($loaders as $loader) {
self::registerExtensionAutoload($loader);
break;
}
}
/**
@@ -925,86 +967,12 @@ PHP;
}
// ──────────────────────────────────────────────────
// GitHub 다운로드 유틸리티 (코어와 동일한 패턴)
// GitHub 다운로드 유틸리티 (GithubHelper로 위임)
//
// `allow_url_fopen=Off` 공유 호스팅 대응을 위해 실제 HTTP 호출은
// `GithubHelper`의 Http 파사드 기반 구현을 사용합니다.
// ──────────────────────────────────────────────────
/**
* GitHub API용 인증 헤더를 생성합니다.
*
* @param string $token GitHub Personal Access Token (선택)
* @return array HTTP 헤더 배열
*/
public function buildGithubHeaders(string $token = ''): array
{
$headers = [
'User-Agent: G7',
'Accept: application/vnd.github.v3+json',
];
if (! empty($token)) {
$headers[] = 'Authorization: Bearer '.$token;
}
return $headers;
}
/**
* GitHub 아카이브 URL을 해석합니다.
*
* v접두사 유무 모두 시도하여 유효한 아카이브 URL을 반환합니다.
*
* @param string $owner GitHub 저장소 소유자
* @param string $repo GitHub 저장소 이름
* @param string $version 버전 태그
* @param string $archiveType 아카이브 타입 (zipball/tarball)
* @param array $authHeaders 인증 헤더
* @return string|null 유효한 URL 또는 null
*/
public function resolveGithubArchiveUrl(string $owner, string $repo, string $version, string $archiveType, array $authHeaders): ?string
{
$tagVariants = ["v{$version}", $version];
foreach ($tagVariants as $tag) {
$testUrl = "https://api.github.com/repos/{$owner}/{$repo}/{$archiveType}/{$tag}";
$testContext = stream_context_create([
'http' => [
'method' => 'HEAD',
'header' => $authHeaders,
'timeout' => 10,
'ignore_errors' => true,
],
]);
@file_get_contents($testUrl, false, $testContext);
$statusCode = $this->extractHttpStatusCode($http_response_header ?? []);
if ($statusCode === 200 || $statusCode === 302) {
return $testUrl;
}
}
return null;
}
/**
* HTTP 응답 헤더에서 상태 코드를 추출합니다.
*
* 리다이렉트 시 마지막 상태 코드를 반환합니다.
*
* @param array $responseHeaders $http_response_header 배열
* @return int HTTP 상태 코드
*/
public function extractHttpStatusCode(array $responseHeaders): int
{
$statusCode = 0;
foreach ($responseHeaders as $header) {
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $header, $matches)) {
$statusCode = (int) $matches[1];
}
}
return $statusCode;
}
/**
* 사용 가능한 아카이브 추출 전략을 구성합니다.
*
@@ -1091,40 +1059,15 @@ PHP;
return $exitCode === 0;
}
/**
* GitHub 아카이브를 다운로드합니다.
*
* @param string $url 다운로드 URL
* @param array $authHeaders 인증 헤더
* @return string 다운로드된 콘텐츠
*
* @throws \RuntimeException 다운로드 실패 시
*/
public function downloadArchive(string $url, array $authHeaders): string
{
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => $authHeaders,
'follow_location' => true,
'timeout' => 120,
],
]);
$content = @file_get_contents($url, false, $context);
if ($content === false) {
throw new \RuntimeException(__('settings.core_update.download_failed', ['version' => basename($url)]));
}
return $content;
}
/**
* GitHub에서 확장을 다운로드하고 추출합니다.
*
* 코어 업데이트의 downloadUpdate()와 동일한 폴백 체인을 사용합니다.
* (zipball/ZipArchive → zipball/unzip)
*
* 모든 HTTP 호출은 `GithubHelper` (Http 파사드 기반)로 위임되어
* `allow_url_fopen=Off` 환경에서도 정상 동작합니다.
*
* @param string $owner GitHub 저장소 소유자
* @param string $repo GitHub 저장소 이름
* @param string $version 버전 태그
@@ -1136,7 +1079,6 @@ PHP;
*/
public function downloadAndExtractFromGitHub(string $owner, string $repo, string $version, string $destDir, string $token = ''): string
{
$authHeaders = $this->buildGithubHeaders($token);
$extractDir = $destDir.DIRECTORY_SEPARATOR.'extracted';
$strategies = $this->buildExtractionStrategies();
@@ -1151,7 +1093,7 @@ PHP;
$extractMethod = $strategy['method'];
$label = $strategy['label'];
$archiveUrl = $this->resolveGithubArchiveUrl($owner, $repo, $version, $archiveType, $authHeaders);
$archiveUrl = GithubHelper::resolveArchiveUrl($owner, $repo, $version, $archiveType, $token);
if (! $archiveUrl) {
continue;
}
@@ -1160,8 +1102,7 @@ PHP;
$archivePath = $destDir.DIRECTORY_SEPARATOR.'download'.$extension;
try {
$content = $this->downloadArchive($archiveUrl, $authHeaders);
File::put($archivePath, $content);
GithubHelper::downloadArchive($archiveUrl, $archivePath, $token);
if (File::isDirectory($extractDir)) {
File::deleteDirectory($extractDir);
@@ -1206,4 +1147,160 @@ PHP;
$lastError
);
}
/**
* 외부 ZIP 파일을 추출하여 소스 디렉토리 경로를 반환합니다.
*
* GitHub zipball 처럼 owner-repo-hash/ 래퍼 디렉토리로 감싼 경우와
* ZIP 루트가 곧바로 확장 소스인 경우를 모두 지원합니다.
* 추출 후 extractDir 내용이 단일 디렉토리뿐이면 그 디렉토리를 반환하고,
* 그 외에는 extractDir 자체를 반환합니다.
*
* downloadAndExtractFromGitHub 와 동일한 폴백 체인(ZipArchive → unzip)을
* 사용하며, GitHub 호출은 수행하지 않습니다.
*
* @param string $zipPath 외부 ZIP 파일 경로
* @param string $destDir 추출 작업 디렉토리 (함수가 'extracted' 하위에 추출)
* @return string 확장 소스 디렉토리 경로 (래퍼 감지 후)
*
* @throws \RuntimeException 추출 실패 또는 지원 추출 수단 부재 시
*/
public function extractFromZip(string $zipPath, string $destDir): string
{
if (! File::exists($zipPath)) {
throw new \RuntimeException(__('settings.core_update.zip_file_not_found', ['path' => $zipPath]));
}
$strategies = $this->buildExtractionStrategies();
if (empty($strategies)) {
throw new \RuntimeException(__('settings.core_update.no_extract_method_available'));
}
$extractDir = $destDir.DIRECTORY_SEPARATOR.'extracted';
if (File::isDirectory($extractDir)) {
File::deleteDirectory($extractDir);
}
File::ensureDirectoryExists($extractDir);
$lastError = null;
foreach ($strategies as $strategy) {
$method = $strategy['method'];
$label = $strategy['label'];
try {
$this->$method($zipPath, $extractDir);
return $this->resolveExtractedRoot($extractDir);
} catch (\Throwable $e) {
$lastError = $e;
// 다음 전략 시도 전 extractDir 초기화
if (File::isDirectory($extractDir)) {
File::deleteDirectory($extractDir);
}
File::ensureDirectoryExists($extractDir);
Log::warning("ZIP 추출 폴백: {$label} 실패", [
'zip' => $zipPath,
'error' => $e->getMessage(),
]);
}
}
throw new \RuntimeException(
__('settings.core_update.all_extract_methods_failed'),
0,
$lastError
);
}
/**
* 추출 디렉토리에서 확장 소스 루트를 판별합니다.
*
* - 하위에 파일이 있고 디렉토리가 0개 또는 2개 이상 → extractDir 자체가 소스
* - 하위에 디렉토리 1개만 있고 파일 없음 → 그 디렉토리가 래퍼 → 하위 반환
* - 혼합(파일 + 단일 디렉토리)인 경우 → extractDir 자체 반환 (manifest 루트에 있다고 가정)
*
* @param string $extractDir 추출 대상 디렉토리
* @return string 확장 소스 디렉토리 경로
*/
protected function resolveExtractedRoot(string $extractDir): string
{
$dirs = File::directories($extractDir);
$files = File::files($extractDir);
if (count($dirs) === 1 && count($files) === 0) {
return $dirs[0];
}
return $extractDir;
}
/**
* 외부 ZIP 소스를 스테이징 전단계까지 준비합니다.
*
* 각 확장 Manager(Module/Plugin/Template)의 --zip 업데이트 경로에서
* 공용으로 사용하는 헬퍼입니다. ZIP 을 임시 디렉토리에 추출하고 manifest 를
* 검증(파일 존재, identifier 일치, version 존재)한 뒤 결과를 반환합니다.
*
* 호출자는 반환된 temp_dir 을 반드시 정리해야 합니다 (try-finally 로 감싸는 것을 권장).
*
* @param string $zipPath 외부 ZIP 파일 경로
* @param string $identifier 기대하는 확장 식별자 (manifest 와 일치해야 함)
* @param string $manifestName manifest 파일명 ('module.json' | 'plugin.json' | 'template.json')
* @return array{temp_dir: string, extracted_dir: string, to_version: string, manifest: array}
*
* @throws \RuntimeException ZIP 추출 실패 / manifest 누락 / identifier 불일치 / version 누락 시
*/
public function prepareZipSource(string $zipPath, string $identifier, string $manifestName): array
{
$tempDir = storage_path('app/temp/ext_zip_'.uniqid());
File::ensureDirectoryExists($tempDir);
try {
$extractedDir = $this->extractFromZip($zipPath, $tempDir);
$manifestPath = $extractedDir.DIRECTORY_SEPARATOR.$manifestName;
if (! File::exists($manifestPath)) {
throw new \RuntimeException(__('extensions.errors.zip_missing_manifest', [
'file' => $manifestName,
'zip' => $zipPath,
]));
}
$manifest = json_decode(File::get($manifestPath), true);
if (! is_array($manifest)) {
throw new \RuntimeException(__('extensions.errors.zip_invalid_manifest', [
'file' => $manifestName,
]));
}
$manifestId = $manifest['identifier'] ?? null;
if ($manifestId !== $identifier) {
throw new \RuntimeException(__('extensions.errors.zip_identifier_mismatch', [
'expected' => $identifier,
'actual' => $manifestId ?? '(missing)',
]));
}
$version = $manifest['version'] ?? null;
if (! is_string($version) || $version === '') {
throw new \RuntimeException(__('extensions.errors.zip_missing_version', [
'file' => $manifestName,
]));
}
return [
'temp_dir' => $tempDir,
'extracted_dir' => $extractedDir,
'to_version' => $version,
'manifest' => $manifest,
];
} catch (\Throwable $e) {
if (File::isDirectory($tempDir)) {
File::deleteDirectory($tempDir);
}
throw $e;
}
}
}
@@ -0,0 +1,134 @@
<?php
namespace App\Extension\Helpers;
use App\Contracts\Repositories\ModuleRepositoryInterface;
use App\Contracts\Repositories\PluginRepositoryInterface;
use Composer\Semver\Semver;
use Illuminate\Support\Facades\App;
/**
* 확장 의존성 정보 보강 헬퍼
*
* manifest 의 dependencies 필드(`{modules|plugins}.{id}: versionConstraint`) 를 받아
* 각 의존 확장의 설치 버전, 활성 여부, 버전 제약 충족 여부를 포함한 상세 배열로 변환합니다.
* ModuleManager / PluginManager / TemplateResource 가 공용으로 사용합니다.
*/
class DependencyEnricher
{
/**
* 의존성 배열을 상세 정보로 보강합니다.
*
* @param array $dependencies manifest 의 dependencies 배열 (`['modules' => [...], 'plugins' => [...]]`)
* @return array<int, array<string, mixed>> 보강된 의존성 목록 (type 필드로 module/plugin 구분)
*/
public static function enrich(array $dependencies): array
{
$result = [];
foreach (self::enrichByType($dependencies, 'modules') as $item) {
$result[] = $item;
}
foreach (self::enrichByType($dependencies, 'plugins') as $item) {
$result[] = $item;
}
return $result;
}
/**
* 특정 타입(modules/plugins)의 의존성만 보강합니다.
*
* @param array $dependencies manifest 의 dependencies 배열
* @param string $type 'modules' 또는 'plugins'
* @return array<int, array<string, mixed>> 보강된 의존성 목록
*/
protected static function enrichByType(array $dependencies, string $type): array
{
if (! isset($dependencies[$type]) || ! is_array($dependencies[$type])) {
return [];
}
$singular = $type === 'modules' ? 'module' : 'plugin';
$repository = $type === 'modules'
? app(ModuleRepositoryInterface::class)
: app(PluginRepositoryInterface::class);
$result = [];
foreach ($dependencies[$type] as $identifier => $versionConstraint) {
$record = $repository->findByIdentifier($identifier);
$activeRecord = $repository->findActiveByIdentifier($identifier);
$installedVersion = $record?->version;
$isActive = (bool) $activeRecord;
$isMet = $isActive
&& $installedVersion
&& self::checkVersionConstraint($installedVersion, (string) $versionConstraint);
$result[] = [
'identifier' => $identifier,
'name' => self::resolveName($record, $identifier),
'type' => $singular,
'required_version' => $versionConstraint,
'installed_version' => $installedVersion,
'is_active' => $isActive,
'is_met' => $isMet,
];
}
return $result;
}
/**
* Semver 제약 조건을 검증합니다.
*
* @param string $installedVersion 설치된 버전
* @param string $versionConstraint 요구 버전 제약
* @return bool 제약 충족 여부
*/
public static function checkVersionConstraint(string $installedVersion, string $versionConstraint): bool
{
try {
return Semver::satisfies($installedVersion, $versionConstraint);
} catch (\Exception $e) {
return false;
}
}
/**
* 확장 모델에서 현재 로케일의 이름을 추출합니다.
*
* @param object|null $record 확장 모델 (Module/Plugin)
* @param string $fallback 모델이 없을 때 반환할 식별자
* @return string 이름
*/
protected static function resolveName(?object $record, string $fallback): string
{
if (! $record) {
return $fallback;
}
$name = $record->name ?? null;
if (is_array($name)) {
$locale = App::getLocale();
$fallbackLocale = config('app.fallback_locale', 'ko');
return (string) ($name[$locale] ?? $name[$fallbackLocale] ?? reset($name) ?: $fallback);
}
if (is_string($name) && str_starts_with($name, '{')) {
$decoded = json_decode($name, true);
if (is_array($decoded)) {
$locale = App::getLocale();
$fallbackLocale = config('app.fallback_locale', 'ko');
return (string) ($decoded[$locale] ?? $decoded[$fallbackLocale] ?? reset($decoded) ?: $fallback);
}
}
return (string) ($name ?? $fallback);
}
}
@@ -205,9 +205,17 @@ class ExtensionMenuSyncHelper
/**
* 현재 확장에 속하지 않는 stale 메뉴를 정리합니다.
*
* ⚠️ 주의: 이 메서드는 정적 정의(getAdminMenus()) 기반으로만 판단하므로,
* 확장이 런타임에 동적으로 생성한 메뉴도 삭제됩니다.
* 자동 호출은 폐기되었으며, 필요 시 UpgradeStep에서 명시적으로 호출하세요.
* 정책:
* - config/확장 정의에 없는 메뉴는 **user_overrides 유무 무관 삭제**
* - 필드 단위 보존은 **upsert 시점(`syncMenu()`)** 에서만 작동 (유지 row 에 한해 override 필드만 보존)
* - row 자체의 존재 여부는 config 기준으로만 결정 (사용자 수정 이력이 있어도 정의에서 제거되면 삭제)
*
* 자식 메뉴는 부모 삭제 시 함께 정리 (orphan 회피).
*
* 자동 호출 경로:
* - `CoreUpdateService::syncCoreMenus()` 말미 (완전 동기화 원칙)
* - `ModuleManager::updateModule()` 말미 (확장 동기화)
* - UpgradeStep 에서 명시 호출
*
* @param ExtensionOwnerType $extensionType 확장 타입
* @param string $extensionIdentifier 확장 식별자
@@ -225,20 +233,22 @@ class ExtensionMenuSyncHelper
$deleted = 0;
foreach ($existingMenus as $menu) {
if (! in_array($menu->slug, $currentSlugs, true)) {
// role_menus 피벗 정리
$menu->roles()->detach();
if (in_array($menu->slug, $currentSlugs, true)) {
continue;
}
// 자식 메뉴 먼저 삭제
foreach ($menu->children as $child) {
$child->roles()->detach();
$this->menuRepository->delete($child);
$deleted++;
}
// role_menus 피벗 정리
$menu->roles()->detach();
$this->menuRepository->delete($menu);
// 자식 메뉴 먼저 삭제 (orphan 회피)
foreach ($menu->children as $child) {
$child->roles()->detach();
$this->menuRepository->delete($child);
$deleted++;
}
$this->menuRepository->delete($menu);
$deleted++;
}
if ($deleted > 0) {
@@ -57,6 +57,17 @@ class ExtensionPendingHelper
$dirName = basename($dir);
$identifier = $data['identifier'] ?? $dirName;
// 디렉토리명과 identifier 가 일치하는 경우만 등록.
// _pending / _bundled 에는 업데이트·백업 과정의 임시 디렉토리
// (예: sirsoft-admin_basic_20260402_081819, sirsoft-admin_basic_updating_<uniq>,
// sirsoft-admin_basic_old_<uniq>) 가 남을 수 있고, 그 내부에 원본 manifest 가 그대로
// 있어 identifier 가 원본과 동일해진다. 이 경우 표준 경로({basePath}/{subDir}/{identifier})
// 와 실제 디렉토리 경로가 어긋나 install 이 실패하므로, 엄격히 일치하는 경로만
// 정식 확장 소스로 인정한다.
if ($dirName !== $identifier) {
continue;
}
$result[$identifier] = array_merge($data, [
'identifier' => $identifier,
'directory' => $dirName,
@@ -178,6 +189,19 @@ class ExtensionPendingHelper
// 교체 완료 후 _old 삭제 (실패해도 무해)
File::deleteDirectory($oldPath);
// 원자적 rename 은 inode 단위로 교체되므로 PHP realpath/stat 캐시가
// 이전 디렉토리의 파일 존재 여부를 기준으로 판단할 수 있다. 직후 Composer
// PSR-4 autoload 가 신규 파일(beta.1 에 없던 Seeder/Model)을 file_exists 로
// 탐색할 때 false 반환 → "Class not found" fatal 로 업그레이드 스텝이 실패.
// clearstatcache(true) 로 전체 stat 캐시를 비워 신규 파일이 즉시 보이도록 한다.
clearstatcache(true);
// opcache 가 활성화된 프로덕션에서는 활성 디렉토리 하위의 이전 컴파일 바이트코드가
// 남아있을 수 있어 신규 PHP 파일을 즉시 invalidate (재컴파일 유도).
if (function_exists('opcache_reset')) {
@opcache_reset();
}
}
/**
@@ -127,9 +127,14 @@ class ExtensionRoleSyncHelper
/**
* 현재 확장에 속하지 않는 stale 권한을 정리합니다.
*
* ⚠️ 주의: 이 메서드는 정적 정의(getPermissions()) 기반으로만 판단하므로,
* 확장이 런타임에 동적으로 생성한 권한도 삭제됩니다.
* 자동 호출은 폐기되었으며, 필요 시 UpgradeStep에서 명시적으로 호출하세요.
* Permission 은 설계상 **관리자가 직접 수정할 수 없는 테이블** 이므로 `user_overrides`
* 컬럼 자체가 없습니다 (Menu/Role 과 달리). 따라서 단순 diff 로 삭제합니다.
* 자식 권한도 동일하게 순수 orphan 삭제.
*
* 자동 호출 경로:
* - `CoreUpdateService::syncCoreRolesAndPermissions()` 말미 (완전 동기화 원칙)
* - `ModuleManager::updateModule()` 말미
* - UpgradeStep 에서 명시 호출
*
* @param ExtensionOwnerType $extensionType 확장 타입
* @param string $extensionIdentifier 확장 식별자
@@ -147,18 +152,22 @@ class ExtensionRoleSyncHelper
$deleted = 0;
foreach ($existingPermissions as $permission) {
if (! in_array($permission->identifier, $currentIdentifiers, true)) {
// 역할 연결 해제
$permission->roles()->detach();
// 자식 권한도 정리
foreach ($permission->children as $child) {
$child->roles()->detach();
$this->permissionRepository->delete($child);
$deleted++;
}
$this->permissionRepository->delete($permission);
if (in_array($permission->identifier, $currentIdentifiers, true)) {
continue;
}
// 역할 연결 해제
$permission->roles()->detach();
// 자식 권한도 정리 (orphan 회피)
foreach ($permission->children as $child) {
$child->roles()->detach();
$this->permissionRepository->delete($child);
$deleted++;
}
$this->permissionRepository->delete($permission);
$deleted++;
}
if ($deleted > 0) {
@@ -172,6 +181,70 @@ class ExtensionRoleSyncHelper
return $deleted;
}
/**
* 현재 확장에 속하지 않는 stale 역할을 정리합니다.
*
* 정책:
* - config/확장 정의에 없는 역할은 **user_overrides 유무 무관 삭제**
* - 필드 단위 보존은 upsert 시점(`syncRole()`) 에서만 작동
* - 예외: `user_roles` 피벗에 참조 사용자가 있으면 **삭제 차단** + 경고 로그
* (사용자를 다른 역할로 수동 재배정 후 재실행)
*
* @param ExtensionOwnerType $extensionType 확장 타입
* @param string $extensionIdentifier 확장 식별자
* @param array $currentIdentifiers 현재 유효한 역할 식별자 목록
* @return int 삭제된 역할 수
*/
public function cleanupStaleRoles(
ExtensionOwnerType $extensionType,
string $extensionIdentifier,
array $currentIdentifiers,
): int {
$existingRoles = $this->roleRepository->getByExtension($extensionType, $extensionIdentifier);
$deleted = 0;
$blocked = 0;
foreach ($existingRoles as $role) {
if (in_array($role->identifier, $currentIdentifiers, true)) {
continue;
}
// user_roles 피벗 참조 검사 — 하나라도 있으면 삭제 차단 (안전 가드)
$userCount = $role->users()->count();
if ($userCount > 0) {
Log::warning('stale 역할 삭제 차단 — 참조 사용자 존재', [
'identifier' => $role->identifier,
'id' => $role->id,
'user_count' => $userCount,
'remediation' => '사용자를 다른 역할로 재배정 후 재실행 필요',
]);
$blocked++;
continue;
}
// 조건 통과 → 삭제 (role_permissions, role_menus 는 cascade 또는 모델 이벤트로 정리)
$this->roleRepository->delete($role);
Log::info('stale 역할 삭제', [
'identifier' => $role->identifier,
'id' => $role->id,
]);
$deleted++;
}
if ($deleted > 0 || $blocked > 0) {
Log::info('stale 역할 정리 결과', [
'extension_type' => $extensionType->value,
'extension_identifier' => $extensionIdentifier,
'deleted' => $deleted,
'blocked' => $blocked,
]);
}
return $deleted;
}
/**
* 확장의 전체 역할-권한 할당을 일괄 동기화합니다.
*
+214 -48
View File
@@ -60,6 +60,24 @@ class FileHandleHelper
return [];
}
// 존재하지 않는 디렉토리는 잠금이 있을 수 없음 → WMI 전체 스캔 회피
// (Get-Process 의 Modules 열거는 수백 프로세스에 접근 핸들을 열어 20초+ 소요 가능)
if (! is_dir($directoryPath)) {
$output('[lock-detect] 디렉토리가 존재하지 않으므로 잠금 감지를 건너뜁니다: '.$directoryPath);
return [];
}
// 파일이 전혀 없는 디렉토리도 파일 수준 잠금이 있을 수 없음
// 디렉토리 핸들 자체를 잠그는 드문 케이스는 Restart Manager 로는 감지 불가하고
// WMI 모듈 검색의 비용이 압도적으로 크므로 빠른 경로로 처리한다.
$files = self::sampleFiles($directoryPath, $maxFiles);
if (empty($files)) {
$output('[lock-detect] 디렉토리가 비어 있으므로 잠금 감지를 건너뜁니다: '.$directoryPath);
return [];
}
$allProcesses = [];
// 1순위: WMI CommandLine + 프로세스 모듈 검색
@@ -70,27 +88,18 @@ class FileHandleHelper
}
// 2순위: Restart Manager API (파일 수준 잠금)
$files = self::sampleFiles($directoryPath, $maxFiles);
if (! empty($files)) {
$output('[lock-detect] 2단계: Restart Manager API ('.count($files).'개 파일)...');
$rmResults = self::detectViaRestartManager($files, $onOutput);
foreach ($rmResults as $proc) {
if (! isset($allProcesses[$proc['pid']])) {
$allProcesses[$proc['pid']] = $proc;
}
$output('[lock-detect] 2단계: Restart Manager API ('.count($files).'개 파일)...');
$rmResults = self::detectViaRestartManager($files, $onOutput);
foreach ($rmResults as $proc) {
if (! isset($allProcesses[$proc['pid']])) {
$allProcesses[$proc['pid']] = $proc;
}
}
// 3순위: handle.exe 폴백
if (empty($allProcesses)) {
$output('[lock-detect] 3단계: handle.exe 폴백...');
$handleResults = self::detectViaHandle($directoryPath, $onOutput);
foreach ($handleResults as $proc) {
if (! isset($allProcesses[$proc['pid']])) {
$allProcesses[$proc['pid']] = $proc;
}
}
}
// 빈 결과 = "잠금 없음" 이라는 정상 응답이므로 폴백을 호출하지 않는다.
// (handle.exe 는 Sysinternals 외부 도구이고, Windows Store App Execution Alias 와
// 충돌하는 경우 무한 대기하므로 명시적으로 사용 가능한 경우에만 호출.)
// 현재 PHP 프로세스 제외
$currentPid = self::currentPid();
@@ -165,12 +174,8 @@ class FileHandleHelper
$processes = self::findLockingProcesses($directoryPath, 30, $onOutput);
if (empty($processes)) {
$output('');
$output('ℹ️ 잠금 프로세스가 감지되지 않았습니다.');
$output(' 수동 해결: 해당 디렉토리를 참조하는 프로세스를 닫은 후 재시도하세요.');
$output('');
return false;
// 해제할 잠금이 없으므로 호출자는 안전하게 진행 가능
return true;
}
$output('');
@@ -224,9 +229,14 @@ class FileHandleHelper
/**
* WMI로 해당 디렉토리 경로를 참조하는 프로세스를 탐지합니다.
*
* Get-CimInstance Win32_Process의 CommandLine에 디렉토리 경로가 포함된 프로세스와,
* Get-Process의 Modules에서 해당 디렉토리 내 DLL을 로드한 프로세스를 찾습니다.
* Node.js 워처, IDE, 파일 탐색기 등 프로세스 종류 무관하게 감지합니다.
* Get-CimInstance Win32_Process의 CommandLine에 디렉토리 경로가 포함된 프로세스를 찾습니다.
*
* 과거 버전은 Get-Process 의 Modules 컬렉션(로드된 DLL) 까지 스캔했지만,
* 이는 모든 프로세스에 접근 핸들을 열어 DLL 테이블을 열거하므로
* 활성 프로세스가 수백 개인 Windows 환경에서 20초+ 블로킹을 유발합니다.
* Modules 스캔은 Node.js native addon 등 드문 케이스만 감지하므로
* 비용 대비 효과가 낮아 CommandLine 검색만 유지합니다.
* (Node 워처, IDE, 파일 탐색기 등 실사용 케이스는 CommandLine 으로 충분히 감지됩니다.)
*
* @param string $directoryPath 디렉토리 경로
* @param \Closure|null $onOutput 진단 출력 콜백
@@ -247,25 +257,21 @@ class FileHandleHelper
$escapedPath = str_replace("'", "''", $normalizedPath);
// 간결한 인라인 PowerShell — 임시 파일 불필요
// CommandLine 검색만 수행 (Modules 스캔은 수백 프로세스 핸들 오픈으로 인해 제거됨)
$psCommand = implode('; ', [
'$ErrorActionPreference = "SilentlyContinue"',
'$p = "'.addcslashes($escapedPath, '"').'"',
'$pl = $p.ToLower()',
'$r = @{}',
// Strategy 1: CommandLine search
'Get-CimInstance Win32_Process | ForEach-Object { if ($_.CommandLine) { $cl = $_.CommandLine.ToLower().Replace("/","\\"); if ($cl.Contains($pl)) { $r[$_.ProcessId] = "$($_.ProcessId)|$($_.Name)|$($_.CommandLine.Substring(0,[Math]::Min(120,$_.CommandLine.Length)))" } } }',
// Strategy 2: Modules search
'Get-Process | ForEach-Object { if (-not $r.ContainsKey($_.Id)) { try { foreach ($m in $_.Modules) { if ($m.FileName -and $m.FileName.ToLower().StartsWith($pl)) { $r[$_.Id] = "$($_.Id)|$($_.ProcessName)|module:$($m.FileName)"; break } } } catch {} } }',
// Output
'foreach ($v in $r.Values) { Write-Output $v }',
]);
$cmdOutput = [];
$exitCode = 0;
exec(
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command '.escapeshellarg($psCommand).' 2>NUL',
$cmdOutput,
$exitCode
// exec() 대신 proc_open 사용 — PHPUnit 환경에서 상속된 부모 파이프로 인한
// PowerShell 하위 프로세스 블로킹을 회피한다.
[$cmdOutput, $exitCode] = self::runCommandWithTimeout(
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command '.escapeshellarg($psCommand),
30
);
$output("[WMI] PowerShell exit code: {$exitCode}, 출력: ".count($cmdOutput).'줄');
@@ -320,14 +326,16 @@ class FileHandleHelper
$stderrPath = $scriptPath.'.err';
try {
$cmdOutput = [];
$exitCode = 0;
exec(
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File '.escapeshellarg($scriptPath).' 2>'.escapeshellarg($stderrPath),
$cmdOutput,
$exitCode
[$cmdOutput, $exitCode, $stderrCaptured] = self::runCommandWithTimeout(
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File '.escapeshellarg($scriptPath),
30,
true
);
if ($stderrCaptured !== '') {
@file_put_contents($stderrPath, $stderrCaptured);
}
$output("[RestartManager] exit code: {$exitCode}, 출력: ".count($cmdOutput).'줄');
if (file_exists($stderrPath)) {
@@ -480,14 +488,25 @@ PSFOOTER;
return [];
}
$cmdOutput = [];
$exitCode = 0;
// PATH 에 handle.exe 가 있는지 사전 검사 (없는 경우 즉시 skip)
// - handle.exe 미설치 시 cmd.exe 가 명령을 찾는 데 수십 초가 걸리거나
// EULA 다이얼로그로 인해 무한 대기에 빠질 수 있음.
// - 결과는 정적 캐시하여 같은 프로세스에서 반복 검사 회피.
static $handleAvailable = null;
if ($handleAvailable === null) {
$handleAvailable = self::isCommandAvailable('handle.exe');
}
if (! $handleAvailable) {
$logOutput('[handle.exe] PATH 에서 찾을 수 없어 건너뜁니다.');
return [];
}
$dirPath = str_replace('/', '\\', $directoryPath);
exec(
'handle.exe -nobanner -accepteula '.escapeshellarg($dirPath).' 2>NUL',
$cmdOutput,
$exitCode
[$cmdOutput, $exitCode] = self::runCommandWithTimeout(
'handle.exe -nobanner -accepteula '.escapeshellarg($dirPath),
5
);
if ($exitCode !== 0 || empty($cmdOutput)) {
@@ -501,6 +520,43 @@ PSFOOTER;
return self::parseHandleOutput($cmdOutput);
}
/**
* Windows PATH 에서 명령어 실행 파일이 발견되는지 빠르게 확인합니다.
*
* Windows Store App Execution Alias(`%LOCALAPPDATA%\Microsoft\WindowsApps\*.exe`)는
* 실제 실행 파일이 아닌 0바이트 stub 으로, 호출 시 Microsoft Store 앱을 실행하려
* 시도하면서 무한 대기를 유발합니다. PATH 검색 결과에서 이런 경로를 제외합니다.
*
* @param string $command 명령어 파일명 (예: 'handle.exe')
*/
private static function isCommandAvailable(string $command): bool
{
if (! self::isWindows()) {
return false;
}
// `where` 는 PATH 검색이 빠르며, 미발견 시 1초 이내에 exit code 1 반환
[$out, $code] = self::runCommandWithTimeout('where '.escapeshellarg($command), 3);
if ($code !== 0 || empty($out)) {
return false;
}
// Windows Store App Execution Alias 경로 제외
foreach ($out as $path) {
$path = trim($path);
if ($path === '' || stripos($path, '\\Microsoft\\WindowsApps\\') !== false) {
continue;
}
// 0 바이트 파일은 stub 으로 간주
if (@filesize($path) > 0) {
return true;
}
}
return false;
}
// ========================================================================
// 파서/유틸리티
// ========================================================================
@@ -606,6 +662,116 @@ PSFOOTER;
return $processes;
}
/**
* 외부 명령을 타임아웃과 함께 실행합니다 (부모 파이프 비상속).
*
* exec()/shell_exec() 는 내부적으로 `sh -c` 또는 `cmd.exe /c` 를 통해 자식
* 프로세스를 스폰하며, 부모 PHP 프로세스의 stdin/stdout/stderr 핸들을 그대로
* 상속시킵니다. PHPUnit 과 같이 stdout 을 자체 파이프로 모니터링하는 환경에서는
* 자식 프로세스가 상속된 파이프에 블로킹 쓰기를 수행할 때 무한 대기가 발생합니다.
*
* proc_open 으로 자체 파이프를 명시적으로 열면 상속을 차단하여 이 문제를 회피합니다.
* 또한 poll 루프에서 deadline 을 초과하면 강제 종료(TerminateProcess)합니다.
*
* @param string $command 실행할 명령 문자열
* @param int $timeoutSeconds 최대 실행 시간(초)
* @param bool $returnStderr true 면 세 번째 요소로 stderr 문자열을 함께 반환
* @return array{0: string[], 1: int, 2?: string} [stdout 라인 배열, exit code, (stderr 문자열)]
*/
private static function runCommandWithTimeout(string $command, int $timeoutSeconds, bool $returnStderr = false): array
{
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$pipes = [];
$process = @proc_open($command, $descriptors, $pipes, null, null, [
'bypass_shell' => false,
'create_new_console' => false,
]);
if (! is_resource($process)) {
return $returnStderr ? [[], -1, ''] : [[], -1];
}
// stdin 즉시 닫기 (하위 프로세스가 입력 대기 방지)
fclose($pipes[0]);
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$stdout = '';
$stderr = '';
$deadline = microtime(true) + $timeoutSeconds;
$timedOut = false;
while (true) {
$status = proc_get_status($process);
if (! $status['running']) {
break;
}
if (microtime(true) >= $deadline) {
$timedOut = true;
break;
}
$read = [$pipes[1], $pipes[2]];
$write = null;
$except = null;
// 100ms 씩 poll (Windows 는 select() 정확도 한계)
$ready = @stream_select($read, $write, $except, 0, 100_000);
if ($ready > 0) {
foreach ($read as $stream) {
$chunk = fread($stream, 8192);
if ($chunk !== false && $chunk !== '') {
if ($stream === $pipes[1]) {
$stdout .= $chunk;
} else {
$stderr .= $chunk;
}
}
}
}
}
// 남은 출력 흡수
$stdout .= stream_get_contents($pipes[1]) ?: '';
$stderr .= stream_get_contents($pipes[2]) ?: '';
fclose($pipes[1]);
fclose($pipes[2]);
if ($timedOut) {
// Windows: taskkill /F /T 로 자식 트리까지 종료
$status = proc_get_status($process);
if (! empty($status['pid'])) {
if (PHP_OS_FAMILY === 'Windows') {
@exec('taskkill /F /T /PID '.$status['pid'].' 2>NUL');
} else {
@posix_kill($status['pid'], 9);
}
}
proc_terminate($process, 9);
}
$exitCode = proc_close($process);
$lines = $stdout === '' ? [] : preg_split("/\r\n|\n|\r/", rtrim($stdout, "\r\n"));
if ($lines === false) {
$lines = [];
}
if ($returnStderr) {
return [$lines, $exitCode, $stderr];
}
return [$lines, $exitCode];
}
/**
* 시스템 프로세스 여부를 확인합니다.
*
+200 -14
View File
@@ -3,6 +3,7 @@
namespace App\Extension\Helpers;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
class FilePermissionHelper
{
@@ -10,12 +11,16 @@ class FilePermissionHelper
* 디렉토리를 재귀적으로 복사하면서 기존 파일/디렉토리의 퍼미션을 보존합니다.
*
* - 기존 디렉토리: 퍼미션/소유자/그룹 유지
* - 신규 디렉토리: 부모 디렉토리의 퍼미션 상속
* - 신규 디렉토리: 부모 디렉토리의 퍼미션/소유자/그룹 상속
* - 기존 파일: 퍼미션/소유자/그룹 유지한 채 내용만 교체
* - 신규 파일: PHP 기본 퍼미션 적용 (umask 기반)
* - 신규 파일: 부모 디렉토리의 소유자/그룹 상속 (퍼미션은 PHP 기본 umask)
* - removeOrphans=false: 소스에 없고 대상에만 있는 파일 유지 (사용자 추가 파일 보호)
* - removeOrphans=true: 소스에 없고 대상에만 있는 파일/디렉토리 삭제 (excludes 제외)
*
* 신규 항목의 소유권 상속은 sudo 로 실행된 업데이트 프로세스가 root 소유로 파일을
* 생성하는 것을 방지한다. vendor/ 처럼 cleanDirectory 후 재생성되는 디렉토리 구조
* 전체가 기존 부모(= vendor/) 의 소유권을 승계하도록 보장한다.
*
* @param string $source 소스 디렉토리 경로
* @param string $destination 대상 디렉토리 경로
* @param \Closure|null $onProgress 진행 콜백
@@ -27,10 +32,8 @@ class FilePermissionHelper
public static function copyDirectory(string $source, string $destination, ?\Closure $onProgress = null, array $excludes = [], string $relativePath = '', bool $removeOrphans = false): void
{
if (! File::isDirectory($destination)) {
// 신규 디렉토리: 부모 디렉토리의 퍼미션 상속
$parentDir = dirname($destination);
$parentPerms = File::isDirectory($parentDir) ? (fileperms($parentDir) & 0777) : 0755;
File::ensureDirectoryExists($destination, $parentPerms, true);
// 신규 디렉토리: 부모 디렉토리의 퍼미션/소유권 상속
static::createDirectoryInheritingParent($destination);
}
// 기존 디렉토리: 퍼미션 건드리지 않음 (그대로 유지)
@@ -130,7 +133,11 @@ class FilePermissionHelper
* 퍼미션과 소유권을 보존하면서 파일을 복사합니다.
*
* - 기존 파일: 복사 후 원래 퍼미션/소유자/그룹 복원
* - 신규 파일: PHP 기본 퍼미션 적용 (umask 기반)
* - 신규 파일: 부모 디렉토리의 소유자/그룹 상속 (퍼미션은 PHP 기본 umask)
*
* 신규 파일에 부모 소유권을 상속시키는 이유는 sudo 로 실행된 업데이트가 root 소유로
* 파일을 생성하는 문제를 방지하기 위함이다. vendor/ 내부처럼 cleanDirectory 후
* 전량 재생성되는 경로에서 필요하다.
*
* @param string $source 소스 파일
* @param string $destination 대상 파일
@@ -138,11 +145,12 @@ class FilePermissionHelper
*/
public static function copyFile(string $source, string $destination): void
{
$isExisting = File::exists($destination);
$existingPerms = null;
$existingOwner = null;
$existingGroup = null;
if (File::exists($destination)) {
if ($isExisting) {
$existingPerms = fileperms($destination);
$existingOwner = fileowner($destination);
$existingGroup = filegroup($destination);
@@ -151,14 +159,192 @@ class FilePermissionHelper
File::ensureDirectoryExists(dirname($destination));
File::copy($source, $destination);
if ($existingPerms !== null) {
@chmod($destination, $existingPerms);
if ($isExisting) {
// 기존 파일: 원래 퍼미션/소유권 복원
if ($existingPerms !== null) {
@chmod($destination, $existingPerms);
}
if ($existingOwner !== null && function_exists('chown')) {
@chown($destination, $existingOwner);
}
if ($existingGroup !== null && function_exists('chgrp')) {
@chgrp($destination, $existingGroup);
}
} else {
// 신규 파일: 부모 디렉토리의 소유자/그룹 상속
static::inheritOwnershipFromParent($destination);
}
if ($existingOwner !== null && function_exists('chown')) {
@chown($destination, $existingOwner);
}
/**
* 부모 디렉토리의 퍼미션·소유자·그룹을 상속하여 신규 디렉토리를 생성합니다.
*
* @param string $path 생성할 디렉토리 경로
* @return void
*/
protected static function createDirectoryInheritingParent(string $path): void
{
$parentDir = dirname($path);
$parentExists = File::isDirectory($parentDir);
$parentPerms = $parentExists ? (fileperms($parentDir) & 0777) : 0755;
File::ensureDirectoryExists($path, $parentPerms, true);
if ($parentExists) {
static::applyOwnership($path, fileowner($parentDir), filegroup($parentDir));
}
if ($existingGroup !== null && function_exists('chgrp')) {
@chgrp($destination, $existingGroup);
}
/**
* 부모 디렉토리의 소유자·그룹을 대상 경로에 상속합니다.
*
* @param string $path 소유권을 상속받을 파일 또는 디렉토리
* @return void
*/
protected static function inheritOwnershipFromParent(string $path): void
{
$parentDir = dirname($path);
if (! File::isDirectory($parentDir)) {
return;
}
static::applyOwnership($path, fileowner($parentDir), filegroup($parentDir));
}
/**
* 소유자·그룹을 적용합니다. sudo 없이 실행 시 silent fail 로 현행 동작 유지.
*
* @param string $path 대상 경로
* @param int|false $owner fileowner() 반환값 (false 허용)
* @param int|false $group filegroup() 반환값 (false 허용)
* @return void
*/
protected static function applyOwnership(string $path, int|false $owner, int|false $group): void
{
if ($owner !== false && function_exists('chown')) {
@chown($path, $owner);
}
if ($group !== false && function_exists('chgrp')) {
@chgrp($path, $group);
}
}
/**
* 웹서버(www-data 등) 계정의 소유자를 추정합니다.
*
* Laravel 표준상 웹서버가 쓰기 접근해야 하는 디렉토리(`storage/*`, `bootstrap/cache`)
* 를 순회하여 base_path() 소유자와 **다른** 첫 소유자를 "웹서버 계정" 으로 판정한다.
* 모든 후보가 base_path() 와 동일하면 대칭 구성으로 보고 base_path() 소유자를 반환.
*
* 사용 예:
* - sudo 실행된 업데이트가 원본 스냅샷을 수집하지 못한 경우의 fallback
* - 외부 프로세스(composer 등) 가 root 로 오염시킨 경로의 원본 추정
*
* @return array{0: int|false, 1: int|false, 2: string} [owner, group, source]
*/
public static function inferWebServerOwnership(): array
{
$baseOwner = @fileowner(base_path());
$baseGroup = @filegroup(base_path());
if ($baseOwner === false) {
return [false, false, 'none'];
}
$candidates = [
'storage/logs',
'storage/framework/views',
'storage/framework/cache',
'storage/app',
'storage',
'bootstrap/cache',
];
foreach ($candidates as $candidate) {
$path = base_path($candidate);
if (! File::isDirectory($path)) {
continue;
}
$owner = @fileowner($path);
if ($owner !== false && $owner !== $baseOwner) {
return [$owner, @filegroup($path), $candidate];
}
}
return [$baseOwner, $baseGroup, 'base_path (대칭 구성)'];
}
/**
* 경로와 그 하위 항목의 소유자·그룹을 재귀적으로 복원합니다.
*
* 현재 소유자가 기준과 이미 일치하면 해당 항목은 스킵. symbolic link 는 링크 자체만
* 처리하고 대상은 따라가지 않는다. @chown/@chgrp suppress 로 권한 부족 / chown 미지원
* 환경에서도 silent fail.
*
* @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
{
if (! function_exists('chown')) {
return 0;
}
// 재귀 전체 기간 동안 실패/성공을 집계하고 종료 시 요약 로그를 남긴다.
// 경로당 개별 로그는 재귀가 깊어지면 로그 폭주 유발 → 최초 실패 1건만 즉시 로깅.
$report = ['changed' => 0, 'failed' => 0, 'first_failure' => null];
self::chownRecursiveInternal($path, $owner, $group, $report);
if ($report['failed'] > 0) {
Log::warning('chownRecursive: 부분 실패', [
'root' => $path,
'owner' => $owner,
'group' => $group,
'changed' => $report['changed'],
'failed' => $report['failed'],
'first_failure' => $report['first_failure'],
]);
}
return $report['changed'];
}
/**
* chownRecursive 의 내부 재귀 구현. 실패 카운터를 참조 전달로 집계한다.
*
* @param string $path 대상 경로
* @param int $owner 기준 소유자 UID
* @param int|false $group 기준 그룹 GID
* @param array{changed:int, failed:int, first_failure:string|null} $report 집계 구조 (참조)
*/
private static function chownRecursiveInternal(string $path, int $owner, int|false $group, array &$report): void
{
$currentOwner = @fileowner($path);
if ($currentOwner !== false && $currentOwner !== $owner) {
if (@chown($path, $owner)) {
$report['changed']++;
} else {
if ($report['first_failure'] === null) {
$report['first_failure'] = $path;
Log::warning('chown 최초 실패', ['path' => $path, 'owner' => $owner]);
}
$report['failed']++;
}
if ($group !== false && function_exists('chgrp')) {
@chgrp($path, $group);
}
}
if (! is_dir($path) || is_link($path)) {
return;
}
$items = new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS);
foreach ($items as $item) {
self::chownRecursiveInternal($item->getPathname(), $owner, $group, $report);
}
}
}
@@ -0,0 +1,80 @@
<?php
namespace App\Extension\Helpers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
/**
* 범용 엔티티 동기화 헬퍼.
*
* 단일 스코프·단일 키 구조의 모듈 내부 도메인 엔티티를 대상으로
* upsert + stale cleanup 패턴을 제공합니다.
*
* 전용 helper (ExtensionMenuSyncHelper, ExtensionRoleSyncHelper,
* NotificationSyncHelper) 와의 역할 구분:
* - 전용 helper: 다중 모델 관계·피벗 참조 차단 등 도메인 로직 포함
* - 본 helper: 단일 테이블 · 단일 unique 키 · 선택적 scope 필터 범용 처리
*
* 사용 조건: 대상 모델은 `HasUserOverrides` trait 적용 필수.
*/
class GenericEntitySyncHelper
{
/**
* 엔티티를 동기화합니다 (user_overrides 보존 upsert).
*
* 내부적으로 `HasUserOverrides::syncOrCreateFromUpgrade` 를 위임 호출합니다.
*
* @template T of Model
* @param class-string<T> $modelClass HasUserOverrides 적용 모델 클래스
* @param array<string, mixed> $finder updateOrCreate 의 unique 키 조건
* @param array<string, mixed> $attributes 갱신할 속성
* @return T 동기화된 모델 인스턴스
*/
public function sync(string $modelClass, array $finder, array $attributes): Model
{
return $modelClass::syncOrCreateFromUpgrade($finder, $attributes);
}
/**
* 주어진 scope 내에서 currentKeys 에 없는 row 를 삭제합니다 (완전 동기화).
*
* 정책: `user_overrides` 무관 — seeder/config 에 없는 row 는 삭제.
*
* @param class-string<Model> $modelClass 대상 모델 클래스
* @param array<string, mixed> $scopeFilter 삭제 대상 한정 조건 (예: ['extension_identifier' => 'x', 'type' => 'refund']). 빈 배열이면 전체 테이블 대상.
* @param string $keyField 비교 기준 컬럼명 (예: 'code', 'slug', 'type')
* @param array<int, string|int> $currentKeys 현재 유효한 키 목록
* @return int 삭제된 행 수
*/
public function cleanupStale(
string $modelClass,
array $scopeFilter,
string $keyField,
array $currentKeys,
): int {
$query = $modelClass::query();
foreach ($scopeFilter as $column => $value) {
$query->where($column, $value);
}
$query->whereNotIn($keyField, $currentKeys);
$targets = $query->get(['id', $keyField]);
foreach ($targets as $row) {
$row->delete();
}
$count = $targets->count();
if ($count > 0) {
Log::info('stale 엔티티 정리 완료', [
'model' => $modelClass,
'scope' => $scopeFilter,
'key_field' => $keyField,
'deleted' => $count,
'keys' => $targets->pluck($keyField)->all(),
]);
}
return $count;
}
}
+142 -72
View File
@@ -2,6 +2,11 @@
namespace App\Extension\Helpers;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
@@ -9,6 +14,9 @@ use Illuminate\Support\Facades\Log;
*
* 코어 업데이트(CoreUpdateService)와 확장 수동 설치(ModuleService, PluginService, TemplateService)
* 모두에서 사용할 수 있는 GitHub API 관련 공통 메서드를 제공합니다.
*
* 모든 원격 HTTP 호출은 Laravel Http 파사드를 사용합니다.
* `allow_url_fopen=Off` 환경(공유 호스팅)에서도 정상 동작합니다.
*/
class GithubHelper
{
@@ -43,26 +51,20 @@ class GithubHelper
*/
public static function checkRepoExists(string $owner, string $repo, string $token = ''): bool
{
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}";
try {
$response = static::request($token, 5)
->get("https://api.github.com/repos/{$owner}/{$repo}");
} catch (ConnectionException $e) {
Log::warning('GitHub 저장소 확인 연결 실패', [
'owner' => $owner,
'repo' => $repo,
'error' => $e->getMessage(),
]);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => static::buildHeaders($token),
'timeout' => 5,
'ignore_errors' => true,
],
]);
$response = @file_get_contents($apiUrl, false, $context);
if ($response === false) {
return false;
}
$statusCode = static::extractStatusCode($http_response_header ?? []);
return $statusCode === 200;
return $response->successful();
}
/**
@@ -77,30 +79,21 @@ class GithubHelper
{
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}/releases/latest";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => static::buildHeaders($token),
'timeout' => 10,
'ignore_errors' => true,
],
]);
try {
$response = static::request($token, 10)->get($apiUrl);
} catch (ConnectionException $e) {
Log::warning('GitHub API 연결 실패', ['url' => $apiUrl, 'error' => $e->getMessage()]);
$response = @file_get_contents($apiUrl, false, $context);
if ($response === false) {
return ['version' => null, 'zipball_url' => null, 'error' => __('common.errors.github_api_failed')];
}
$statusCode = static::extractStatusCode($http_response_header ?? []);
if ($statusCode !== 200) {
if (! $response->successful()) {
return ['version' => null, 'zipball_url' => null, 'error' => null];
}
$data = json_decode($response, true);
$data = $response->json();
if (! isset($data['tag_name'])) {
if (! is_array($data) || ! isset($data['tag_name'])) {
return ['version' => null, 'zipball_url' => null, 'error' => null];
}
@@ -166,7 +159,9 @@ class GithubHelper
}
/**
* 특정 URL에서 아카이브를 다운로드합니다.
* 특정 URL에서 아카이브를 다운로드하여 파일로 저장합니다.
*
* Http 파사드의 `sink()`를 사용하여 메모리 사용을 최소화합니다.
*
* @param string $url 다운로드 URL
* @param string $savePath 저장할 파일 경로
@@ -176,22 +171,100 @@ class GithubHelper
*/
public static function downloadArchive(string $url, string $savePath, string $token = ''): void
{
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => static::buildHeaders($token),
'follow_location' => true,
'timeout' => 120,
],
]);
try {
$response = static::request($token, 120)
->sink($savePath)
->get($url);
} catch (ConnectionException $e) {
// 연결 실패 시에도 sink가 생성했을 수 있는 빈/부분 파일 정리
if (File::exists($savePath)) {
File::delete($savePath);
}
$content = @file_get_contents($url, false, $context);
Log::warning('GitHub 아카이브 다운로드 연결 실패', ['url' => $url, 'error' => $e->getMessage()]);
if ($content === false) {
throw new \RuntimeException(__('common.errors.github_archive_download_failed', ['url' => $url]));
}
\Illuminate\Support\Facades\File::put($savePath, $content);
if (! $response->successful()) {
// sink로 저장된 미완성 파일 정리
if (File::exists($savePath)) {
File::delete($savePath);
}
throw new \RuntimeException(__('common.errors.github_archive_download_failed', ['url' => $url]));
}
}
/**
* 특정 URL에서 아카이브를 다운로드하여 바이너리 내용을 반환합니다.
*
* `downloadArchive()`와 달리 파일로 저장하지 않고 메모리로 내용을 반환합니다.
* 호출부가 바이너리 내용을 직접 처리해야 하는 경우에만 사용하세요.
*
* @param string $url 다운로드 URL
* @param string $token GitHub Personal Access Token
* @return string 다운로드된 바이너리 내용
*
* @throws \RuntimeException 다운로드 실패 시
*/
public static function downloadArchiveContent(string $url, string $token = ''): string
{
try {
$response = static::request($token, 120)->get($url);
} catch (ConnectionException $e) {
Log::warning('GitHub 아카이브 다운로드 연결 실패', ['url' => $url, 'error' => $e->getMessage()]);
throw new \RuntimeException(__('settings.core_update.download_failed', ['version' => basename($url)]));
}
if (! $response->successful()) {
throw new \RuntimeException(__('settings.core_update.download_failed', ['version' => basename($url)]));
}
return $response->body();
}
/**
* GitHub 아카이브 URL을 해석합니다 (v 접두사 유/무 모두 시도).
*
* HEAD 요청으로 200/302 응답이 오는 첫 번째 URL을 반환합니다.
*
* @param string $owner 저장소 소유자
* @param string $repo 저장소 이름
* @param string $version 버전 태그 (v 접두사 유/무 무관)
* @param string $archiveType 아카이브 타입 (zipball/tarball)
* @param string $token GitHub Personal Access Token
* @return string|null 유효한 아카이브 URL 또는 null
*/
public static function resolveArchiveUrl(string $owner, string $repo, string $version, string $archiveType = 'zipball', string $token = ''): ?string
{
$tagVariants = ["v{$version}", $version];
foreach ($tagVariants as $tag) {
// GitHub API 의 `zipball/{tag}` 엔드포인트는 태그가 존재하지 않아도 무조건 302 로
// codeload 에 리다이렉트하며, 실제 다운로드 시점에 codeload 에서 404 가 반환되어
// 다운로드 파일이 "404: Not Found" 14 byte 텍스트로 저장되는 불가시 실패가 발생한다.
// 따라서 아카이브 URL 반환 전에 `git/refs/tags/{tag}` 로 태그 자체의 존재 여부를
// 먼저 검증한다 (GitHub API: 존재=200, 부재=404).
$tagCheckUrl = "https://api.github.com/repos/{$owner}/{$repo}/git/refs/tags/{$tag}";
try {
$tagResponse = static::request($token, 10)->get($tagCheckUrl);
} catch (ConnectionException $e) {
Log::info('GitHub 태그 존재 검증 실패', ['url' => $tagCheckUrl, 'error' => $e->getMessage()]);
continue;
}
if ($tagResponse->status() !== 200) {
continue;
}
return "https://api.github.com/repos/{$owner}/{$repo}/{$archiveType}/{$tag}";
}
return null;
}
/**
@@ -215,25 +288,14 @@ class GithubHelper
foreach ($refs as $tryRef) {
$url = "https://raw.githubusercontent.com/{$owner}/{$repo}/{$tryRef}/{$filePath}";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => static::buildHeaders($token),
'timeout' => 10,
'ignore_errors' => true,
],
]);
$content = @file_get_contents($url, false, $context);
if ($content === false) {
try {
$response = static::request($token, 10)->get($url);
} catch (ConnectionException $e) {
continue;
}
$statusCode = static::extractStatusCode($http_response_header ?? []);
if ($statusCode === 200) {
return $content;
if ($response->successful()) {
return $response->body();
}
}
@@ -241,7 +303,10 @@ class GithubHelper
}
/**
* GitHub API 요청용 HTTP 헤더를 생성합니다.
* GitHub API 요청용 HTTP 헤더를 생성합니다 (file_get_contents 스트림 컨텍스트 호환).
*
* 레거시 호출부 호환을 위해 배열 형태의 헤더를 반환합니다.
* 신규 코드는 `request()`를 사용하세요.
*
* @param string $token GitHub Personal Access Token (빈 문자열이면 인증 없음)
* @return array HTTP 헤더 배열
@@ -261,22 +326,27 @@ class GithubHelper
}
/**
* HTTP 응답 헤더에서 상태 코드를 추출합니다.
* GitHub API 호출을 위한 표준화된 Http 파사드 PendingRequest를 생성합니다.
*
* @param array $responseHeaders $http_response_header 배열
* @return int HTTP 상태 코드
* 모든 원격 HTTP 호출의 단일 진입점입니다. User-Agent, Accept, 토큰 인증,
* 타임아웃을 일괄 설정합니다.
*
* @param string $token GitHub Personal Access Token (빈 문자열이면 인증 없음)
* @param int $timeout 읽기 타임아웃(초)
*/
public static function extractStatusCode(array $responseHeaders): int
protected static function request(string $token = '', int $timeout = 10): PendingRequest
{
$statusCode = 0;
$request = Http::withHeaders([
'User-Agent' => 'G7',
'Accept' => 'application/vnd.github.v3+json',
])
->timeout($timeout)
->connectTimeout(5);
foreach ($responseHeaders as $header) {
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $header, $matches)) {
// 리다이렉트 시 마지막 상태 코드를 사용하기 위해 계속 진행
$statusCode = (int) $matches[1];
}
if ($token !== '') {
$request = $request->withToken($token);
}
return $statusCode;
return $request;
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Extension\Helpers;
use App\Models\NotificationDefinition;
use App\Models\NotificationTemplate;
use Illuminate\Support\Facades\Log;
/**
* 알림 정의/템플릿 동기화 헬퍼.
*
* 코어/확장 업그레이드 경로에서 알림 정의·템플릿을 동기화합니다.
* ExtensionMenuSyncHelper, ExtensionRoleSyncHelper 와 동일한 Helper 패턴을
* 따르며, 내부 upsert 는 `HasUserOverrides::syncOrCreateFromUpgrade` 에 위임하여
* trait 공통 API 를 재활용합니다.
*
* Seeder 는 본 helper 를 호출하는 얇은 진입점이며, 모든 데이터 정합성 로직은
* helper 에 집중됩니다.
*/
class NotificationSyncHelper
{
/**
* 알림 정의를 동기화합니다 (user_overrides 보존 upsert).
*
* 신규: 생성
* 기존: user_overrides 에 없는 필드만 업데이트
*
* @param array<string, mixed> $data definition 데이터 (type, hook_prefix, extension_type,
* extension_identifier, name, description, variables,
* channels, hooks, is_active, is_default, templates 포함 가능)
* @return NotificationDefinition 동기화된 definition
*/
public function syncDefinition(array $data): NotificationDefinition
{
return NotificationDefinition::syncOrCreateFromUpgrade(
['type' => $data['type']],
[
'hook_prefix' => $data['hook_prefix'],
'extension_type' => $data['extension_type'],
'extension_identifier' => $data['extension_identifier'],
'name' => $data['name'],
'description' => $data['description'] ?? null,
'variables' => $data['variables'] ?? [],
'channels' => $data['channels'] ?? ['mail'],
'hooks' => $data['hooks'] ?? [],
'is_active' => $data['is_active'] ?? true,
'is_default' => $data['is_default'] ?? true,
]
);
}
/**
* 알림 템플릿을 동기화합니다 (user_overrides 보존 upsert).
*
* @param int $definitionId 연결된 definition id
* @param array<string, mixed> $data template 데이터 (channel, subject, body,
* click_url, recipients, is_active, is_default)
* @return NotificationTemplate 동기화된 template
*/
public function syncTemplate(int $definitionId, array $data): NotificationTemplate
{
return NotificationTemplate::syncOrCreateFromUpgrade(
['definition_id' => $definitionId, 'channel' => $data['channel']],
[
'subject' => $data['subject'] ?? null,
'body' => $data['body'],
'click_url' => $data['click_url'] ?? null,
'recipients' => $data['recipients'] ?? null,
'is_active' => $data['is_active'] ?? true,
'is_default' => $data['is_default'] ?? true,
]
);
}
/**
* seeder/정의에 없는 stale 알림 정의를 삭제합니다 (완전 동기화 원칙).
*
* 정책: `user_overrides` 무관 — config/seeder 에 없는 정의는 삭제.
* FK cascade 로 연관 `notification_templates` 도 자동 정리됩니다.
*
* @param string $extensionType 확장 타입: 'core', 'module', 'plugin'
* @param string $extensionIdentifier 확장 식별자
* @param array<int, string> $currentTypes 현재 유효한 definition type 목록
* @return int 삭제된 definition 수
*/
public function cleanupStaleDefinitions(
string $extensionType,
string $extensionIdentifier,
array $currentTypes,
): int {
$query = NotificationDefinition::query()
->where('extension_type', $extensionType)
->where('extension_identifier', $extensionIdentifier)
->whereNotIn('type', $currentTypes);
$targets = $query->get(['id', 'type']);
foreach ($targets as $def) {
$def->delete();
}
$count = $targets->count();
if ($count > 0) {
Log::info('stale 알림 정의 정리 완료', [
'extension_type' => $extensionType,
'extension_identifier' => $extensionIdentifier,
'deleted' => $count,
'types' => $targets->pluck('type')->all(),
]);
}
return $count;
}
/**
* 주어진 definition 의 channel 목록 기준으로 stale template 을 삭제합니다.
*
* 정책: `user_overrides` 무관 — seeder 에 없는 (definition_id, channel)
* 조합은 삭제. definition 삭제 시 FK cascade 로 자동 정리되는 경로와 별개로,
* definition 은 유지되지만 channel 이 재구성된 경우에 사용됩니다.
*
* @param int $definitionId
* @param array<int, string> $currentChannels 현재 유효한 channel 목록
* @return int 삭제된 template 수
*/
public function cleanupStaleTemplates(int $definitionId, array $currentChannels): int
{
$query = NotificationTemplate::query()
->where('definition_id', $definitionId)
->whereNotIn('channel', $currentChannels);
$targets = $query->get(['id', 'channel']);
foreach ($targets as $template) {
$template->delete();
}
$count = $targets->count();
if ($count > 0) {
Log::info('stale 알림 템플릿 정리 완료', [
'definition_id' => $definitionId,
'deleted' => $count,
'channels' => $targets->pluck('channel')->all(),
]);
}
return $count;
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Extension;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* 훅 리스너 인자를 큐 직렬화에 안전한 형태로 변환합니다.
*
* Eloquent Model은 클래스명 + PK로 변환하고,
* 큐 워커에서 실행 시 다시 DB에서 조회하여 복원합니다.
*/
class HookArgumentSerializer
{
/**
* Model 직렬화 마커 키
*/
private const MODEL_MARKER = '__hook_model__';
/**
* Collection 직렬화 마커 키
*/
private const COLLECTION_MARKER = '__hook_collection__';
/**
* 인자 배열을 직렬화 안전한 형태로 변환합니다.
*
* @param array $args 원본 인자 배열
* @return array 직렬화된 인자 배열
*/
public static function serialize(array $args): array
{
return array_map([self::class, 'serializeValue'], $args);
}
/**
* 직렬화된 인자 배열을 원본으로 복원합니다.
*
* @param array $args 직렬화된 인자 배열
* @return array 복원된 인자 배열
*/
public static function deserialize(array $args): array
{
return array_map([self::class, 'deserializeValue'], $args);
}
/**
* 단일 값을 직렬화합니다.
*
* @param mixed $value 원본 값
* @return mixed 직렬화된 값
*/
private static function serializeValue(mixed $value): mixed
{
// Eloquent Model → 클래스명 + PK
if ($value instanceof Model) {
return [
self::MODEL_MARKER => true,
'class' => get_class($value),
'id' => $value->getKey(),
];
}
// Collection → 배열로 변환 (내부 요소도 재귀 직렬화)
if ($value instanceof Collection) {
return [
self::COLLECTION_MARKER => true,
'items' => self::serialize($value->all()),
];
}
// 배열 → 재귀 직렬화
if (is_array($value)) {
return array_map([self::class, 'serializeValue'], $value);
}
// 스칼라 값 (string, int, float, bool, null)
if (is_scalar($value) || is_null($value)) {
return $value;
}
// Closure 등 직렬화 불가능한 객체 → null로 대체 + 경고
Log::warning('훅 인자 직렬화 불가: 해당 인자를 null로 대체합니다.', [
'type' => get_debug_type($value),
]);
return null;
}
/**
* 단일 값을 역직렬화합니다.
*
* @param mixed $value 직렬화된 값
* @return mixed 복원된 값
*/
private static function deserializeValue(mixed $value): mixed
{
if (! is_array($value)) {
return $value;
}
// Model 복원
if (! empty($value[self::MODEL_MARKER])) {
$class = $value['class'];
$id = $value['id'];
if (class_exists($class) && is_subclass_of($class, Model::class)) {
return $class::find($id);
}
Log::warning('훅 인자 역직렬화 실패: 모델 클래스를 찾을 수 없습니다.', [
'class' => $class,
'id' => $id,
]);
return null;
}
// Collection 복원
if (! empty($value[self::COLLECTION_MARKER])) {
return collect(self::deserialize($value['items']));
}
// 일반 배열 → 재귀 역직렬화
return array_map([self::class, 'deserializeValue'], $value);
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Extension;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
/**
* 훅 리스너 큐 디스패치 시 요청 컨텍스트 캡처/복원 헬퍼.
*
* 큐 워커는 별도 프로세스이므로 Auth, Request, App 로케일이 모두 리셋된다.
* 디스패치 시점(원래 요청 컨텍스트)에 capture()로 스냅샷을 만들고,
* Job::handle() 진입 시 restore()로 복원하여 리스너가 평소처럼 동작하도록 한다.
*
* 코어 기본 항목: user_id, ip_address, user_agent, locale, path
* 확장점:
* - capture() 마지막에 'hook.context.capture' 필터 발화 (플러그인 키 추가 가능)
* - restore() 진입 직후 'hook.context.restore' 액션 발화 (플러그인 복원 로직)
*/
class HookContextCapture
{
/**
* 현재 요청 컨텍스트를 스냅샷으로 캡처합니다.
*
* dispatch 클로저에서 호출되므로 Auth/Request가 살아있는 상태입니다.
*
* @return array<string, mixed>
*/
public static function capture(): array
{
$request = request();
$context = [
'user_id' => Auth::id(),
'ip_address' => $request?->ip(),
'user_agent' => $request?->userAgent(),
'locale' => App::getLocale(),
'path' => $request?->path(),
];
return HookManager::applyFilters('hook.context.capture', $context);
}
/**
* 캡처된 컨텍스트를 큐 워커 환경에 복원합니다.
*
* Job::handle() 진입 직후 호출됩니다. Job 종료 시 컨테이너가 폐기되므로
* 별도 원복(finally) 처리는 불필요합니다.
*
* @param array<string, mixed> $context
*/
public static function restore(array $context): void
{
// 확장 복원 로직 (코어보다 먼저 실행 — 플러그인이 코어 동작에 영향 주는 컨텍스트 설정 가능)
HookManager::doAction('hook.context.restore', $context);
// 로케일
if (! empty($context['locale'])) {
App::setLocale($context['locale']);
}
// 인증 사용자
// 주의: Sanctum의 RequestGuard는 onceUsingId()를 지원하지 않으므로
// User를 직접 조회하여 setUser()로 주입합니다. (Job 종료 시 컨테이너 폐기되어 자동 해제)
if (! empty($context['user_id'])) {
$user = User::find($context['user_id']);
if ($user !== null) {
Auth::setUser($user);
}
}
// Request 재구성 (IP, User-Agent, Path)
// ResolvesActivityLogType::resolveLogType() 등이 request()->path() / is('api/admin/*') 를
// 큐 워커 컨텍스트에서 호출하기 때문에 path 복원이 필수입니다.
$server = [];
if (! empty($context['ip_address'])) {
$server['REMOTE_ADDR'] = $context['ip_address'];
}
if (! empty($context['user_agent'])) {
$server['HTTP_USER_AGENT'] = $context['user_agent'];
}
if (! empty($context['path'])) {
$server['REQUEST_URI'] = '/'.ltrim($context['path'], '/');
}
if ($server !== []) {
$request = Request::create(
$server['REQUEST_URI'] ?? '/',
'GET',
[],
[],
[],
$server,
);
app()->instance('request', $request);
}
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace App\Extension;
use App\Jobs\DispatchHookListenerJob;
use Illuminate\Support\Facades\Log;
/**
* 훅 리스너를 HookManager에 등록하는 공통 유틸리티
*
* CoreServiceProvider, ModuleManager, PluginManager 3곳의
* 중복된 등록 로직을 통합합니다.
*
* 기본 동작:
* - Action 훅: 큐 드라이버에 따라 자동으로 큐/동기 실행
* - Filter 훅: 항상 동기 실행 (반환값 체인)
* - `'sync' => true` 선언 시: 큐 드라이버 무관하게 동기 실행
*/
class HookListenerRegistrar
{
/**
* 리스너 클래스를 HookManager에 등록합니다.
*
* @param string $listenerClass HookListenerInterface 구현 클래스의 FQCN
* @param string|null $source 등록 출처 (로그용: 'core', 모듈/플러그인 식별자)
* @return void
*/
public static function register(string $listenerClass, ?string $source = null): void
{
try {
$subscribedHooks = $listenerClass::getSubscribedHooks();
} catch (\Throwable $e) {
Log::error('훅 리스너 등록 실패: getSubscribedHooks() 오류', [
'listener' => $listenerClass,
'source' => $source,
'exception' => $e->getMessage(),
]);
return;
}
foreach ($subscribedHooks as $hookName => $config) {
$method = $config['method'] ?? 'handle';
$priority = $config['priority'] ?? 10;
$type = $config['type'] ?? 'action';
$forceSync = ! empty($config['sync']);
if ($type === 'filter') {
// Filter: 항상 동기 실행 (반환값 체인이므로 큐 불가)
HookManager::addFilter($hookName, function ($value, ...$args) use ($listenerClass, $method) {
return app($listenerClass)->{$method}($value, ...$args);
}, $priority);
} elseif ($forceSync) {
// Action + sync: true → 동기 실행 (개발자가 명시적으로 opt-out)
HookManager::addAction($hookName, function (...$args) use ($listenerClass, $method) {
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);
}
Log::info('훅 리스너 등록 완료', [
'hook' => $hookName,
'listener' => $listenerClass,
'method' => $method,
'priority' => $priority,
'type' => $type,
'sync' => $forceSync,
'source' => $source,
]);
}
}
}
+76 -45
View File
@@ -3,24 +3,27 @@
namespace App\Extension;
use App\Contracts\Extension\HookManagerInterface;
use App\Events\GenericBroadcastEvent;
use App\Models\PermissionHook;
use App\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
class HookManager implements HookManagerInterface
{
private static array $hooks = [];
private static array $filters = [];
private static array $dispatching = [];
/**
* Hook 이벤트를 발생시켜 등록된 콜백들을 실행합니다.
*
* @param string $hookName Hook 이름
* @param mixed ...$args Hook에 전달할 인수들
* @return void
* @param string $hookName Hook 이름
* @param mixed ...$args Hook에 전달할 인수들
*/
public static function doAction(string $hookName, ...$args): void
{
@@ -50,9 +53,9 @@ class HookManager implements HookManagerInterface
/**
* Filter를 적용하여 데이터를 변환합니다.
*
* @param string $filterName Filter 이름
* @param mixed $value 변환할 원본 값
* @param mixed ...$args Filter에 전달할 추가 인수들
* @param string $filterName Filter 이름
* @param mixed $value 변환할 원본 값
* @param mixed ...$args Filter에 전달할 추가 인수들
* @return mixed 변환된 값
*/
public static function applyFilters(string $filterName, $value, ...$args)
@@ -60,7 +63,7 @@ class HookManager implements HookManagerInterface
$eventName = "filter.{$filterName}";
// 등록된 필터가 있는지 확인
if (!isset(self::$filters[$filterName])) {
if (! isset(self::$filters[$filterName])) {
return $value;
}
@@ -81,18 +84,17 @@ class HookManager implements HookManagerInterface
/**
* Hook 이벤트에 콜백 함수를 등록합니다.
*
* @param string $hookName Hook 이름
* @param callable $callback 실행할 콜백 함수
* @param int $priority 실행 우선순위 (기본값: 10)
* @return void
* @param string $hookName Hook 이름
* @param callable $callback 실행할 콜백 함수
* @param int $priority 실행 우선순위 (기본값: 10)
*/
public static function addAction(string $hookName, callable $callback, int $priority = 10): void
{
if (!isset(self::$hooks[$hookName])) {
if (! isset(self::$hooks[$hookName])) {
self::$hooks[$hookName] = [];
}
if (!isset(self::$hooks[$hookName][$priority])) {
if (! isset(self::$hooks[$hookName][$priority])) {
self::$hooks[$hookName][$priority] = [];
}
@@ -100,7 +102,7 @@ class HookManager implements HookManagerInterface
// Laravel 이벤트 시스템에도 등록 (가드 래핑으로 doAction 실행 중 중복 방지)
Event::listen("hook.{$hookName}", function (...$args) use ($hookName, $callback) {
if (!empty(self::$dispatching[$hookName])) {
if (! empty(self::$dispatching[$hookName])) {
return; // doAction() 내부 배열에서 이미 실행됨 → 스킵
}
call_user_func_array($callback, $args);
@@ -110,30 +112,63 @@ class HookManager implements HookManagerInterface
/**
* Filter에 콜백 함수를 등록합니다.
*
* @param string $filterName Filter 이름
* @param callable $callback 실행할 콜백 함수
* @param int $priority 실행 우선순위 (기본값: 10)
* @return void
* @param string $filterName Filter 이름
* @param callable $callback 실행할 콜백 함수
* @param int $priority 실행 우선순위 (기본값: 10)
*/
public static function addFilter(string $filterName, callable $callback, int $priority = 10): void
{
if (!isset(self::$filters[$filterName])) {
if (! isset(self::$filters[$filterName])) {
self::$filters[$filterName] = [];
}
if (!isset(self::$filters[$filterName][$priority])) {
if (! isset(self::$filters[$filterName][$priority])) {
self::$filters[$filterName][$priority] = [];
}
self::$filters[$filterName][$priority][] = $callback;
}
/**
* WebSocket 브로드캐스트를 실행합니다.
*
* broadcast(new Event(...)) 직접 호출 대신 이 메서드를 사용합니다.
* 내부적으로 GenericBroadcastEvent를 생성하여 Laravel broadcast()를 실행합니다.
*
* @param string $channel 채널명 (예: 'admin.dashboard', 'user.notifications.123')
* @param string $eventName 이벤트명 (예: 'dashboard.stats.updated', 'notification.received')
* @param array $payload 브로드캐스트 데이터
*/
public static function broadcast(string $channel, string $eventName, array $payload = []): void
{
$driver = config('broadcasting.default');
if (in_array($driver, ['null', 'log', null], true)) {
return;
}
// Reverb/Pusher 드라이버: 호스트 미설정 시 연결 시도 없이 건너뜀
$connection = config("broadcasting.connections.{$driver}");
if (empty($connection['options']['host'] ?? null)) {
return;
}
try {
broadcast(new GenericBroadcastEvent($channel, $eventName, $payload));
} catch (\Throwable $e) {
Log::warning('브로드캐스트 실패 (Reverb 미실행 가능)', [
'channel' => $channel,
'event' => $eventName,
'error' => $e->getMessage(),
]);
}
}
/**
* Hook 이벤트에서 콜백 함수를 제거합니다.
*
* @param string $hookName Hook 이름
* @param callable $callback 제거할 콜백 함수
* @return void
* @param string $hookName Hook 이름
* @param callable $callback 제거할 콜백 함수
*/
public static function removeAction(string $hookName, callable $callback): void
{
@@ -153,9 +188,8 @@ class HookManager implements HookManagerInterface
/**
* Filter에서 콜백 함수를 제거합니다.
*
* @param string $filterName Filter 이름
* @param callable $callback 제거할 콜백 함수
* @return void
* @param string $filterName Filter 이름
* @param callable $callback 제거할 콜백 함수
*/
public static function removeFilter(string $filterName, callable $callback): void
{
@@ -192,8 +226,7 @@ class HookManager implements HookManagerInterface
/**
* 특정 Hook에 등록된 모든 콜백을 제거합니다.
*
* @param string $hookName Hook 이름
* @return void
* @param string $hookName Hook 이름
*/
public static function clearAction(string $hookName): void
{
@@ -208,8 +241,7 @@ class HookManager implements HookManagerInterface
/**
* 특정 Filter에 등록된 모든 콜백을 제거합니다.
*
* @param string $filterName Filter 이름
* @return void
* @param string $filterName Filter 이름
*/
public static function clearFilter(string $filterName): void
{
@@ -222,8 +254,6 @@ class HookManager implements HookManagerInterface
* 테스트 환경에서 등록된 모든 Hook과 Filter를 초기화합니다.
*
* 주의: 이 메서드는 테스트 환경에서만 사용해야 합니다.
*
* @return void
*/
public static function resetAll(): void
{
@@ -238,15 +268,15 @@ class HookManager implements HookManagerInterface
* permission_hooks 테이블에 해당 훅이 매핑되어 있으면
* 현재 사용자가 해당 권한을 보유하고 있는지 확인합니다.
*
* @param string $hookName 훅 이름
* @param User|null $user 사용자 (null이면 현재 인증된 사용자)
* @return void
* @param string $hookName 훅 이름
* @param User|null $user 사용자 (null이면 현재 인증된 사용자)
*
* @throws AuthorizationException 권한이 없는 경우
*/
public static function checkHookPermission(string $hookName, ?User $user = null): void
{
// 훅에 권한 매핑이 없으면 모든 사용자 허용
if (!PermissionHook::hasPermissionMapping($hookName)) {
if (! PermissionHook::hasPermissionMapping($hookName)) {
return;
}
@@ -254,7 +284,7 @@ class HookManager implements HookManagerInterface
$user = $user ?? Auth::user();
// 비인증 사용자는 권한 매핑된 훅 접근 불가
if (!$user) {
if (! $user) {
throw new AuthorizationException(__('auth.unauthorized'));
}
@@ -278,10 +308,10 @@ class HookManager implements HookManagerInterface
/**
* 훅 실행 전 권한 체크 후 Action 실행
*
* @param string $hookName 훅 이름
* @param User|null $user 권한 체크 대상 사용자
* @param mixed ...$args 훅에 전달할 인자
* @return void
* @param string $hookName 훅 이름
* @param User|null $user 권한 체크 대상 사용자
* @param mixed ...$args 훅에 전달할 인자
*
* @throws AuthorizationException 권한이 없는 경우
*/
public static function doActionWithPermission(string $hookName, ?User $user = null, ...$args): void
@@ -293,11 +323,12 @@ class HookManager implements HookManagerInterface
/**
* 훅 실행 전 권한 체크 후 Filter 실행
*
* @param string $hookName 훅 이름
* @param User|null $user 권한 체크 대상 사용자
* @param mixed $value 필터링할 값
* @param mixed ...$args 필터에 전달할 추가 인자
* @param string $hookName 훅 이름
* @param User|null $user 권한 체크 대상 사용자
* @param mixed $value 필터링할 값
* @param mixed ...$args 필터에 전달할 추가 인자
* @return mixed 필터링된 값
*
* @throws AuthorizationException 권한이 없는 경우
*/
public static function applyFiltersWithPermission(string $hookName, ?User $user = null, mixed $value = null, ...$args): mixed
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+188 -99
View File
@@ -18,7 +18,8 @@ use App\Services\LayoutService;
use App\Services\TemplateService;
use Composer\Semver\Semver;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
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;
@@ -32,6 +33,7 @@ class TemplateManager implements TemplateManagerInterface
{
use Traits\CachesTemplateStatus;
use Traits\ClearsTemplateCaches;
use Traits\ComputesLayoutContentHash;
use Traits\InspectsUninstallData;
use Traits\InvalidatesLayoutCache;
use Traits\ValidatesLayoutFiles;
@@ -80,6 +82,18 @@ class TemplateManager implements TemplateManagerInterface
$this->bundledTemplatesPath = $this->templatesPath.DIRECTORY_SEPARATOR.'_bundled';
}
/**
* 코어 캐시 드라이버를 lazy 조회합니다.
*/
private function cache(): CacheInterface
{
try {
return app(CacheInterface::class);
} catch (\Throwable $e) {
return new CoreCacheDriver(config('cache.default', 'array'));
}
}
/**
* 모든 템플릿을 로드하고 초기화합니다.
*/
@@ -111,6 +125,15 @@ class TemplateManager implements TemplateManagerInterface
continue;
}
// 무결성 검사: 활성 디렉토리는 있으나 template.json 누락 감지
if (! File::exists($templateFile)) {
Log::warning('템플릿 활성 디렉토리가 불완전합니다 (template.json 누락)', [
'template' => $templateName,
'directory' => $directory,
'hint' => "복구: php artisan template:install {$templateName} --force",
]);
}
if (File::exists($templateFile)) {
try {
$jsonContent = File::get($templateFile);
@@ -355,7 +378,7 @@ class TemplateManager implements TemplateManagerInterface
*
* @throws \Exception 템플릿을 찾을 수 없거나 의존성 문제 시
*/
public function installTemplate(string $templateName, ?\Closure $onProgress = null): bool
public function installTemplate(string $templateName, ?\Closure $onProgress = null, bool $force = false): bool
{
// identifier 형식 검증 (내부 호출 방어)
ExtensionManager::validateIdentifierFormat($templateName);
@@ -370,9 +393,10 @@ class TemplateManager implements TemplateManagerInterface
}
// 1. _pending/_bundled에서 활성 디렉토리로 복사 (활성 디렉토리에 없는 경우)
// force=true 시 활성 디렉토리가 있어도 원본으로 덮어씀 (불완전 설치 복구)
$onProgress?->__invoke('copy', '파일 복사 중...');
if (! isset($this->templates[$templateName])) {
$this->copyToActiveFromSource($templateName, $onProgress);
if ($force || ! isset($this->templates[$templateName])) {
$this->copyToActiveFromSource($templateName, $onProgress, $force);
}
// 2. 검증
@@ -900,6 +924,7 @@ class TemplateManager implements TemplateManagerInterface
'description' => $this->getLocalizedValue($template['description'] ?? '', $locale),
'github_url' => $template['github_url'] ?? null,
'github_changelog_url' => $template['github_changelog_url'] ?? null,
'requires_core' => $template['g7_version'] ?? null,
'dependencies' => $template['dependencies'] ?? [],
'locales' => $template['locales'] ?? [],
'layouts_count' => $layoutsCount,
@@ -946,6 +971,7 @@ class TemplateManager implements TemplateManagerInterface
'description' => $this->getLocalizedValue($description, $locale),
'github_url' => $metadata['github_url'] ?? null,
'github_changelog_url' => $metadata['github_changelog_url'] ?? null,
'requires_core' => $metadata['g7_version'] ?? null,
'dependencies' => $metadata['dependencies'] ?? [],
'locales' => $metadata['locales'] ?? [],
'layouts_count' => 0,
@@ -1579,11 +1605,11 @@ class TemplateManager implements TemplateManagerInterface
if (! in_array($override->name, $registeredLayoutNames)) {
// 캐시 삭제 (레코드 삭제 전에 수행)
$cacheKey = "template.{$templateId}.layout.{$override->name}";
Cache::forget($cacheKey);
$this->cache()->forget($cacheKey);
$sourceHash = md5($override->source_type?->value.$override->source_identifier);
$cacheKeyWithHash = "template.{$templateId}.layout.{$override->name}.{$sourceHash}";
Cache::forget($cacheKeyWithHash);
$this->cache()->forget($cacheKeyWithHash);
$override->forceDelete();
$deletedCount++;
@@ -1632,12 +1658,12 @@ class TemplateManager implements TemplateManagerInterface
foreach ($overrideLayouts as $layout) {
// 기본 캐시 키 패턴으로 삭제
$cacheKey = "template.{$templateId}.layout.{$layout->name}";
Cache::forget($cacheKey);
$this->cache()->forget($cacheKey);
// sourceHash를 포함한 캐시 키도 삭제 (LayoutService의 캐시 키 패턴)
$sourceHash = md5($layout->source_type?->value.$layout->source_identifier);
$cacheKeyWithHash = "template.{$templateId}.layout.{$layout->name}.{$sourceHash}";
Cache::forget($cacheKeyWithHash);
$this->cache()->forget($cacheKeyWithHash);
}
Log::info(__('templates.info.override_layouts_cache_invalidated'), [
@@ -1754,9 +1780,9 @@ class TemplateManager implements TemplateManagerInterface
// PublicLayoutController::serve()와 동일한 캐시 키 패턴 사용
$cacheKey = "layout.{$templateIdentifier}.{$layoutName}.v{$cacheVersion}";
Cache::remember($cacheKey, $cacheTtl, function () use ($templateIdentifier, $layoutName, $layoutService) {
$this->cache()->remember($cacheKey, function () use ($templateIdentifier, $layoutName, $layoutService) {
return $layoutService->getLayout($templateIdentifier, $layoutName);
});
}, $cacheTtl);
Log::debug('레이아웃 캐시 워밍 완료', [
'template' => $templateIdentifier,
@@ -1780,7 +1806,7 @@ class TemplateManager implements TemplateManagerInterface
if ($result['success']) {
$cacheKey = "template.routes.{$templateIdentifier}.v{$cacheVersion}";
Cache::put($cacheKey, ['success' => true, 'data' => $result['data']], $cacheTtl);
$this->cache()->put($cacheKey, ['success' => true, 'data' => $result['data']], $cacheTtl);
}
} catch (\Exception $e) {
Log::debug('Routes 캐시 워밍 실패', [
@@ -1797,7 +1823,7 @@ class TemplateManager implements TemplateManagerInterface
$langFilePath = base_path("templates/{$templateIdentifier}/lang/{$locale}.json");
if (file_exists($langFilePath)) {
$cacheKey = "template.language.{$templateIdentifier}.{$locale}.v{$cacheVersion}";
Cache::remember($cacheKey, $cacheTtl, function () use ($templateIdentifier, $locale, $templateService) {
$this->cache()->remember($cacheKey, function () use ($templateIdentifier, $locale, $templateService) {
// TemplateService를 통해 $partial 해석 + 모듈/플러그인 다국어 병합
$result = $templateService->getLanguageDataWithModules($templateIdentifier, $locale);
@@ -1806,7 +1832,7 @@ class TemplateManager implements TemplateManagerInterface
}
return ['success' => true, 'data' => $result['data']];
});
}, $cacheTtl);
}
} catch (\Exception $e) {
Log::debug('다국어 파일 캐시 워밍 실패', [
@@ -2346,39 +2372,16 @@ class TemplateManager implements TemplateManagerInterface
}
try {
if (! preg_match('#github\.com[/:]([^/]+)/([^/\.]+)#', $githubUrl, $matches)) {
return null;
}
$owner = $matches[1];
$repo = $matches[2];
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}/releases/latest";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => GithubHelper::buildHeaders(config('app.update.github_token') ?? ''),
'timeout' => 5,
],
]);
$response = @file_get_contents($apiUrl, false, $context);
if ($response === false) {
Log::warning("GitHub API 호출 실패: {$apiUrl}");
return null;
}
$data = json_decode($response, true);
if (isset($data['tag_name'])) {
return ltrim($data['tag_name'], 'v');
}
[$owner, $repo] = GithubHelper::parseUrl($githubUrl);
} catch (\RuntimeException $e) {
return null;
}
try {
$token = (string) (config('app.update.github_token') ?? '');
$result = GithubHelper::fetchLatestRelease($owner, $repo, $token);
return $result['version'];
} catch (\Exception $e) {
Log::error('최신 버전 확인 중 오류 발생', [
'github_url' => $githubUrl,
@@ -2415,7 +2418,7 @@ class TemplateManager implements TemplateManagerInterface
*
* @throws \RuntimeException 소스를 찾을 수 없을 때
*/
protected function copyToActiveFromSource(string $templateName, ?\Closure $onProgress = null): void
protected function copyToActiveFromSource(string $templateName, ?\Closure $onProgress = null, bool $force = false): void
{
$targetPath = $this->templatesPath.DIRECTORY_SEPARATOR.$templateName;
@@ -2423,6 +2426,7 @@ class TemplateManager implements TemplateManagerInterface
if (isset($this->pendingTemplates[$templateName]) || ExtensionPendingHelper::isPending($this->templatesPath, $templateName)) {
$sourcePath = ExtensionPendingHelper::getPendingPath($this->templatesPath, $templateName);
ExtensionPendingHelper::copyToActive($sourcePath, $targetPath, $onProgress);
Log::info('템플릿을 _pending에서 활성 디렉토리로 복사', ['template' => $templateName, 'force' => $force]);
// 메모리 재로드
$this->reloadTemplate($templateName);
@@ -2434,6 +2438,7 @@ class TemplateManager implements TemplateManagerInterface
if (isset($this->bundledTemplates[$templateName]) || ExtensionPendingHelper::isBundled($this->templatesPath, $templateName)) {
$sourcePath = ExtensionPendingHelper::getBundledPath($this->templatesPath, $templateName);
ExtensionPendingHelper::copyToActive($sourcePath, $targetPath, $onProgress);
Log::info('템플릿을 _bundled에서 활성 디렉토리로 복사', ['template' => $templateName, 'force' => $force]);
// 메모리 재로드
$this->reloadTemplate($templateName);
@@ -2503,7 +2508,15 @@ class TemplateManager implements TemplateManagerInterface
/**
* 단일 템플릿의 업데이트 가능 여부를 확인합니다.
*
* 우선순위: GitHub → _pending → _bundled
* 일반 업데이트 우선순위 (GitHub 엄격 우선):
* 1. GitHub URL 존재 + API 조회 성공 → GitHub 결과만 신뢰
* a. GitHub 버전 > 현재 → 'github' 소스 반환
* b. GitHub 버전 ≤ 현재 → "업데이트 없음" 즉시 반환 (bundled 폴백 없음)
* 2. GitHub URL 없음 OR API 조회 실패 → _bundled 폴백 (안전망)
*
* --force 업데이트 우선순위는 resolveForceUpdateSource() 참조 (번들 우선).
*
* 참고: _pending 디렉토리는 install 경로에서만 사용되며 update 에서는 참조하지 않음.
*
* @param string $identifier 템플릿 식별자
* @return array{update_available: bool, update_source: string|null, latest_version: string|null, current_version: string|null}
@@ -2523,21 +2536,46 @@ class TemplateManager implements TemplateManagerInterface
$currentVersion = $record->version;
$template = $this->getTemplate($identifier);
// 1. GitHub URL이 있으면 GitHub에서 최신 버전 확인
// 1. GitHub URL이 있으면 GitHub에서 최신 버전 확인 (조회 성공 시 GitHub만 신뢰)
$githubUrl = $template['github_url'] ?? ($record->github_url ?? null);
if ($githubUrl) {
$latestVersion = $this->fetchLatestVersion($githubUrl);
if ($latestVersion && version_compare($latestVersion, $currentVersion, '>')) {
try {
$latestVersion = $this->fetchLatestVersion($githubUrl);
} catch (\Throwable $e) {
Log::warning('템플릿 GitHub 버전 조회 실패', [
'template' => $identifier,
'url' => $githubUrl,
'error' => $e->getMessage(),
]);
$latestVersion = null;
}
if ($latestVersion !== null) {
// GitHub 조회 성공 → GitHub 결과만 신뢰 (bundled 폴백 없음)
if (version_compare($latestVersion, $currentVersion, '>')) {
return [
'update_available' => true,
'update_source' => 'github',
'latest_version' => $latestVersion,
'current_version' => $currentVersion,
];
}
return [
'update_available' => true,
'update_source' => 'github',
'latest_version' => $latestVersion,
'update_available' => false,
'update_source' => null,
'latest_version' => $currentVersion,
'current_version' => $currentVersion,
];
}
// GitHub 조회 실패 → _bundled 폴백 안내
Log::info('템플릿 업데이트 확인: GitHub 조회 실패로 bundled 폴백', [
'template' => $identifier,
]);
}
// 2. _bundled에서 업데이트 확인
// 2. _bundled에서 업데이트 확인 (GitHub URL 없음 OR GitHub 조회 실패)
if (isset($this->bundledTemplates[$identifier])) {
$bundledVersion = $this->bundledTemplates[$identifier]['version'] ?? null;
if ($bundledVersion && version_compare($bundledVersion, $currentVersion, '>')) {
@@ -2682,43 +2720,6 @@ class TemplateManager implements TemplateManagerInterface
}
}
/**
* 레이아웃 콘텐츠의 정규화된 SHA-256 해시를 계산합니다.
*
* 배열/JSON 문자열 모두 동일한 결과를 반환합니다.
*
* @param array|string $content 레이아웃 콘텐츠 (배열 또는 JSON 문자열)
* @return string SHA-256 해시
*/
private function computeContentHash(array|string $content): string
{
return hash('sha256', $this->normalizeContent($content));
}
/**
* 레이아웃 콘텐츠의 정규화된 바이트 크기를 계산합니다.
*
* @param array|string $content 레이아웃 콘텐츠 (배열 또는 JSON 문자열)
* @return int 바이트 크기
*/
private function computeContentSize(array|string $content): int
{
return strlen($this->normalizeContent($content));
}
/**
* 콘텐츠를 정규화된 JSON 문자열로 변환합니다.
*
* @param array|string $content 레이아웃 콘텐츠 (배열 또는 JSON 문자열)
* @return string 정규화된 JSON 문자열
*/
private function normalizeContent(array|string $content): string
{
return is_string($content)
? json_encode(json_decode($content, true), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
: json_encode($content, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/**
* 사용자가 수정한 레이아웃이 있는지 확인합니다.
*
@@ -2779,15 +2780,19 @@ class TemplateManager implements TemplateManagerInterface
* 프로세스: 백업 → updating 상태 → 파일 교체 → DB 갱신 →
* 레이아웃 갱신 → 상태 복원 → 백업 삭제
*
* 파라미터 순서는 updateModule / updatePlugin 과 일치시켜 공통 prefix
* (id, force, onProgress, ...) 를 공유한다. 템플릿은 upgrade step 이 없어
* vendorMode / onUpgradeStep 은 없음.
*
* @param string $identifier 템플릿 식별자
* @param string $layoutStrategy 레이아웃 전략 ('overwrite' 또는 'keep')
* @param bool $force 버전 비교 없이 강제 업데이트
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
* @param string $layoutStrategy 레이아웃 전략 ('overwrite' 또는 'keep')
* @return array{success: bool, from_version: string|null, to_version: string|null, message: string}
*
* @throws \RuntimeException 업데이트 실패 시
*/
public function updateTemplate(string $identifier, string $layoutStrategy = 'overwrite', bool $force = false, ?\Closure $onProgress = null): array
public function updateTemplate(string $identifier, bool $force = false, ?\Closure $onProgress = null, string $layoutStrategy = 'overwrite', ?string $sourceOverride = null, ?string $zipPath = null): array
{
$record = $this->templateRepository->findByIdentifier($identifier);
if (! $record) {
@@ -2804,19 +2809,62 @@ class TemplateManager implements TemplateManagerInterface
$fromVersion = $record->version;
$updateInfo = $this->checkTemplateUpdate($identifier);
if (! $updateInfo['update_available'] && ! $force) {
// ZIP 강제 경로: 외부 ZIP 파일을 직접 추출하여 사용. checkTemplateUpdate 결과는 무시.
// zipTempDir / zipExtractedDir 는 staging 단계에서 사용 후 finally 에서 정리.
$zipTempDir = null;
$zipExtractedDir = null;
if ($zipPath !== null) {
$prepared = $this->extensionManager->prepareZipSource($zipPath, $identifier, 'template.json');
$zipTempDir = $prepared['temp_dir'];
$zipExtractedDir = $prepared['extracted_dir'];
$updateSource = 'zip';
$toVersion = $prepared['to_version'];
}
// 번들 강제 경로: 코어 업그레이드 / 일괄 업데이트 컨텍스트에서 GitHub 상태와 무관하게
// _bundled manifest 버전을 강제 사용.
elseif ($sourceOverride === 'bundled') {
$bundled = $this->getBundledVersion($identifier);
if ($bundled === null) {
throw new \RuntimeException(
__('templates.errors.force_update_no_source', ['template' => $identifier])
);
}
$updateSource = 'bundled';
$toVersion = $bundled;
} elseif ($sourceOverride === 'github') {
// GitHub 강제 경로: _bundled 폴백 없이 GitHub 만 시도.
$template = $this->getTemplate($identifier);
$githubUrl = $template['github_url'] ?? ($record->github_url ?? null);
if (empty($githubUrl)) {
throw new \RuntimeException(
__('templates.errors.force_update_no_source', ['template' => $identifier])
);
}
$updateSource = 'github';
$toVersion = ($updateInfo['update_source'] === 'github' ? $updateInfo['latest_version'] : null)
?? $updateInfo['current_version'];
} elseif (! $updateInfo['update_available'] && ! $force) {
return [
'success' => false,
'from_version' => $fromVersion,
'to_version' => $fromVersion,
'message' => __('templates.no_update_available'),
];
}
// force 시 버전/소스 결정
if ($force && ! $updateInfo['update_available']) {
$toVersion = $updateInfo['current_version'];
} elseif ($force && ! $updateInfo['update_available']) {
$updateSource = $this->resolveForceUpdateSource($identifier);
if ($updateSource === null) {
throw new \RuntimeException(
__('templates.errors.force_update_no_source', ['template' => $identifier])
);
}
// 번들 재설치는 번들 manifest 버전 기준, github 재설치는 현재 버전 기준
if ($updateSource === 'bundled') {
$toVersion = $this->getBundledVersion($identifier) ?? $updateInfo['current_version'];
} else {
$toVersion = $updateInfo['current_version'];
}
} else {
$toVersion = $updateInfo['latest_version'];
$updateSource = $updateInfo['update_source'];
@@ -2848,6 +2896,9 @@ class TemplateManager implements TemplateManagerInterface
$sourcePath = ExtensionPendingHelper::getBundledPath($this->templatesPath, $identifier);
$stagingPath = ExtensionPendingHelper::createUpdateStagingPath($this->templatesPath, $identifier);
ExtensionPendingHelper::stageForUpdate($sourcePath, $stagingPath, $onProgress);
} elseif ($updateSource === 'zip') {
$stagingPath = ExtensionPendingHelper::createUpdateStagingPath($this->templatesPath, $identifier);
ExtensionPendingHelper::stageForUpdate($zipExtractedDir, $stagingPath, $onProgress);
}
// 4. 원자적 적용 (스테이징 → 활성 디렉토리)
@@ -2861,6 +2912,10 @@ class TemplateManager implements TemplateManagerInterface
if ($stagingPath) {
ExtensionPendingHelper::cleanupStaging($stagingPath);
}
// ZIP 임시 추출 디렉토리 정리
if ($zipTempDir && File::isDirectory($zipTempDir)) {
File::deleteDirectory($zipTempDir);
}
}
// 템플릿 재로드 (새 파일로)
@@ -2987,8 +3042,17 @@ class TemplateManager implements TemplateManagerInterface
/**
* --force 시 업데이트 소스를 결정합니다.
*
* PO 정책: --force 시에는 번들이 우선, 번들이 없는 경우에만 GitHub 사용.
* (일반 업데이트의 GitHub 우선과 반대 — 개발자가 로컬 번들로 되돌리려는 의도 존중)
*
* 우선순위:
* 1. _bundled (메모리 캐시) → 'bundled'
* 2. _bundled (디스크 재조회) → 'bundled'
* 3. GitHub URL 존재 → 'github'
* 4. 둘 다 없음 → null (업데이트 불가)
*
* @param string $identifier 템플릿 식별자
* @return string|null 업데이트 소스 ('bundled' 또는 null)
* @return string|null 'bundled' | 'github' | null
*/
private function resolveForceUpdateSource(string $identifier): ?string
{
@@ -3001,6 +3065,31 @@ class TemplateManager implements TemplateManagerInterface
return 'bundled';
}
// 번들 없음 → GitHub URL 확인
$template = $this->getTemplate($identifier);
$record = $this->templateRepository->findByIdentifier($identifier);
$githubUrl = ($template['github_url'] ?? null) ?: ($record->github_url ?? null);
if ($githubUrl) {
return 'github';
}
return null;
}
/**
* _bundled 에 등록된 템플릿의 버전을 반환합니다 (force 업데이트용).
*
* @param string $identifier 템플릿 식별자
* @return string|null 버전 문자열 또는 null
*/
private function getBundledVersion(string $identifier): ?string
{
if (isset($this->bundledTemplates[$identifier]['version'])) {
return $this->bundledTemplates[$identifier]['version'];
}
$meta = ExtensionPendingHelper::loadBundledExtensions($this->templatesPath, 'template.json');
return $meta[$identifier]['version'] ?? null;
}
}
@@ -0,0 +1,94 @@
<?php
namespace App\Extension\Traits;
use App\Contracts\Extension\CacheInterface;
use Illuminate\Support\Facades\Log;
/**
* 캐시 자동 무효화 트레이트
*
* 모델에 적용하면 saved/deleted 이벤트 시 관련 태그 캐시를 자동 무효화합니다.
*
* 사용 예:
* ```php
* class Product extends Model
* {
* use CacheInvalidatable;
*
* protected function getCacheInvalidationTags(): array
* {
* return ['products', 'product:' . $this->id];
* }
*
* protected function getCacheDriver(): ?CacheInterface
* {
* return app(ModuleManager::class)
* ->getModule('sirsoft-ecommerce')?->getCache();
* }
* }
* ```
*
* @since engine-v1.18.0
*/
trait CacheInvalidatable
{
/**
* 트레이트 부트 메서드
*
* saved/deleted 이벤트에 캐시 무효화 로직을 등록합니다.
*
* @return void
*/
public static function bootCacheInvalidatable(): void
{
static::saved(fn ($model) => $model->invalidateRelatedCache());
static::deleted(fn ($model) => $model->invalidateRelatedCache());
}
/**
* 무효화할 캐시 태그를 반환합니다.
*
* 모델에서 구현해야 합니다.
*
* @return array 태그 배열
*/
abstract protected function getCacheInvalidationTags(): array;
/**
* 사용할 CacheInterface를 반환합니다.
*
* 모델에서 구현해야 합니다. null을 반환하면 무효화를 건너뜁니다.
*
* @return CacheInterface|null 캐시 드라이버 인스턴스
*/
abstract protected function getCacheDriver(): ?CacheInterface;
/**
* 관련 캐시를 무효화합니다.
*
* @return void
*/
protected function invalidateRelatedCache(): void
{
$cache = $this->getCacheDriver();
if ($cache === null) {
return;
}
$tags = $this->getCacheInvalidationTags();
if (empty($tags)) {
return;
}
try {
$cache->flushTags($tags);
} catch (\Exception $e) {
Log::warning('캐시 자동 무효화 실패', [
'model' => static::class,
'tags' => $tags,
'error' => $e->getMessage(),
]);
}
}
}
+57 -20
View File
@@ -2,9 +2,12 @@
namespace App\Extension\Traits;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Extension\Cache\CoreCacheDriver;
use App\Models\Module;
use App\Services\CacheService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* 모듈 상태 캐시를 관리하는 Trait
@@ -14,11 +17,6 @@ use App\Services\CacheService;
*/
trait CachesModuleStatus
{
/**
* 캐시 그룹
*/
private static string $cacheGroup = 'modules';
/**
* 활성화된 모듈 identifier 목록을 조회합니다.
*
@@ -26,14 +24,17 @@ trait CachesModuleStatus
*/
public static function getActiveModuleIdentifiers(): array
{
return CacheService::remember(
self::$cacheGroup,
'active_identifiers',
if (! self::isExtensionTableReady('modules')) {
return [];
}
return self::resolveStatusCache()->remember(
'ext.modules.active_identifiers',
fn () => Module::where('status', ExtensionStatus::Active->value)
->pluck('identifier')
->toArray(),
null,
'modules'
(int) g7_core_settings('cache.extension_status_ttl', 86400),
['ext.status', 'ext.modules']
);
}
@@ -44,15 +45,18 @@ trait CachesModuleStatus
*/
public static function getInstalledModuleIdentifiers(): array
{
return CacheService::remember(
self::$cacheGroup,
'installed_identifiers',
if (! self::isExtensionTableReady('modules')) {
return [];
}
return self::resolveStatusCache()->remember(
'ext.modules.installed_identifiers',
fn () => Module::whereIn('status', [
ExtensionStatus::Active->value,
ExtensionStatus::Inactive->value,
])->pluck('identifier')->toArray(),
null,
'modules'
(int) g7_core_settings('cache.extension_status_ttl', 86400),
['ext.status', 'ext.modules']
);
}
@@ -64,9 +68,42 @@ trait CachesModuleStatus
*/
public static function invalidateModuleStatusCache(): void
{
CacheService::forgetMany(self::$cacheGroup, [
'active_identifiers',
'installed_identifiers',
]);
$cache = self::resolveStatusCache();
$cache->forget('ext.modules.active_identifiers');
$cache->forget('ext.modules.installed_identifiers');
}
/**
* DB 연결 + 테이블 존재 여부를 확인합니다 (인스톨러 안전성).
*
* 설치 완료 상태(`config('app.installer_completed')`)일 때는 테이블 존재를
* 전제로 하여 `Schema::hasTable()` 호출을 건너뜁니다. 인스톨러 이전 환경이나
* 테스트에서는 기존 체크 경로로 폴백합니다.
*/
private static function isExtensionTableReady(string $table): bool
{
if (config('app.installer_completed')) {
return true;
}
try {
DB::connection()->getPdo();
return Schema::hasTable($table);
} catch (\Throwable $e) {
return false;
}
}
/**
* CacheInterface 인스턴스를 lazy 조회합니다 (register 시점 안전).
*/
private static function resolveStatusCache(): CacheInterface
{
try {
return app(CacheInterface::class);
} catch (\Throwable $e) {
return new CoreCacheDriver(config('cache.default', 'array'));
}
}
}
+51 -20
View File
@@ -2,9 +2,12 @@
namespace App\Extension\Traits;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Extension\Cache\CoreCacheDriver;
use App\Models\Plugin;
use App\Services\CacheService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* 플러그인 상태 캐시를 관리하는 Trait
@@ -14,11 +17,6 @@ use App\Services\CacheService;
*/
trait CachesPluginStatus
{
/**
* 캐시 그룹
*/
private static string $pluginCacheGroup = 'plugins';
/**
* 활성화된 플러그인 identifier 목록을 조회합니다.
*
@@ -26,14 +24,17 @@ trait CachesPluginStatus
*/
public static function getActivePluginIdentifiers(): array
{
return CacheService::remember(
self::$pluginCacheGroup,
'active_identifiers',
if (! self::isPluginTableReady()) {
return [];
}
return self::resolvePluginStatusCache()->remember(
'ext.plugins.active_identifiers',
fn () => Plugin::where('status', ExtensionStatus::Active->value)
->pluck('identifier')
->toArray(),
null,
'plugins'
(int) g7_core_settings('cache.extension_status_ttl', 86400),
['ext.status', 'ext.plugins']
);
}
@@ -44,15 +45,18 @@ trait CachesPluginStatus
*/
public static function getInstalledPluginIdentifiers(): array
{
return CacheService::remember(
self::$pluginCacheGroup,
'installed_identifiers',
if (! self::isPluginTableReady()) {
return [];
}
return self::resolvePluginStatusCache()->remember(
'ext.plugins.installed_identifiers',
fn () => Plugin::whereIn('status', [
ExtensionStatus::Active->value,
ExtensionStatus::Inactive->value,
])->pluck('identifier')->toArray(),
null,
'plugins'
(int) g7_core_settings('cache.extension_status_ttl', 86400),
['ext.status', 'ext.plugins']
);
}
@@ -64,9 +68,36 @@ trait CachesPluginStatus
*/
public static function invalidatePluginStatusCache(): void
{
CacheService::forgetMany(self::$pluginCacheGroup, [
'active_identifiers',
'installed_identifiers',
]);
$cache = self::resolvePluginStatusCache();
$cache->forget('ext.plugins.active_identifiers');
$cache->forget('ext.plugins.installed_identifiers');
}
/**
* 설치 완료 상태에서는 `Schema::hasTable()` 호출을 건너뜁니다.
* 인스톨러 이전 환경이나 테스트에서는 기존 체크 경로로 폴백합니다.
*/
private static function isPluginTableReady(): bool
{
if (config('app.installer_completed')) {
return true;
}
try {
DB::connection()->getPdo();
return Schema::hasTable('plugins');
} catch (\Throwable $e) {
return false;
}
}
private static function resolvePluginStatusCache(): CacheInterface
{
try {
return app(CacheInterface::class);
} catch (\Throwable $e) {
return new CoreCacheDriver(config('cache.default', 'array'));
}
}
}
+61 -27
View File
@@ -2,9 +2,12 @@
namespace App\Extension\Traits;
use App\Contracts\Extension\CacheInterface;
use App\Enums\ExtensionStatus;
use App\Extension\Cache\CoreCacheDriver;
use App\Models\Template;
use App\Services\CacheService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* 템플릿 상태 캐시를 관리하는 Trait
@@ -14,11 +17,6 @@ use App\Services\CacheService;
*/
trait CachesTemplateStatus
{
/**
* 캐시 그룹
*/
private static string $templateCacheGroup = 'templates';
/**
* 활성화된 템플릿 identifier 목록을 조회합니다.
*
@@ -26,14 +24,17 @@ trait CachesTemplateStatus
*/
public static function getActiveTemplateIdentifiers(): array
{
return CacheService::remember(
self::$templateCacheGroup,
'active_identifiers',
if (! self::isTemplateTableReady()) {
return [];
}
return self::resolveTemplateStatusCache()->remember(
'ext.templates.active_identifiers',
fn () => Template::where('status', ExtensionStatus::Active->value)
->pluck('identifier')
->toArray(),
null,
'templates'
(int) g7_core_settings('cache.extension_status_ttl', 86400),
['ext.status', 'ext.templates']
);
}
@@ -45,15 +46,18 @@ trait CachesTemplateStatus
*/
public static function getActiveTemplateIdentifiersByType(string $type): array
{
return CacheService::remember(
self::$templateCacheGroup,
"active_identifiers_{$type}",
if (! self::isTemplateTableReady()) {
return [];
}
return self::resolveTemplateStatusCache()->remember(
"ext.templates.active_identifiers_{$type}",
fn () => Template::where('status', ExtensionStatus::Active->value)
->where('type', $type)
->pluck('identifier')
->toArray(),
null,
'templates'
(int) g7_core_settings('cache.extension_status_ttl', 86400),
['ext.status', 'ext.templates']
);
}
@@ -64,15 +68,18 @@ trait CachesTemplateStatus
*/
public static function getInstalledTemplateIdentifiers(): array
{
return CacheService::remember(
self::$templateCacheGroup,
'installed_identifiers',
if (! self::isTemplateTableReady()) {
return [];
}
return self::resolveTemplateStatusCache()->remember(
'ext.templates.installed_identifiers',
fn () => Template::whereIn('status', [
ExtensionStatus::Active->value,
ExtensionStatus::Inactive->value,
])->pluck('identifier')->toArray(),
null,
'templates'
(int) g7_core_settings('cache.extension_status_ttl', 86400),
['ext.status', 'ext.templates']
);
}
@@ -84,11 +91,38 @@ trait CachesTemplateStatus
*/
public static function invalidateTemplateStatusCache(): void
{
CacheService::forgetMany(self::$templateCacheGroup, [
'active_identifiers',
'active_identifiers_admin',
'active_identifiers_user',
'installed_identifiers',
]);
$cache = self::resolveTemplateStatusCache();
$cache->forget('ext.templates.active_identifiers');
$cache->forget('ext.templates.active_identifiers_admin');
$cache->forget('ext.templates.active_identifiers_user');
$cache->forget('ext.templates.installed_identifiers');
}
/**
* 설치 완료 상태에서는 `Schema::hasTable()` 호출을 건너뜁니다.
* 인스톨러 이전 환경이나 테스트에서는 기존 체크 경로로 폴백합니다.
*/
private static function isTemplateTableReady(): bool
{
if (config('app.installer_completed')) {
return true;
}
try {
DB::connection()->getPdo();
return Schema::hasTable('templates');
} catch (\Throwable $e) {
return false;
}
}
private static function resolveTemplateStatusCache(): CacheInterface
{
try {
return app(CacheInterface::class);
} catch (\Throwable $e) {
return new CoreCacheDriver(config('cache.default', 'array'));
}
}
}
+24 -3
View File
@@ -2,7 +2,8 @@
namespace App\Extension\Traits;
use Illuminate\Support\Facades\Cache;
use App\Contracts\Extension\CacheInterface;
use App\Extension\Cache\CoreCacheDriver;
use Illuminate\Support\Facades\Log;
/**
@@ -14,6 +15,11 @@ use Illuminate\Support\Facades\Log;
*/
trait ClearsTemplateCaches
{
/**
* 캐시 버전 키 (드라이버 접두사 `g7:core:` 다음에 붙음).
*/
private static string $extensionCacheVersionKey = 'ext.cache_version';
/**
* 확장 기능 캐시 버전을 증가시킵니다.
*
@@ -25,7 +31,7 @@ trait ClearsTemplateCaches
{
try {
$newVersion = time();
Cache::put('extension_cache_version', $newVersion);
self::resolveExtensionCache()->put(self::$extensionCacheVersionKey, $newVersion);
Log::info('확장 기능 캐시 버전 증가', [
'new_version' => $newVersion,
@@ -44,7 +50,7 @@ trait ClearsTemplateCaches
*/
public static function getExtensionCacheVersion(): int
{
return (int) Cache::get('extension_cache_version', 0);
return (int) self::resolveExtensionCache()->get(self::$extensionCacheVersionKey, 0);
}
/**
@@ -82,4 +88,19 @@ trait ClearsTemplateCaches
{
Log::info('템플릿 레이아웃 캐시 무효화 (캐시 버전 증가로 처리)');
}
/**
* CacheInterface 인스턴스를 컨테이너에서 lazy 조회합니다.
*
* 컨테이너 미구성 환경(예: 일부 단위 테스트)에서도 동작하도록
* fallback 으로 직접 CoreCacheDriver 를 생성합니다.
*/
private static function resolveExtensionCache(): CacheInterface
{
try {
return app(CacheInterface::class);
} catch (\Throwable $e) {
return new CoreCacheDriver(config('cache.default', 'array'));
}
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Extension\Traits;
/**
* 레이아웃 콘텐츠의 정규화된 해시/크기를 계산하는 공통 로직.
*
* template_layouts 테이블의 original_content_hash / original_content_size
* 컬럼에 기록되는 값이며, 확장 업데이트 시 사용자 수정 여부 판단에 사용됩니다.
*
* Module/Plugin/Template 매니저에서 공용으로 사용합니다.
*/
trait ComputesLayoutContentHash
{
/**
* 레이아웃 콘텐츠의 정규화된 SHA-256 해시를 계산합니다.
*
* @param array|string $content 배열 또는 JSON 문자열
*/
protected function computeContentHash(array|string $content): string
{
return hash('sha256', $this->normalizeContent($content));
}
/**
* 레이아웃 콘텐츠의 정규화된 바이트 크기를 계산합니다.
*
* @param array|string $content 배열 또는 JSON 문자열
*/
protected function computeContentSize(array|string $content): int
{
return strlen($this->normalizeContent($content));
}
/**
* 콘텐츠를 정규화된 JSON 문자열로 변환합니다.
*
* @param array|string $content 배열 또는 JSON 문자열
*/
protected function normalizeContent(array|string $content): string
{
return is_string($content)
? json_encode(json_decode($content, true), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
: json_encode($content, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
@@ -2,9 +2,10 @@
namespace App\Extension\Traits;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\LayoutRepositoryInterface;
use App\Enums\LayoutSourceType;
use Illuminate\Support\Facades\Cache;
use App\Extension\Cache\CoreCacheDriver;
use Illuminate\Support\Facades\Log;
/**
@@ -93,20 +94,34 @@ trait InvalidatesLayoutCache
*/
protected function forgetLayoutCacheKeys(object $layout, string $templateIdentifier = ''): void
{
$cache = $this->resolveLayoutCache();
// 1. LayoutService 내부 캐시 (버전 없음 → 능동 삭제)
Cache::forget("template.{$layout->template_id}.layout.{$layout->name}");
$cache->forget("template.{$layout->template_id}.layout.{$layout->name}");
// 2. 소스 해시 포함 키 (버전 없음 → 능동 삭제)
if ($layout->source_type && $layout->source_identifier) {
$sourceHash = md5($layout->source_type->value.$layout->source_identifier);
Cache::forget("template.{$layout->template_id}.layout.{$layout->name}.{$sourceHash}");
$cache->forget("template.{$layout->template_id}.layout.{$layout->name}.{$sourceHash}");
}
// 3. PublicLayoutController 캐시 (버전 포함)
// 레이아웃 내용 편집 시 현재 버전 키 삭제 (버전 변경 없이 내용만 바뀜)
if ($templateIdentifier) {
$cacheVersion = (int) Cache::get('extension_cache_version', 0);
Cache::forget("layout.{$templateIdentifier}.{$layout->name}.v{$cacheVersion}");
$cacheVersion = (int) $cache->get('ext.cache_version', 0);
$cache->forget("layout.{$templateIdentifier}.{$layout->name}.v{$cacheVersion}");
}
}
/**
* CacheInterface 인스턴스를 lazy 조회합니다.
*/
private function resolveLayoutCache(): CacheInterface
{
try {
return app(CacheInterface::class);
} catch (\Throwable $e) {
return new CoreCacheDriver(config('cache.default', 'array'));
}
}
@@ -0,0 +1,216 @@
<?php
namespace App\Extension\Traits;
use App\Contracts\Extension\ModuleManagerInterface;
use App\Contracts\Extension\PluginManagerInterface;
use Illuminate\Support\Facades\Log;
/**
* SEO 변수 중복 검증 기능을 제공하는 트레이트.
*
* 모듈 및 플러그인 설치 시 seoVariables()에서 반환하는
* 변수명이 기존 활성 확장과 충돌하지 않는지 검증합니다.
*
* 검증 대상:
* - _common 변수: 모든 활성 확장의 _common 및 page_type별 변수와 중복 확인
* - page_type별 변수: 동일 page_type 내 기존 변수 + _common 변수와 중복 확인
*/
trait ValidatesSeoVariables
{
/**
* 확장의 SEO 변수명이 기존 활성 확장과 중복되지 않는지 검증합니다.
*
* @param object $extension 검증할 모듈 또는 플러그인 인스턴스
* @param string $extensionType 확장 타입 ('module' 또는 'plugin')
*
* @throws \Exception SEO 변수명이 중복될 때
*/
protected function validateSeoVariables(object $extension, string $extensionType = 'module'): void
{
$newVars = $extension->seoVariables();
$identifier = $extension->getIdentifier();
// SEO 변수가 없으면 검증 통과
if (empty($newVars)) {
return;
}
// 1. 자체 _common과 page_type별 변수 간 중복 검증
$selfErrors = $this->validateSelfSeoVariableConflicts($newVars);
// 2. 기존 활성 확장들의 SEO 변수 수집
$existingVars = $this->collectExistingSeoVariables($identifier);
// 3. 기존 변수와 충돌 검증
$crossErrors = $this->validateCrossSeoVariableConflicts($newVars, $existingVars);
$errors = array_merge($selfErrors, $crossErrors);
if (! empty($errors)) {
throw new \Exception(
$this->formatSeoValidationError($extensionType, $identifier, implode("\n- ", $errors))
);
}
}
/**
* SEO 변수 검증 에러 메시지를 포맷합니다.
*
* @param string $extensionType 확장 타입 ('module' 또는 'plugin')
* @param string $identifier 확장 식별자
* @param string $reason 에러 사유
* @return string 포맷된 에러 메시지
*/
private function formatSeoValidationError(string $extensionType, string $identifier, string $reason): string
{
$translationKey = $extensionType === 'module'
? 'modules.errors.seo_variable_conflict'
: 'plugins.errors.seo_variable_conflict';
return __($translationKey, [
'identifier' => $identifier,
'reason' => $reason,
]);
}
/**
* 확장 자체 내에서 _common과 page_type별 변수명 충돌을 검증합니다.
*
* @param array $vars SEO 변수 정의
* @return array 에러 메시지 배열
*/
private function validateSelfSeoVariableConflicts(array $vars): array
{
$errors = [];
$commonVarNames = array_keys($vars['_common'] ?? []);
foreach ($vars as $pageType => $pageVars) {
if ($pageType === '_common' || ! is_array($pageVars)) {
continue;
}
$pageVarNames = array_keys($pageVars);
$conflicts = array_intersect($commonVarNames, $pageVarNames);
if (! empty($conflicts)) {
$errors[] = "SEO variable name conflict: _common variables [".implode(', ', $conflicts)."] duplicated in page_type '{$pageType}'";
}
}
return $errors;
}
/**
* 기존 활성 확장들의 SEO 변수를 수집합니다.
*
* @param string $excludeIdentifier 제외할 확장 식별자 (현재 설치 중인 확장)
* @return array ['_common' => [변수명 => 소유자], 'page_type' => [변수명 => 소유자]]
*/
private function collectExistingSeoVariables(string $excludeIdentifier): array
{
$collected = ['_common' => []];
// 활성 모듈들의 SEO 변수 수집
try {
$moduleManager = app(ModuleManagerInterface::class);
foreach ($moduleManager->getActiveModules() as $module) {
if ($module->getIdentifier() === $excludeIdentifier) {
continue;
}
$this->mergeExtensionSeoVars($collected, $module->seoVariables(), $module->getIdentifier());
}
} catch (\Throwable $e) {
Log::debug('[SEO] Failed to collect module SEO variables', ['error' => $e->getMessage()]);
}
// 활성 플러그인들의 SEO 변수 수집
try {
$pluginManager = app(PluginManagerInterface::class);
foreach ($pluginManager->getActivePlugins() as $plugin) {
if ($plugin->getIdentifier() === $excludeIdentifier) {
continue;
}
$this->mergeExtensionSeoVars($collected, $plugin->seoVariables(), $plugin->getIdentifier());
}
} catch (\Throwable $e) {
Log::debug('[SEO] Failed to collect plugin SEO variables', ['error' => $e->getMessage()]);
}
return $collected;
}
/**
* 확장의 SEO 변수를 수집 결과에 병합합니다.
*
* @param array &$collected 수집 결과 (참조)
* @param array $vars 확장의 seoVariables() 반환값
* @param string $owner 소유자 식별자
*/
private function mergeExtensionSeoVars(array &$collected, array $vars, string $owner): void
{
foreach ($vars as $pageType => $pageVars) {
if (! is_array($pageVars)) {
continue;
}
if (! isset($collected[$pageType])) {
$collected[$pageType] = [];
}
foreach (array_keys($pageVars) as $varName) {
$collected[$pageType][$varName] = $owner;
}
}
}
/**
* 새 확장의 변수가 기존 확장과 충돌하는지 검증합니다.
*
* @param array $newVars 새 확장의 SEO 변수
* @param array $existingVars 기존 활성 확장들의 변수 맵
* @return array 에러 메시지 배열
*/
private function validateCrossSeoVariableConflicts(array $newVars, array $existingVars): array
{
$errors = [];
foreach ($newVars as $pageType => $pageVars) {
if (! is_array($pageVars)) {
continue;
}
foreach (array_keys($pageVars) as $varName) {
// 동일 pageType 내 중복 확인
if (isset($existingVars[$pageType][$varName])) {
$owner = $existingVars[$pageType][$varName];
$errors[] = "Variable '{$varName}' in '{$pageType}' conflicts with {$owner}";
continue;
}
// 새 _common 변수가 기존 page_type별 변수와 충돌 확인
if ($pageType === '_common') {
foreach ($existingVars as $existPageType => $existPageVars) {
if ($existPageType === '_common') {
continue;
}
if (isset($existPageVars[$varName])) {
$owner = $existPageVars[$varName];
$errors[] = "Common variable '{$varName}' conflicts with '{$existPageType}' variable of {$owner}";
}
}
}
// 새 page_type별 변수가 기존 _common 변수와 충돌 확인
if ($pageType !== '_common' && isset($existingVars['_common'][$varName])) {
$owner = $existingVars['_common'][$varName];
$errors[] = "Variable '{$varName}' in '{$pageType}' conflicts with _common variable of {$owner}";
}
}
}
return $errors;
}
}
+28
View File
@@ -80,4 +80,32 @@ class UpgradeContext
currentStep: $stepVersion,
);
}
/**
* 업그레이드 스텝의 spawn 프로세스(proc_open)에 전달할 환경변수 기본 세트를 반환합니다.
*
* 코어 업그레이드의 `updateVersionInEnv()` 는 Step 11 (마지막) 에서 실행되므로,
* Step 10 의 upgrade step / spawn 은 디스크 `.env` 의 `APP_VERSION` 이 여전히
* `fromVersion` 상태에서 부팅된다. 이 때 `CoreServiceProvider::boot()` 의
* `validateAndDeactivateIncompatibleExtensions` 가 확장 manifest 의 요구 버전과
* 구 APP_VERSION 을 비교하여 전 확장을 자동 비활성화하는 회귀가 발생한다.
*
* 본 헬퍼는 `APP_VERSION` 을 `toVersion` 으로 명시 전달해 spawn 자식이 새 버전 기준으로
* 호환성 판정을 수행하도록 보장한다. 반환값을 `proc_open` 의 `$env` 인자로 그대로 넘기거나
* `array_merge` 로 확장 전용 env 와 합쳐 사용한다.
*
* 추가 키를 병합할 때 예시:
* $env = $context->spawnEnv(['MY_FLAG' => '1']);
*
* @param array<string, string> $additional 병합할 추가 env 쌍 (APP_VERSION 보다 나중에 적용되어 덮어쓸 수 있음)
* @return array<string, string>
*/
public function spawnEnv(array $additional = []): array
{
return array_merge(
$_ENV,
['APP_VERSION' => $this->toVersion],
$additional,
);
}
}
+280
View File
@@ -0,0 +1,280 @@
<?php
namespace App\Extension\Vendor;
use Illuminate\Support\Facades\Log;
/**
* 런타임 환경에서 composer 실행 가능 여부 및 ZipArchive 사용 가능 여부를 감지합니다.
*
* 공유 호스팅 환경(proc_open 차단, composer 미설치)에서 vendor 번들 모드로
* 자동 폴백하기 위한 판단 근거를 제공합니다.
*/
class EnvironmentDetector
{
/**
* 캐시된 composer 실행 가능 여부.
*/
private ?bool $cachedComposerExecutable = null;
/**
* 캐시된 composer 바이너리 경로.
*/
private ?string $cachedComposerBinary = null;
/**
* proc_open() 함수 사용 가능 여부.
*/
public function hasProcOpen(): bool
{
if (! function_exists('proc_open')) {
return false;
}
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
return ! in_array('proc_open', $disabled, true);
}
/**
* shell_exec() 함수 사용 가능 여부.
*/
public function hasShellExec(): bool
{
if (! function_exists('shell_exec')) {
return false;
}
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
return ! in_array('shell_exec', $disabled, true);
}
/**
* ZipArchive 클래스 사용 가능 여부.
*/
public function hasZipArchive(): bool
{
return class_exists(\ZipArchive::class);
}
/**
* composer 바이너리 경로 찾기.
*
* 우선순위: hint → config(process.composer_binary) → $_ENV['COMPOSER_BINARY']
* → PATH 검색 → composer.phar
*/
public function findComposerBinary(?string $hint = null): ?string
{
if ($this->cachedComposerBinary !== null) {
return $this->cachedComposerBinary ?: null;
}
$candidates = array_filter([
$hint,
config('process.composer_binary'),
$_ENV['COMPOSER_BINARY'] ?? null,
getenv('COMPOSER_BINARY') ?: null,
]);
foreach ($candidates as $candidate) {
if ($this->isExecutableCandidate($candidate)) {
return $this->cachedComposerBinary = $candidate;
}
}
$found = $this->searchComposerInPath();
if ($found !== null) {
return $this->cachedComposerBinary = $found;
}
// composer.phar 폴백
$pharCandidates = [
base_path('composer.phar'),
getcwd().DIRECTORY_SEPARATOR.'composer.phar',
];
foreach ($pharCandidates as $phar) {
if (is_file($phar)) {
return $this->cachedComposerBinary = $phar;
}
}
$this->cachedComposerBinary = '';
return null;
}
/**
* composer 실행 가능 여부 종합 판단.
*
* proc_open 사용 가능 + composer 바이너리 발견 + `composer --version` 종료 코드 0.
*/
public function canExecuteComposer(?string $hint = null): bool
{
if ($this->cachedComposerExecutable !== null && $hint === null) {
return $this->cachedComposerExecutable;
}
if (! $this->hasProcOpen()) {
return $this->cachedComposerExecutable = false;
}
$binary = $this->findComposerBinary($hint);
if ($binary === null) {
return $this->cachedComposerExecutable = false;
}
try {
$command = $this->buildComposerCommand($binary, ['--version', '--no-interaction']);
$process = @proc_open(
$command,
[
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
],
$pipes,
null,
null,
['bypass_shell' => true]
);
if (! is_resource($process)) {
return $this->cachedComposerExecutable = false;
}
foreach ($pipes as $pipe) {
if (is_resource($pipe)) {
@fclose($pipe);
}
}
$exit = proc_close($process);
return $this->cachedComposerExecutable = ($exit === 0);
} catch (\Throwable $e) {
Log::warning('Composer 실행 가능 여부 확인 실패', [
'error' => $e->getMessage(),
'binary' => $binary,
]);
return $this->cachedComposerExecutable = false;
}
}
/**
* 지정 경로에 쓰기 가능한지 확인.
*/
public function canWriteVendor(string $targetPath): bool
{
$parent = dirname($targetPath);
return is_dir($parent) && is_writable($parent);
}
/**
* 인스톨러 Step 2 요구사항 체크용 종합 리포트.
*
* @return array{
* proc_open: bool,
* shell_exec: bool,
* zip_archive: bool,
* composer_binary: string|null,
* composer_executable: bool,
* can_use_composer: bool,
* can_use_bundle: bool,
* }
*/
public function summarize(?string $hint = null): array
{
$composerBinary = $this->findComposerBinary($hint);
$composerExecutable = $this->canExecuteComposer($hint);
$zipAvailable = $this->hasZipArchive();
return [
'proc_open' => $this->hasProcOpen(),
'shell_exec' => $this->hasShellExec(),
'zip_archive' => $zipAvailable,
'composer_binary' => $composerBinary,
'composer_executable' => $composerExecutable,
'can_use_composer' => $composerExecutable,
'can_use_bundle' => $zipAvailable,
];
}
/**
* 캐시 초기화 (테스트용).
*/
public function resetCache(): void
{
$this->cachedComposerExecutable = null;
$this->cachedComposerBinary = null;
}
/**
* composer 실행 명령 문자열 구성.
*
* @param array<int, string> $args
*/
private function buildComposerCommand(string $binary, array $args): string
{
$escaped = array_map('escapeshellarg', $args);
if (str_contains($binary, ' ')) {
// 전체 명령어로 취급
return $binary.' '.implode(' ', $escaped);
}
if (str_ends_with(strtolower($binary), '.phar')) {
$phpBinary = config('process.php_binary', 'php');
return escapeshellarg($phpBinary).' '.escapeshellarg($binary).' '.implode(' ', $escaped);
}
return escapeshellarg($binary).' '.implode(' ', $escaped);
}
/**
* PATH 환경변수에서 composer 검색.
*/
private function searchComposerInPath(): ?string
{
$pathEnv = getenv('PATH') ?: ($_SERVER['PATH'] ?? '');
if (empty($pathEnv)) {
return null;
}
$separator = DIRECTORY_SEPARATOR === '\\' ? ';' : ':';
$paths = explode($separator, $pathEnv);
$names = DIRECTORY_SEPARATOR === '\\'
? ['composer.bat', 'composer.exe', 'composer.phar', 'composer']
: ['composer', 'composer.phar'];
foreach ($paths as $dir) {
foreach ($names as $name) {
$candidate = rtrim($dir, '/\\').DIRECTORY_SEPARATOR.$name;
if (is_file($candidate)) {
return $candidate;
}
}
}
return null;
}
/**
* 후보 경로가 실행 가능한 파일인지 확인.
*/
private function isExecutableCandidate(?string $candidate): bool
{
if ($candidate === null || $candidate === '') {
return false;
}
// 공백 포함 시 전체 커맨드로 간주 — 파일 존재 검사 스킵
if (str_contains($candidate, ' ')) {
return true;
}
return is_file($candidate);
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Extension\Vendor\Exceptions;
/**
* Vendor 설치 실패 예외.
*
* 에러 키는 lang/{locale}/exceptions.php 의 vendor.* 하위에 정의되어 있음.
* 예: exceptions.vendor.composer_not_available
*/
class VendorInstallException extends \RuntimeException
{
/**
* @param string $errorKey 'exceptions.vendor.*' 하위 키 (예: 'composer_not_available')
* @param array<string, mixed> $context 다국어 파라미터 치환 컨텍스트
* @param \Throwable|null $previous 이전 예외
*/
public function __construct(
public readonly string $errorKey,
public readonly array $context = [],
?\Throwable $previous = null,
) {
$message = __('exceptions.vendor.'.$errorKey, $context);
if (is_array($message)) {
$message = 'exceptions.vendor.'.$errorKey;
}
// 권한 거부 등 진단 힌트가 있으면 메시지에 덧붙여 사용자에게 즉시 노출
if (isset($context['hint'])) {
$message = (string) $message.' — '.$context['hint'];
}
parent::__construct((string) $message, 0, $previous);
}
public function getErrorKey(): string
{
return $this->errorKey;
}
public function getContext(): array
{
return $this->context;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 번들 무결성 검증 결과.
*/
class IntegrityResult
{
/**
* @param bool $valid 모든 검증 통과 여부
* @param array<string> $errors 검증 실패 키 목록 (다국어 키)
* @param array<string> $warnings 경고 목록 (valid=true여도 존재 가능)
* @param array<string, mixed> $meta manifest에서 읽은 메타정보
*/
public function __construct(
public readonly bool $valid,
public readonly array $errors = [],
public readonly array $warnings = [],
public readonly array $meta = [],
) {}
public static function valid(array $meta = [], array $warnings = []): self
{
return new self(valid: true, errors: [], warnings: $warnings, meta: $meta);
}
public static function invalid(array $errors, array $meta = []): self
{
return new self(valid: false, errors: $errors, warnings: [], meta: $meta);
}
public function errorMessages(): array
{
return array_map(
fn (string $key) => __('exceptions.vendor.'.$key),
$this->errors
);
}
}
+320
View File
@@ -0,0 +1,320 @@
<?php
namespace App\Extension\Vendor;
use App\Extension\Vendor\Exceptions\VendorInstallException;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
/**
* vendor-bundle.zip 을 대상 디렉토리로 추출하여 vendor/를 구성합니다.
*
* 공유 호스팅 친화적 설계:
* - targetDir 자체(프로젝트 루트)의 쓰기 권한은 요구하지 않음
* - vendor/ 디렉토리 자체는 유지하고 **내부 항목만 조작**
* - 기존 내용은 vendor/.bundle_backup_{ts}/ 로 이동 (vendor/ 쓰기 권한만으로 가능)
* - 추출 실패 시 백업에서 복원, 성공 시 백업 삭제
*
* 이 접근은 웹 서버 사용자가 프로젝트 루트에는 쓰기 권한이 없지만
* vendor/ 디렉토리에만 권한이 부여된 전형적 공유 호스팅 환경을 지원합니다.
*/
class VendorBundleInstaller
{
public function __construct(
private readonly VendorIntegrityChecker $integrityChecker,
) {}
/**
* 번들 zip을 대상 디렉토리에 추출합니다.
*
* @param string $sourceDir vendor-bundle.zip 이 위치한 디렉토리
* @param string $targetDir vendor/가 배치될 디렉토리 (일반적으로 sourceDir과 동일)
*
* @throws VendorInstallException
*/
public function install(string $sourceDir, string $targetDir): VendorInstallResult
{
$startTime = microtime(true);
// 1. ZipArchive 확장 확인
if (! class_exists(\ZipArchive::class)) {
throw new VendorInstallException('zip_archive_not_available');
}
// 2. 무결성 검증
$integrity = $this->integrityChecker->verify($sourceDir);
if (! $integrity->valid) {
throw new VendorInstallException(
errorKey: 'bundle_integrity_failed',
context: ['details' => implode(', ', $integrity->errorMessages())],
);
}
$zipPath = $sourceDir.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
$vendorDir = $targetDir.DIRECTORY_SEPARATOR.'vendor';
$backupDirName = '.bundle_backup_'.date('Ymd_His');
$backupDir = $vendorDir.DIRECTORY_SEPARATOR.$backupDirName;
// 3. 쓰기 권한 유연 검사 — vendor/ 가 있으면 vendor/ 권한만, 없으면 targetDir 권한 필요
$this->validateTargetWritable($targetDir, $vendorDir);
// 4. zip slip 방지 사전 검증
$this->validateZipContents($zipPath);
// 5. 기존 vendor/ 내부 항목을 vendor/.bundle_backup_{ts}/ 로 이동
// (vendor/ 디렉토리 자체는 유지 — targetDir 쓰기 권한 불필요)
$hasBackup = false;
if (is_dir($vendorDir)) {
$hasBackup = $this->moveVendorContentsToBackup($vendorDir, $backupDir, $backupDirName);
} else {
// vendor/ 없음 — 신규 생성 (targetDir 쓰기 권한 필요, 위에서 이미 검증)
if (! @mkdir($vendorDir, 0755, true) && ! is_dir($vendorDir)) {
throw new VendorInstallException(
errorKey: 'target_not_writable',
context: ['path' => $vendorDir],
);
}
}
// 6. 추출
try {
$zip = new \ZipArchive;
$openResult = $zip->open($zipPath);
if ($openResult !== true) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'ZipArchive::open failed (code: '.$openResult.')'],
);
}
$extracted = $zip->extractTo($targetDir);
$zip->close();
if (! $extracted) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'ZipArchive::extractTo returned false'],
);
}
// 7. 성공: 백업 디렉토리 삭제 (vendor/.bundle_backup_{ts}/)
if ($hasBackup && is_dir($backupDir)) {
File::deleteDirectory($backupDir);
}
$duration = microtime(true) - $startTime;
$packageCount = (int) ($integrity->meta['package_count'] ?? 0);
$zipSize = @filesize($zipPath) ?: 0;
Log::info('Vendor 번들 추출 성공', [
'source_dir' => $sourceDir,
'target_dir' => $targetDir,
'package_count' => $packageCount,
'zip_size' => $zipSize,
'duration_seconds' => round($duration, 2),
]);
return new VendorInstallResult(
mode: VendorMode::Bundled,
strategy: 'bundled',
packageCount: $packageCount,
durationSeconds: $duration,
details: [
'zip_size' => $zipSize,
'source_dir' => $sourceDir,
],
);
} catch (\Throwable $e) {
// 실패: 백업에서 복원
if ($hasBackup && is_dir($backupDir)) {
$this->restoreVendorFromBackup($vendorDir, $backupDir, $backupDirName);
}
if ($e instanceof VendorInstallException) {
throw $e;
}
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => $e->getMessage()],
previous: $e,
);
}
}
/**
* 쓰기 권한 검사 — vendor/ 가 존재하면 vendor/ 권한만, 없으면 targetDir 권한 필요.
*
* 공유 호스팅 환경에서 targetDir (프로젝트 루트) 에는 쓰기 권한이 없고
* vendor/ 에만 권한이 부여된 케이스를 지원한다.
*
* @throws VendorInstallException
*/
private function validateTargetWritable(string $targetDir, string $vendorDir): void
{
if (is_dir($vendorDir)) {
if (! is_writable($vendorDir)) {
throw new VendorInstallException(
errorKey: 'target_not_writable',
context: $this->buildPermissionContext($vendorDir),
);
}
return;
}
// vendor/ 없음 — 생성을 위해 targetDir 에 쓰기 권한 필요
if (! is_dir($targetDir) || ! is_writable($targetDir)) {
throw new VendorInstallException(
errorKey: 'target_not_writable',
context: $this->buildPermissionContext($targetDir),
);
}
}
/**
* 권한 거부 컨텍스트에 소유권 정보를 포함합니다.
*
* 공유 호스팅에서 FTP 사용자와 PHP 실행 사용자가 다른 경우 진단을 돕기 위해
* 현재 실행 사용자, 디렉토리 소유자, 권장 조치를 함께 반환합니다.
*/
private function buildPermissionContext(string $path): array
{
$context = ['path' => $path];
if (! function_exists('posix_geteuid') || ! function_exists('posix_getpwuid')) {
return $context;
}
$currentUid = posix_geteuid();
$currentUser = posix_getpwuid($currentUid)['name'] ?? (string) $currentUid;
$context['current_user'] = "{$currentUser}({$currentUid})";
if (file_exists($path)) {
$ownerUid = fileowner($path);
$ownerUser = posix_getpwuid($ownerUid)['name'] ?? (string) $ownerUid;
$context['owner'] = "{$ownerUser}({$ownerUid})";
if ($currentUid !== $ownerUid) {
$context['hint'] = __('exceptions.vendor.target_not_writable_owner_hint', [
'path' => $path,
'current_user' => $context['current_user'],
'current_user_name' => $currentUser,
'owner' => $context['owner'],
'owner_name' => $ownerUser,
]);
}
}
return $context;
}
/**
* 기존 vendor/ 내부 항목을 vendor/.bundle_backup_{ts}/ 로 이동합니다.
*
* vendor/ 디렉토리 자체는 유지하므로 targetDir 쓰기 권한이 필요하지 않습니다.
*
* @return bool 백업 성공 여부 (false 시 in-place overwrite 로 추출 진행)
*/
private function moveVendorContentsToBackup(string $vendorDir, string $backupDir, string $backupDirName): bool
{
if (! @mkdir($backupDir) && ! is_dir($backupDir)) {
Log::warning('Vendor 번들 백업 디렉토리 생성 실패 — in-place overwrite 로 진행', [
'vendor_dir' => $vendorDir,
'backup_dir' => $backupDir,
]);
return false;
}
$items = @scandir($vendorDir) ?: [];
foreach ($items as $item) {
if ($item === '.' || $item === '..' || $item === $backupDirName) {
continue;
}
$src = $vendorDir.DIRECTORY_SEPARATOR.$item;
$dst = $backupDir.DIRECTORY_SEPARATOR.$item;
@rename($src, $dst);
}
return true;
}
/**
* 백업 디렉토리에서 vendor/ 로 내용을 복원합니다.
*
* 추출 중 실패한 경우 기존 상태로 되돌리기 위해 호출됩니다.
*/
private function restoreVendorFromBackup(string $vendorDir, string $backupDir, string $backupDirName): void
{
// 1. 추출로 이미 생성된 파일/디렉토리 정리 (백업 폴더 제외)
$items = @scandir($vendorDir) ?: [];
foreach ($items as $item) {
if ($item === '.' || $item === '..' || $item === $backupDirName) {
continue;
}
$path = $vendorDir.DIRECTORY_SEPARATOR.$item;
if (is_dir($path) && ! is_link($path)) {
File::deleteDirectory($path);
} elseif (file_exists($path)) {
@unlink($path);
}
}
// 2. 백업 항목을 원위치로 이동
$backupItems = @scandir($backupDir) ?: [];
foreach ($backupItems as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$src = $backupDir.DIRECTORY_SEPARATOR.$item;
$dst = $vendorDir.DIRECTORY_SEPARATOR.$item;
@rename($src, $dst);
}
// 3. 빈 백업 디렉토리 제거
@rmdir($backupDir);
}
/**
* zip 내부 파일 경로의 안전성을 검증합니다 (zip slip 방지).
*
* @throws VendorInstallException
*/
private function validateZipContents(string $zipPath): void
{
$zip = new \ZipArchive;
if ($zip->open($zipPath) !== true) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'cannot open zip for validation'],
);
}
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if ($name === false) {
continue;
}
// 경로 탈출 방지
$normalized = str_replace('\\', '/', $name);
if (
str_contains($normalized, '../')
|| str_starts_with($normalized, '/')
|| preg_match('#^[A-Za-z]:/#', $normalized)
) {
$zip->close();
throw new VendorInstallException(
errorKey: 'bundle_contains_unsafe_path',
context: ['path' => $name],
);
}
}
$zip->close();
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 번들 빌드 결과 DTO.
*/
class VendorBundleResult
{
/**
* @param string $target 'core' | 'module:identifier' | 'plugin:identifier'
* @param string $zipPath 생성된 zip 파일 절대 경로
* @param string $manifestPath 생성된 vendor-bundle.json 절대 경로
* @param int $zipSize zip 파일 크기 (bytes)
* @param int $packageCount 번들에 포함된 composer 패키지 수
* @param bool $skipped 이미 최신 상태여서 빌드 스킵 여부
* @param string $reason 스킵 사유 또는 빌드 메시지
*/
public function __construct(
public readonly string $target,
public readonly string $zipPath,
public readonly string $manifestPath,
public readonly int $zipSize,
public readonly int $packageCount,
public readonly bool $skipped = false,
public readonly string $reason = '',
) {}
public function zipSizeHuman(): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$size = $this->zipSize;
$unit = 0;
while ($size >= 1024 && $unit < count($units) - 1) {
$size /= 1024;
$unit++;
}
return sprintf('%.1f %s', $size, $units[$unit]);
}
}
+592
View File
@@ -0,0 +1,592 @@
<?php
namespace App\Extension\Vendor;
use App\Extension\Vendor\Exceptions\VendorInstallException;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
/**
* 개발 환경에서 vendor/ 디렉토리를 zip으로 압축하여 번들 파일을 생성합니다.
*
* 빌드 타임에만 실행되며, 생성된 번들은 런타임에 VendorBundleInstaller가 소비합니다.
*
* 빌드 절차 (staging 기반):
* 1. storage/app/vendor-bundle-staging/{uniqid}/ 임시 디렉토리 생성
* 2. 소스의 composer.json + composer.lock 을 임시 디렉토리로 복사
* 3. 임시 디렉토리에서 `composer install --no-dev --no-scripts --prefer-dist` 실행
* 4. 생성된 vendor/ 를 (EXCLUDE_PATTERNS 적용 후) zip 으로 기록
* 5. manifest.json 기록
* 6. 임시 디렉토리 정리
*
* 이 방식은 개발 vendor/ 가 dev 의존성을 포함하고 있어도 번들에 dev 의존성이
* 섞여 들어가지 않도록 보장하며, composer 가 생성한 autoload 파일과 vendor/
* 내용이 완벽히 일치함을 보장합니다 (autoload_files.php 가 존재하지 않는
* dev 패키지를 require 하는 버그 방지).
*/
class VendorBundler
{
public const SCHEMA_VERSION = '1.0';
/**
* 압축 제외 경로 패턴 (패키지 디렉토리 내부 파일).
*
* @var array<int, string>
*/
private const EXCLUDE_PATTERNS = [
'.git',
'.github',
'tests',
'Tests',
'docs',
'.gitignore',
'.gitattributes',
'.gitkeep',
'phpunit.xml',
'phpunit.xml.dist',
'psalm.xml',
'psalm.xml.dist',
'.phpcs.xml',
'.phpcs.xml.dist',
];
/**
* 테스트에서 composer 실행을 대체하기 위한 주입 가능한 러너.
*
* null 이면 실제 composer 바이너리를 proc_open 으로 실행합니다.
* 테스트에서는 setComposerInstallRunner() 로 주입하여 가짜 vendor/ 구조를 생성합니다.
*/
private ?\Closure $composerInstallRunner = null;
public function __construct(
private readonly VendorIntegrityChecker $integrityChecker,
private readonly ?EnvironmentDetector $environmentDetector = null,
) {}
/**
* 테스트용 — composer 실행을 대체할 러너를 주입합니다.
*
* 러너는 `fn (string $stagingDir): void` 형식이며, 주어진 스테이징 디렉토리에
* vendor/ 구조를 직접 생성해야 합니다.
*/
public function setComposerInstallRunner(?\Closure $runner): void
{
$this->composerInstallRunner = $runner;
}
/**
* 코어(루트) vendor/를 번들링합니다.
*
* 코어는 소스 = 출력 경로가 base_path() 로 동일합니다.
*/
public function buildForCore(bool $force = false): VendorBundleResult
{
return $this->build(
sourcePath: base_path(),
outputPath: base_path(),
target: 'core',
force: $force,
);
}
/**
* 모듈/플러그인의 vendor/를 번들링합니다.
*
* 소스는 **활성 디렉토리** (예: modules/sirsoft-ecommerce/vendor/) 에서 읽고,
* 출력은 **_bundled 디렉토리** (예: modules/_bundled/sirsoft-ecommerce/vendor-bundle.zip) 에 저장합니다.
*
* 이유: _bundled 는 Git 추적 소스 디렉토리로 vendor/ 를 두지 않는 것이 원칙.
* 활성 디렉토리는 설치 시 composer install 이 실행되어 실제 패키지가 설치된 상태.
*
* @param string $type 'module' | 'plugin'
*/
public function buildForExtension(string $type, string $identifier, bool $force = false): VendorBundleResult
{
$activePath = match ($type) {
'module' => base_path('modules/'.$identifier),
'plugin' => base_path('plugins/'.$identifier),
default => throw new \InvalidArgumentException("Unsupported extension type: $type"),
};
$outputPath = match ($type) {
'module' => base_path('modules/_bundled/'.$identifier),
'plugin' => base_path('plugins/_bundled/'.$identifier),
};
if (! is_dir($outputPath)) {
throw new VendorInstallException(
errorKey: 'source_dir_not_found',
context: ['path' => $outputPath],
);
}
// 활성 디렉토리가 없으면 미설치 확장 — skip 처리 (예외 대신)
//
// 미설치 확장의 경우 composer.json 은 _bundled 에만 존재하므로
// 외부 의존성 여부를 _bundled 의 composer.json 에서 확인한다.
if (! is_dir($activePath)) {
$bundledComposerJson = $outputPath.DIRECTORY_SEPARATOR.'composer.json';
$reason = file_exists($bundledComposerJson) && $this->hasExternalDependencies($bundledComposerJson)
? 'extension-not-installed'
: 'no-external-dependencies';
return new VendorBundleResult(
target: $type.':'.$identifier,
zipPath: $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME,
manifestPath: $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::MANIFEST_FILENAME,
zipSize: 0,
packageCount: 0,
skipped: true,
reason: $reason,
);
}
return $this->build(
sourcePath: $activePath,
outputPath: $outputPath,
target: $type.':'.$identifier,
force: $force,
);
}
/**
* stale 여부 확인 — composer.json/lock 해시가 기존 manifest와 일치하는지 검사.
*
* 외부 패키지 의존성이 없는 확장은 번들링 대상이 아니므로 항상 false 를 반환합니다.
*
* @param string $sourcePath composer.json/lock 을 읽을 경로 (활성 디렉토리)
* @param string|null $outputPath 번들 출력 경로 (null 이면 sourcePath 와 동일 — 코어 케이스)
*/
public function isStale(string $sourcePath, ?string $outputPath = null): bool
{
$outputPath ??= $sourcePath;
$composerJsonPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.json';
if (file_exists($composerJsonPath) && ! $this->hasExternalDependencies($composerJsonPath)) {
return false;
}
$manifestPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::MANIFEST_FILENAME;
$zipPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
if (! file_exists($manifestPath) || ! file_exists($zipPath)) {
return true;
}
$manifest = $this->integrityChecker->readManifest($outputPath);
if ($manifest === null) {
return true;
}
if (file_exists($composerJsonPath)) {
$currentHash = $this->integrityChecker->computeFileHash($composerJsonPath);
if (($manifest['composer_json_sha256'] ?? null) !== $currentHash) {
return true;
}
}
$composerLockPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.lock';
if (file_exists($composerLockPath)) {
$currentHash = $this->integrityChecker->computeFileHash($composerLockPath);
if (($manifest['composer_lock_sha256'] ?? null) !== $currentHash) {
return true;
}
}
return false;
}
/**
* 빌드 실행.
*
* @param string $sourcePath composer.json, composer.lock, vendor/ 를 읽을 경로 (활성 디렉토리)
* @param string $outputPath vendor-bundle.zip 과 vendor-bundle.json 을 쓸 경로 (_bundled 또는 코어는 sourcePath 와 동일)
* @param string $target 라벨용 대상 식별자 (예: 'core', 'module:sirsoft-ecommerce')
* @param bool $force 해시 체크 무시 강제 재빌드
*/
private function build(string $sourcePath, string $outputPath, string $target, bool $force): VendorBundleResult
{
// 전제 조건 검증
$composerJsonPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.json';
if (! file_exists($composerJsonPath)) {
throw new VendorInstallException(
errorKey: 'composer_json_not_found',
context: ['path' => $composerJsonPath],
);
}
$zipPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
$manifestPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::MANIFEST_FILENAME;
// 실제 외부 패키지 의존성이 없는 확장은 번들링 대상이 아님 — skip 처리
// (composer.json 에 `php: ^8.2` 런타임 제약만 있고 패키지 require 가 없는 경우)
if (! $this->hasExternalDependencies($composerJsonPath)) {
return new VendorBundleResult(
target: $target,
zipPath: $zipPath,
manifestPath: $manifestPath,
zipSize: 0,
packageCount: 0,
skipped: true,
reason: 'no-external-dependencies',
);
}
// stale 체크
if (! $force && ! $this->isStale($sourcePath, $outputPath)) {
$existingSize = file_exists($zipPath) ? (int) filesize($zipPath) : 0;
$existingManifest = $this->integrityChecker->readManifest($outputPath) ?? [];
$existingCount = (int) ($existingManifest['package_count'] ?? 0);
return new VendorBundleResult(
target: $target,
zipPath: $zipPath,
manifestPath: $manifestPath,
zipSize: $existingSize,
packageCount: $existingCount,
skipped: true,
reason: 'up-to-date',
);
}
// 기존 파일 제거
if (file_exists($zipPath)) {
@unlink($zipPath);
}
if (file_exists($manifestPath)) {
@unlink($manifestPath);
}
// === 스테이징 빌드 ===
// 개발 머신의 vendor/ 를 직접 사용하지 않고, composer install --no-dev 를
// 스테이징 디렉토리에서 새로 실행하여 dev 의존성과 완전히 분리된 번들을 생성한다.
$stagingDir = storage_path('app/vendor-bundle-staging/'.uniqid('build-', true));
File::ensureDirectoryExists($stagingDir, 0755);
try {
// 1. composer.json + composer.lock 을 스테이징으로 복사
File::copy($composerJsonPath, $stagingDir.DIRECTORY_SEPARATOR.'composer.json');
$sourceLockPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.lock';
if (file_exists($sourceLockPath)) {
File::copy($sourceLockPath, $stagingDir.DIRECTORY_SEPARATOR.'composer.lock');
}
// 2. 스테이징에서 composer install --no-dev 실행
$this->runComposerInstall($stagingDir, $target);
// 3. 생성된 vendor/ 검증
$stagedVendor = $stagingDir.DIRECTORY_SEPARATOR.'vendor';
if (! is_dir($stagedVendor)) {
throw new VendorInstallException(
errorKey: 'vendor_dir_not_found',
context: ['path' => $stagedVendor.' (composer install 후에도 vendor/ 가 생성되지 않음)'],
);
}
// 4. zip 생성 (EXCLUDE_PATTERNS 만 적용 — 화이트리스트 불필요)
[$zipSize, $fileCount] = $this->writeZip($stagedVendor, $zipPath);
// 5. manifest 작성 — 스테이징의 composer.lock 을 기준으로 패키지 목록 추출
$stagedLockPath = $stagingDir.DIRECTORY_SEPARATOR.'composer.lock';
$packages = file_exists($stagedLockPath)
? $this->collectPackages($stagedLockPath)
: [];
$manifest = [
'schema_version' => self::SCHEMA_VERSION,
'generated_at' => date('c'),
'generator' => 'g7 vendor-bundle:build',
'target' => $target,
// manifest 의 해시는 **소스** 의 composer.json/lock 기준 — 런타임에서
// 소스 디렉토리(또는 번들과 함께 배포된) composer.json 과 비교하여
// stale 여부를 감지한다.
'composer_json_sha256' => $this->integrityChecker->computeFileHash($composerJsonPath),
'composer_lock_sha256' => file_exists($sourceLockPath)
? $this->integrityChecker->computeFileHash($sourceLockPath)
: null,
'zip_sha256' => $this->integrityChecker->computeFileHash($zipPath),
'zip_size' => $zipSize,
'package_count' => count($packages),
'php_requirement' => $this->extractPhpRequirement($composerJsonPath),
'g7_version' => config('app.version'),
'packages' => $packages,
];
File::put($manifestPath, json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
Log::info('Vendor 번들 빌드 완료', [
'target' => $target,
'zip_size' => $zipSize,
'package_count' => count($packages),
'file_count' => $fileCount,
]);
return new VendorBundleResult(
target: $target,
zipPath: $zipPath,
manifestPath: $manifestPath,
zipSize: $zipSize,
packageCount: count($packages),
skipped: false,
reason: 'built',
);
} finally {
// 스테이징 정리 (실패/성공 무관)
if (File::isDirectory($stagingDir)) {
File::deleteDirectory($stagingDir);
}
}
}
/**
* 스테이징 디렉토리에서 `composer install --no-dev` 를 실행합니다.
*
* 테스트에서는 setComposerInstallRunner() 로 주입된 closure 를 대신 호출합니다.
*
* @throws VendorInstallException composer 미설치, 실행 실패 시
*/
private function runComposerInstall(string $stagingDir, string $target): void
{
// 테스트용 러너 우선
if ($this->composerInstallRunner !== null) {
($this->composerInstallRunner)($stagingDir);
return;
}
$detector = $this->environmentDetector ?? app(EnvironmentDetector::class);
if (! $detector->canExecuteComposer()) {
throw new VendorInstallException(
errorKey: 'composer_not_available_for_build',
);
}
$binary = $detector->findComposerBinary();
if ($binary === null) {
throw new VendorInstallException(
errorKey: 'composer_not_available_for_build',
);
}
$phpBinary = config('process.php_binary', 'php');
if (str_contains($binary, ' ')) {
$composerCmd = $binary;
} elseif (str_ends_with(strtolower($binary), '.phar')) {
$composerCmd = escapeshellarg($phpBinary).' '.escapeshellarg($binary);
} else {
$composerCmd = escapeshellarg($binary);
}
$command = $composerCmd.' install --no-dev --no-scripts --prefer-dist --no-interaction --no-progress 2>&1';
Log::info('vendor-bundle 빌드: composer install 시작', [
'target' => $target,
'staging' => $stagingDir,
]);
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = @proc_open($command, $descriptors, $pipes, $stagingDir);
if (! is_resource($process)) {
throw new VendorInstallException(
errorKey: 'bundle_build_composer_failed',
context: ['exit' => -1, 'message' => "proc_open 실패: {$stagingDir}"],
);
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0) {
throw new VendorInstallException(
errorKey: 'bundle_build_composer_failed',
context: ['exit' => $exitCode, 'message' => (string) $output],
);
}
Log::info('vendor-bundle 빌드: composer install 완료', [
'target' => $target,
'staging' => $stagingDir,
]);
}
/**
* vendor/ 디렉토리를 재귀적으로 zip에 쓰기.
*
* 스테이징에서 composer install --no-dev 로 새로 생성된 vendor/ 를 대상으로 하므로
* 화이트리스트 필터링은 불필요하며, EXCLUDE_PATTERNS (tests/, docs/ 등) 만 적용한다.
*
* @return array{0: int, 1: int} [zipSize, fileCount]
*/
private function writeZip(string $vendorPath, string $zipPath): array
{
if (! class_exists(\ZipArchive::class)) {
throw new VendorInstallException('zip_archive_not_available');
}
$zip = new \ZipArchive;
if ($zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'cannot create zip for writing: '.$zipPath],
);
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($vendorPath, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST
);
// 경로 정규화 — Windows 의 경로 구분자 차이를 제거하여 Linux 와 동일하게 처리
$normalizedVendorPath = rtrim(str_replace('\\', '/', $vendorPath), '/');
$vendorPathLen = strlen($normalizedVendorPath);
$fileCount = 0;
foreach ($iterator as $file) {
$realPath = $file->getRealPath();
if ($realPath === false) {
continue;
}
// vendor 루트로부터의 상대 경로 계산 (OS 일관)
$normalizedReal = str_replace('\\', '/', $realPath);
if (! str_starts_with($normalizedReal, $normalizedVendorPath.'/')) {
continue;
}
$subPath = substr($normalizedReal, $vendorPathLen + 1);
if ($subPath === '' || $subPath === false) {
continue;
}
$relativePath = 'vendor/'.$subPath;
if ($this->shouldExclude($relativePath)) {
continue;
}
if ($file->isDir()) {
$zip->addEmptyDir($relativePath);
} else {
$zip->addFile($realPath, $relativePath);
$fileCount++;
}
}
$zip->close();
$size = @filesize($zipPath) ?: 0;
return [$size, $fileCount];
}
/**
* 제외 패턴 검사.
*/
private function shouldExclude(string $relativePath): bool
{
$segments = explode('/', $relativePath);
foreach ($segments as $segment) {
if (in_array($segment, self::EXCLUDE_PATTERNS, true)) {
return true;
}
}
return false;
}
/**
* composer.lock 에서 설치된 패키지 목록 추출.
*
* @return array<int, array{name: string, version: string, type: string}>
*/
private function collectPackages(string $composerLockPath): array
{
$json = @file_get_contents($composerLockPath);
if ($json === false) {
return [];
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return [];
}
$packages = [];
foreach (($data['packages'] ?? []) as $package) {
if (! is_array($package)) {
continue;
}
$packages[] = [
'name' => (string) ($package['name'] ?? ''),
'version' => (string) ($package['version'] ?? ''),
'type' => (string) ($package['type'] ?? 'library'),
];
}
return $packages;
}
/**
* composer.json 에서 php 요구 버전 추출.
*/
private function extractPhpRequirement(string $composerJsonPath): ?string
{
$json = @file_get_contents($composerJsonPath);
if ($json === false) {
return null;
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return null;
}
return $data['require']['php'] ?? null;
}
/**
* composer.json 에 외부 패키지 의존성이 선언되어 있는지 확인합니다.
*
* 런타임 제약(php, ext-*)만 있는 경우 false 를 반환합니다.
* 이런 확장은 vendor 번들링 대상이 아니므로 skip 처리됩니다.
*/
private function hasExternalDependencies(string $composerJsonPath): bool
{
$json = @file_get_contents($composerJsonPath);
if ($json === false) {
return false;
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return false;
}
$require = $data['require'] ?? [];
if (! is_array($require) || empty($require)) {
return false;
}
foreach (array_keys($require) as $package) {
// php 버전 제약과 ext-* PHP 확장 제약은 외부 의존성이 아님
if ($package === 'php' || str_starts_with($package, 'ext-')) {
continue;
}
return true;
}
return false;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 설치 요청 컨텍스트.
*
* CLI/웹/API 모든 진입점에서 공통으로 사용되는 설치 파라미터 DTO.
*/
class VendorInstallContext
{
/**
* @param string $target 'core' | 'module' | 'plugin'
* @param string|null $identifier 코어는 null, 확장은 식별자
* @param string $sourceDir vendor 설치 소스 경로 (vendor-bundle.zip이 이 위치에 있어야 함)
* @param string $targetDir vendor/가 배치될 경로 (보통 sourceDir과 동일)
* @param VendorMode $requestedMode 사용자 요청 모드
* @param VendorMode|null $previousMode 업데이트 시 이전 설치 모드 (DB에서 조회)
* @param string|null $composerBinaryHint composer 바이너리 경로 힌트
* @param bool $noDev composer --no-dev 플래그
* @param string $operation 'install' | 'update'
*/
public function __construct(
public readonly string $target,
public readonly ?string $identifier,
public readonly string $sourceDir,
public readonly string $targetDir,
public readonly VendorMode $requestedMode = VendorMode::Auto,
public readonly ?VendorMode $previousMode = null,
public readonly ?string $composerBinaryHint = null,
public readonly bool $noDev = true,
public readonly string $operation = 'install',
) {}
public function isCore(): bool
{
return $this->target === 'core';
}
public function label(): string
{
return $this->isCore()
? 'core'
: sprintf('%s:%s', $this->target, $this->identifier);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 설치 결과 DTO.
*/
class VendorInstallResult
{
/**
* @param VendorMode $mode 실제로 사용된 모드 (auto가 resolver에 의해 해석된 결과)
* @param string $strategy 'composer' | 'bundled' | 'skipped'
* @param int $packageCount 설치된 패키지 수 (bundled일 때 manifest 기준)
* @param float $durationSeconds 설치 소요 시간
* @param array<string, mixed> $details 부가 정보 (composer 출력, bundle 크기 등)
*/
public function __construct(
public readonly VendorMode $mode,
public readonly string $strategy,
public readonly int $packageCount = 0,
public readonly float $durationSeconds = 0.0,
public readonly array $details = [],
) {}
public static function skipped(VendorMode $mode, string $reason): self
{
return new self(
mode: $mode,
strategy: 'skipped',
details: ['skip_reason' => $reason],
);
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
namespace App\Extension\Vendor;
/**
* vendor-bundle.json 기반 번들 파일의 무결성을 검증합니다.
*
* 검증 항목:
* - vendor-bundle.zip 존재 + SHA256 일치
* - vendor-bundle.json 존재 + 파싱 가능 + 스키마 버전 지원
* - composer.json/composer.lock SHA256 일치 (소스 디렉토리에 존재 시)
*/
class VendorIntegrityChecker
{
/**
* 지원하는 manifest 스키마 버전 목록.
*/
public const SUPPORTED_SCHEMA_VERSIONS = ['1.0'];
public const MANIFEST_FILENAME = 'vendor-bundle.json';
public const ZIP_FILENAME = 'vendor-bundle.zip';
/**
* 주어진 소스 디렉토리의 번들 무결성을 검증합니다.
*
* @param string $sourceDir vendor-bundle.zip 이 위치한 디렉토리
*/
public function verify(string $sourceDir): IntegrityResult
{
$zipPath = $sourceDir.DIRECTORY_SEPARATOR.self::ZIP_FILENAME;
$manifestPath = $sourceDir.DIRECTORY_SEPARATOR.self::MANIFEST_FILENAME;
// 1. 파일 존재 확인
if (! file_exists($zipPath)) {
return IntegrityResult::invalid(['bundle_zip_missing']);
}
if (! file_exists($manifestPath)) {
return IntegrityResult::invalid(['bundle_manifest_missing']);
}
// 2. manifest 파싱
$manifestJson = @file_get_contents($manifestPath);
if ($manifestJson === false) {
return IntegrityResult::invalid(['bundle_manifest_invalid']);
}
try {
$manifest = json_decode($manifestJson, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return IntegrityResult::invalid(['bundle_manifest_invalid']);
}
if (! is_array($manifest)) {
return IntegrityResult::invalid(['bundle_manifest_invalid']);
}
// 3. 스키마 버전 확인
$schemaVersion = $manifest['schema_version'] ?? null;
if (! in_array($schemaVersion, self::SUPPORTED_SCHEMA_VERSIONS, true)) {
return IntegrityResult::invalid(['bundle_schema_unsupported'], $manifest);
}
$errors = [];
$warnings = [];
// 4. zip SHA256 검증
$expectedZipHash = $manifest['zip_sha256'] ?? null;
if ($expectedZipHash === null) {
$errors[] = 'bundle_manifest_invalid';
} else {
$actualZipHash = $this->computeFileHash($zipPath);
if (! hash_equals((string) $expectedZipHash, $actualZipHash)) {
$errors[] = 'zip_hash_mismatch';
}
}
// 5. composer.json/lock 해시 비교 (소스에 존재할 때만)
$composerJsonPath = $sourceDir.DIRECTORY_SEPARATOR.'composer.json';
if (file_exists($composerJsonPath)) {
$expected = $manifest['composer_json_sha256'] ?? null;
if ($expected !== null) {
$actual = $this->computeFileHash($composerJsonPath);
if (! hash_equals((string) $expected, $actual)) {
$errors[] = 'composer_json_sha_mismatch';
}
}
}
$composerLockPath = $sourceDir.DIRECTORY_SEPARATOR.'composer.lock';
if (file_exists($composerLockPath)) {
$expected = $manifest['composer_lock_sha256'] ?? null;
if ($expected !== null) {
$actual = $this->computeFileHash($composerLockPath);
if (! hash_equals((string) $expected, $actual)) {
$errors[] = 'composer_lock_sha_mismatch';
}
}
}
if (! empty($errors)) {
return IntegrityResult::invalid($errors, $manifest);
}
return IntegrityResult::valid($manifest, $warnings);
}
/**
* 파일의 SHA256 해시를 계산합니다.
*/
public function computeFileHash(string $path): string
{
return hash_file('sha256', $path) ?: '';
}
/**
* manifest만 파싱하여 반환 (검증 없이 메타 조회용).
*
* @return array<string, mixed>|null
*/
public function readManifest(string $sourceDir): ?array
{
$path = $sourceDir.DIRECTORY_SEPARATOR.self::MANIFEST_FILENAME;
if (! file_exists($path)) {
return null;
}
$json = @file_get_contents($path);
if ($json === false) {
return null;
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return null;
}
return is_array($data) ? $data : null;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 설치 모드.
*
* - Auto: composer 사용 가능 시 composer, 불가 시 bundled
* - Composer: 강제 composer 실행 (불가 시 예외)
* - Bundled: 강제 vendor-bundle.zip 추출 (zip 없으면 예외)
*/
enum VendorMode: string
{
case Auto = 'auto';
case Composer = 'composer';
case Bundled = 'bundled';
/**
* 다국어 라벨.
*/
public function label(): string
{
return match ($this) {
self::Auto => __('vendor.mode.auto'),
self::Composer => __('vendor.mode.composer'),
self::Bundled => __('vendor.mode.bundled'),
};
}
/**
* 문자열에서 안전하게 변환 (null/auto 폴백).
*/
public static function fromStringOrAuto(?string $value): self
{
if ($value === null || $value === '') {
return self::Auto;
}
return self::tryFrom($value) ?? self::Auto;
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
namespace App\Extension\Vendor;
use App\Extension\Vendor\Exceptions\VendorInstallException;
use Illuminate\Support\Facades\Log;
/**
* Vendor 설치 진입점.
*
* CLI / 웹 인스톨러 / Admin API 모든 경로가 최종적으로 이 클래스를 경유합니다.
* 모드를 결정(resolveMode)하고 적절한 전략으로 위임합니다.
*
* Composer 전략은 외부 콜백(executeComposer)에 위임 — 코어(CoreUpdateService)와
* 확장(ExtensionManager)이 각자 기존 composer 실행 로직을 전달하는 형태.
*/
class VendorResolver
{
public function __construct(
private readonly EnvironmentDetector $environmentDetector,
private readonly VendorIntegrityChecker $integrityChecker,
private readonly VendorBundleInstaller $bundleInstaller,
) {}
/**
* 사용할 Vendor 모드를 결정합니다.
*
* 우선순위:
* 1. 명시적 요청 모드 (composer/bundled) → 그대로 사용
* 2. 업데이트 시 이전 설치 모드 상속 (auto가 아닐 때)
* 3. 전역 기본값 config('app.install.default_vendor_mode')
* 4. 환경 감지: composer 가능하면 composer, 불가 시 번들 존재 여부 확인
*
* @throws VendorInstallException
*/
public function resolveMode(VendorInstallContext $ctx): VendorMode
{
// 1. 명시적 지정
if ($ctx->requestedMode !== VendorMode::Auto) {
return $ctx->requestedMode;
}
// 2. 업데이트 시 이전 모드 상속
if ($ctx->operation === 'update'
&& $ctx->previousMode !== null
&& $ctx->previousMode !== VendorMode::Auto
) {
return $ctx->previousMode;
}
// 3. 전역 기본값
$configured = config('app.install.default_vendor_mode', 'auto');
if ($configured !== 'auto') {
$parsed = VendorMode::tryFrom((string) $configured);
if ($parsed !== null && $parsed !== VendorMode::Auto) {
return $parsed;
}
}
// 4. auto → 환경 감지
if ($this->environmentDetector->canExecuteComposer($ctx->composerBinaryHint)) {
return VendorMode::Composer;
}
// 5. composer 불가 → 번들 존재 확인
$zipPath = $ctx->sourceDir.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
if (file_exists($zipPath)) {
return VendorMode::Bundled;
}
throw new VendorInstallException('no_vendor_strategy_available');
}
/**
* Vendor 설치를 수행합니다.
*
* @param VendorInstallContext $ctx 설치 컨텍스트
* @param callable|null $composerExecutor Composer 모드일 때 실행될 콜백
* 시그니처: fn(VendorInstallContext $ctx): VendorInstallResult
*
* @throws VendorInstallException
*/
public function install(VendorInstallContext $ctx, ?callable $composerExecutor = null): VendorInstallResult
{
$mode = $this->resolveMode($ctx);
Log::info('Vendor 설치 모드 결정됨', [
'target' => $ctx->label(),
'requested_mode' => $ctx->requestedMode->value,
'resolved_mode' => $mode->value,
'operation' => $ctx->operation,
]);
$this->validateModeFeasibility($mode, $ctx, $composerExecutor);
return match ($mode) {
VendorMode::Composer => $this->executeComposer($ctx, $composerExecutor),
VendorMode::Bundled => $this->executeBundle($ctx),
VendorMode::Auto => throw new VendorInstallException('no_vendor_strategy_available'),
};
}
/**
* 선택된 모드가 실제로 가능한지 사전 검증합니다.
*
* @throws VendorInstallException
*/
private function validateModeFeasibility(
VendorMode $mode,
VendorInstallContext $ctx,
?callable $composerExecutor,
): void {
if ($mode === VendorMode::Composer) {
if (! $this->environmentDetector->canExecuteComposer($ctx->composerBinaryHint)) {
throw new VendorInstallException('composer_not_available');
}
if ($composerExecutor === null) {
throw new VendorInstallException(
errorKey: 'composer_execution_failed',
context: ['message' => 'composer executor callback not provided'],
);
}
return;
}
if ($mode === VendorMode::Bundled) {
$zipPath = $ctx->sourceDir.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
if (! file_exists($zipPath)) {
throw new VendorInstallException(
errorKey: 'bundle_zip_missing',
context: ['path' => $zipPath],
);
}
$integrity = $this->integrityChecker->verify($ctx->sourceDir);
if (! $integrity->valid) {
throw new VendorInstallException(
errorKey: 'bundle_integrity_failed',
context: ['details' => implode(', ', $integrity->errorMessages())],
);
}
}
}
private function executeComposer(VendorInstallContext $ctx, callable $composerExecutor): VendorInstallResult
{
$startTime = microtime(true);
$result = $composerExecutor($ctx);
$duration = microtime(true) - $startTime;
if ($result instanceof VendorInstallResult) {
return $result;
}
// 콜백이 단순 true/void를 반환한 경우 — 기본 결과 생성
return new VendorInstallResult(
mode: VendorMode::Composer,
strategy: 'composer',
packageCount: 0,
durationSeconds: $duration,
details: ['raw_result' => $result],
);
}
private function executeBundle(VendorInstallContext $ctx): VendorInstallResult
{
return $this->bundleInstaller->install($ctx->sourceDir, $ctx->targetDir);
}
}