v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -8,14 +8,15 @@ use App\Contracts\Repositories\UserConsentRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Enums\ConsentType;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Exceptions\Auth\AccountLockedException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Laravel\Sanctum\PersonalAccessToken;
|
||||
|
||||
class AuthService
|
||||
{
|
||||
@@ -88,7 +89,7 @@ class AuthService
|
||||
* @return array 사용자 정보와 토큰을 포함한 배열
|
||||
*
|
||||
* @throws ValidationException 인증 정보가 올바르지 않을 때
|
||||
* @throws \App\Exceptions\Auth\AccountLockedException 계정이 잠겨 있을 때
|
||||
* @throws AccountLockedException 계정이 잠겨 있을 때
|
||||
*/
|
||||
public function login(string $email, string $password): array
|
||||
{
|
||||
@@ -99,7 +100,7 @@ class AuthService
|
||||
$candidate = $this->userRepository->findByEmail($email);
|
||||
if ($candidate !== null && $this->userRepository->isLocked($candidate)) {
|
||||
$remaining = max(1, (int) ceil(now()->diffInSeconds($candidate->locked_until, false) / 60));
|
||||
throw new \App\Exceptions\Auth\AccountLockedException(
|
||||
throw new AccountLockedException(
|
||||
lockedUntil: $candidate->locked_until,
|
||||
remainingMinutes: $remaining,
|
||||
);
|
||||
@@ -222,6 +223,9 @@ class AuthService
|
||||
'user_agent' => request()->userAgent(),
|
||||
'signup_stage' => 'after_create',
|
||||
'verification_token' => $data['verification_token'] ?? null,
|
||||
// 모듈이 동적 추가한 가입 필드(예: 결제 통화)를 리스너가 읽을 수 있도록 검증된 가입 데이터 전달.
|
||||
// request() 직접 접근을 피하기 위해 Service 가 도메인 객체로 넘긴다(Listener 규율).
|
||||
'registration_data' => $data,
|
||||
]);
|
||||
|
||||
return [
|
||||
@@ -245,7 +249,7 @@ class AuthService
|
||||
$currentToken = $user->currentAccessToken();
|
||||
|
||||
// Case 1: 토큰만 보낸 경우 - currentAccessToken()이 PersonalAccessToken 반환
|
||||
if ($currentToken instanceof \Laravel\Sanctum\PersonalAccessToken) {
|
||||
if ($currentToken instanceof PersonalAccessToken) {
|
||||
$currentToken->delete();
|
||||
}
|
||||
// Case 2: 쿠키 + 토큰을 함께 보낸 경우 또는 TransientToken
|
||||
@@ -294,7 +298,7 @@ class AuthService
|
||||
$currentToken = $user->currentAccessToken();
|
||||
|
||||
// PersonalAccessToken만 삭제 (TransientToken은 세션 기반이므로 삭제 불필요)
|
||||
if ($currentToken instanceof \Laravel\Sanctum\PersonalAccessToken) {
|
||||
if ($currentToken instanceof PersonalAccessToken) {
|
||||
$currentToken->delete();
|
||||
}
|
||||
|
||||
@@ -351,9 +355,9 @@ class AuthService
|
||||
|
||||
// 리셋 URL 생성 (extract_data 필터에서 사용)
|
||||
$resetPath = $redirectPrefix
|
||||
? '/' . $redirectPrefix . '/reset-password'
|
||||
? '/'.$redirectPrefix.'/reset-password'
|
||||
: '/reset-password';
|
||||
$resetUrl = config('app.url') . $resetPath . '?' . http_build_query([
|
||||
$resetUrl = config('app.url').$resetPath.'?'.http_build_query([
|
||||
'token' => $token,
|
||||
'email' => $user->email,
|
||||
]);
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\UpgradeStepInterface;
|
||||
use App\Contracts\Repositories\PermissionRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\PermissionType;
|
||||
use App\Exceptions\CoreUpdateOperationException;
|
||||
use App\Exceptions\UpgradeHandoffException;
|
||||
use App\Extension\AbstractUpgradeStep;
|
||||
use App\Extension\CoreVersionChecker;
|
||||
use App\Extension\Helpers\ChangelogParser;
|
||||
use App\Extension\Helpers\CoreBackupHelper;
|
||||
@@ -910,7 +912,12 @@ class CoreUpdateService
|
||||
$onProgress?->__invoke('apply', $target);
|
||||
|
||||
if (File::isDirectory($src)) {
|
||||
FilePermissionHelper::copyDirectory($src, $dest, $onProgress, $excludes, removeOrphans: true);
|
||||
// `{domain}/_bundled` 타깃은 최상위 한 레벨의 orphan 을 보존한다 — 사용자가
|
||||
// `_bundled/` 바로 아래에 직접 만든 커스텀 확장 디렉토리/파일이 코어 업데이트
|
||||
// 소스(번들 확장만 포함)에 없다는 이유로 삭제되던 결함 차단.
|
||||
// 번들 확장 디렉토리 *내부* stale 정리는 그대로 유지된다.
|
||||
$preserveTopLevelOrphans = str_ends_with($this->normalizeRelativePath($target), '_bundled');
|
||||
FilePermissionHelper::copyDirectory($src, $dest, $onProgress, $excludes, removeOrphans: true, preserveTopLevelOrphans: $preserveTopLevelOrphans);
|
||||
} else {
|
||||
File::ensureDirectoryExists(dirname($dest));
|
||||
FilePermissionHelper::copyFile($src, $dest);
|
||||
@@ -1383,7 +1390,7 @@ class CoreUpdateService
|
||||
|
||||
// 3. 역할-권한 할당 동기화 (user_overrides 보호)
|
||||
// 코어: core/core 소유 전체 권한을 diff 범위로 사용해 이관된 구 식별자도 detach 가능
|
||||
$allCorePermIdentifiers = app(\App\Contracts\Repositories\PermissionRepositoryInterface::class)
|
||||
$allCorePermIdentifiers = app(PermissionRepositoryInterface::class)
|
||||
->getByExtension(ExtensionOwnerType::Core, 'core')
|
||||
->pluck('identifier')
|
||||
->all();
|
||||
@@ -1514,7 +1521,7 @@ class CoreUpdateService
|
||||
|
||||
try {
|
||||
if (Schema::hasTable('notification_definitions')) {
|
||||
(new NotificationDefinitionSeeder())->run();
|
||||
(new NotificationDefinitionSeeder)->run();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::channel('upgrade')->warning('reloadCoreConfigAndResync: 알림 정의 재시딩 실패', ['error' => $e->getMessage()]);
|
||||
@@ -1522,7 +1529,7 @@ class CoreUpdateService
|
||||
|
||||
try {
|
||||
if (Schema::hasTable('identity_policies')) {
|
||||
(new IdentityPolicySeeder())->run();
|
||||
(new IdentityPolicySeeder)->run();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::channel('upgrade')->warning('reloadCoreConfigAndResync: IDV 정책 재시딩 실패', ['error' => $e->getMessage()]);
|
||||
@@ -1530,7 +1537,7 @@ class CoreUpdateService
|
||||
|
||||
try {
|
||||
if (Schema::hasTable('identity_message_definitions') && Schema::hasTable('identity_message_templates')) {
|
||||
(new IdentityMessageDefinitionSeeder())->run();
|
||||
(new IdentityMessageDefinitionSeeder)->run();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::channel('upgrade')->warning('reloadCoreConfigAndResync: IDV 메시지 정의 재시딩 실패', ['error' => $e->getMessage()]);
|
||||
@@ -1557,8 +1564,8 @@ class CoreUpdateService
|
||||
// 부모 in-process fallback 진입 시 stale 메모리 가드.
|
||||
//
|
||||
// 현재 메모리의 `config('app.version')` 이 toVersion 보다 낮으면 부모는 stale 코드를
|
||||
// 보유한 채 step 을 실행 중. upgrade step 안에서 신규 메서드 호출 시 fatal 위험
|
||||
// (이슈 #28 의 발현 메커니즘). `spawn_failure_mode` 와 연동하여 abort/fallback 분기.
|
||||
// 보유한 채 step 을 실행 중. upgrade step 안에서 신규 메서드 호출 시 fatal 위험.
|
||||
// `spawn_failure_mode` 와 연동하여 abort/fallback 분기.
|
||||
//
|
||||
// spawn 자식 (ExecuteUpgradeStepsCommand) 의 경우 spawn env 의 APP_VERSION=toVersion
|
||||
// 이 적용된 채 새 프로세스에서 부팅되므로 memoryVersion === toVersion → 가드 미발동.
|
||||
@@ -1633,7 +1640,7 @@ class CoreUpdateService
|
||||
// 미상속 시점에 즉시 throw → core:update 전체 중단 → 상위 백업 복원.
|
||||
// 상세: docs/extension/upgrade-step-guide.md §12
|
||||
if (version_compare($version, '7.0.0-beta.5', '>=')
|
||||
&& ! $instance instanceof \App\Extension\AbstractUpgradeStep) {
|
||||
&& ! $instance instanceof AbstractUpgradeStep) {
|
||||
throw new CoreUpdateOperationException(sprintf(
|
||||
'Upgrade step %s must extend App\\Extension\\AbstractUpgradeStep '
|
||||
.'(introduced in 7.0.0-beta.5). See docs/extension/upgrade-step-guide.md §12.',
|
||||
@@ -1881,7 +1888,7 @@ class CoreUpdateService
|
||||
*/
|
||||
private function detectBundledUpdatesFor(string $tableAndDir, string $manifestName): array
|
||||
{
|
||||
if (! \Illuminate\Support\Facades\Schema::hasTable($tableAndDir)) {
|
||||
if (! Schema::hasTable($tableAndDir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -1924,7 +1931,7 @@ class CoreUpdateService
|
||||
* 대상 경로는 config('app.update.restore_ownership') 에 정의된 목록.
|
||||
* chown 미지원 환경(Windows 등) 은 빈 배열을 반환한다.
|
||||
*
|
||||
* @return array<string, array{owner:int|false, group:int|false}> target => {owner, group}
|
||||
* @return array<string, array{owner:int|false, group:int|false}> target => {owner, group}
|
||||
*/
|
||||
public function snapshotOwnership(): array
|
||||
{
|
||||
@@ -2116,7 +2123,6 @@ class CoreUpdateService
|
||||
* @param array<string, array{owner:int|false, group:int|false}> $snapshot snapshotOwnership() 결과
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @param array<string, array{owner:int|false, group:int|false, perms:int|null, is_dir:bool, is_link:bool}> $detailedSnapshot snapshotOwnershipDetailed() 결과 (선택)
|
||||
* @return void
|
||||
*/
|
||||
public function restoreOwnership(array $snapshot, ?\Closure $onProgress = null, array $detailedSnapshot = []): void
|
||||
{
|
||||
@@ -2204,6 +2210,16 @@ class CoreUpdateService
|
||||
'storage',
|
||||
'bootstrap/cache',
|
||||
]);
|
||||
// 백업 디렉토리는 운영자 정책 보존 대상이 아니라 업데이트/롤백이 생성·소비·삭제하는
|
||||
// 임시 산출물이다. sudo 업데이트가 이들을 g-w(0755) 로 만들어 두면 이후 www-data 가
|
||||
// 그 안에 백업을 mkdir 하지 못한다(mkdir(): Permission denied). 따라서 이 경로들은
|
||||
// force=true 로 정상화하여 루트가 g-w 라도 g+w 승격 후 하위까지 재귀 전파한다.
|
||||
// (그 외 경로는 force=false — 운영자가 의도적으로 차단한 그룹 쓰기 정책을 보존.)
|
||||
$forceGroupWritablePaths = [
|
||||
'storage/app/extension_backups',
|
||||
'storage/app/core_backups',
|
||||
];
|
||||
|
||||
$groupWritableChanged = 0;
|
||||
foreach ($groupWritableTargets as $target) {
|
||||
$path = base_path($target);
|
||||
@@ -2211,8 +2227,10 @@ class CoreUpdateService
|
||||
continue;
|
||||
}
|
||||
|
||||
$force = in_array($target, $forceGroupWritablePaths, true);
|
||||
|
||||
$onProgress?->__invoke('group_writable', $target);
|
||||
$report = FilePermissionHelper::syncGroupWritabilityDetailed($path);
|
||||
$report = FilePermissionHelper::syncGroupWritabilityDetailed($path, $force);
|
||||
$groupWritableChanged += $report['changed'];
|
||||
|
||||
if ($report['failed'] > 0) {
|
||||
@@ -2251,7 +2269,6 @@ class CoreUpdateService
|
||||
* - 실패 항목 누적 → `lastPermissionWarnings` 에 'kind' => 'detailed' 로 기록
|
||||
*
|
||||
* @param array<string, array{owner:int|false, group:int|false, perms:int|null, is_dir:bool, is_link:bool}> $detailedSnapshot
|
||||
* @param \Closure|null $onProgress
|
||||
*/
|
||||
private function restoreFromDetailedSnapshot(array $detailedSnapshot, ?\Closure $onProgress = null): void
|
||||
{
|
||||
@@ -2428,5 +2445,4 @@ class CoreUpdateService
|
||||
{
|
||||
return config('core.menus', []);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,11 +4,17 @@ namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\ActivityLogRepositoryInterface;
|
||||
use App\Contracts\Repositories\LanguagePackRepositoryInterface;
|
||||
use App\Contracts\Repositories\NotificationLogRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\NotificationLog;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* 대시보드 서비스
|
||||
@@ -21,7 +27,11 @@ class DashboardService
|
||||
private UserRepositoryInterface $userRepository,
|
||||
private ActivityLogRepositoryInterface $activityLogRepository,
|
||||
private ModuleManagerInterface $moduleManager,
|
||||
private PluginManagerInterface $pluginManager
|
||||
private PluginManagerInterface $pluginManager,
|
||||
private NotificationLogRepositoryInterface $notificationLogRepository,
|
||||
private TemplateManagerInterface $templateManager,
|
||||
private LanguagePackRepositoryInterface $languagePackRepository,
|
||||
private LanguagePackService $languagePackService
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -38,6 +48,8 @@ class DashboardService
|
||||
'total_users' => $this->getUserStats(),
|
||||
'installed_modules' => $this->getModuleStats(),
|
||||
'active_plugins' => $this->getPluginStats(),
|
||||
'installed_templates' => $this->getTemplateStats(),
|
||||
'language_packs' => $this->getLanguagePackStats(),
|
||||
'system_status' => $this->getSystemStatus(),
|
||||
];
|
||||
|
||||
@@ -109,6 +121,50 @@ class DashboardService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 통계를 조회합니다.
|
||||
*
|
||||
* 활성 템플릿은 타입(admin/user)별로 1개씩 지정되므로, 활성 수는
|
||||
* 활성 템플릿이 지정된 타입 수와 같습니다.
|
||||
*
|
||||
* @return array{total: int, active: int} 템플릿 통계 배열
|
||||
*/
|
||||
private function getTemplateStats(): array
|
||||
{
|
||||
$allTemplates = $this->templateManager->getAllTemplates();
|
||||
|
||||
$activeCount = 0;
|
||||
foreach (['admin', 'user'] as $type) {
|
||||
if ($this->templateManager->getActiveTemplate($type) !== null) {
|
||||
$activeCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'total' => count($allTemplates),
|
||||
'active' => $activeCount,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 언어팩 통계를 조회합니다.
|
||||
*
|
||||
* 활성 = 현재 활성화된 언어팩 레코드 수,
|
||||
* 전체 = 활성 + 미설치 번들 팩(설치 가능 후보) 수.
|
||||
*
|
||||
* @return array{total: int, active: int} 언어팩 통계 배열
|
||||
*/
|
||||
private function getLanguagePackStats(): array
|
||||
{
|
||||
$activeCount = $this->languagePackRepository->getActivePacks()->count();
|
||||
$uninstalledBundledCount = $this->languagePackService->getUninstalledBundledPacks()->count();
|
||||
|
||||
return [
|
||||
'total' => $activeCount + $uninstalledBundledCount,
|
||||
'active' => $activeCount,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 상태를 조회합니다.
|
||||
*
|
||||
@@ -150,19 +206,84 @@ class DashboardService
|
||||
*/
|
||||
public function getSystemResources(): array
|
||||
{
|
||||
// IDV 정책 가드 지점 (계획서 #297 — 민감 관리자 조회 훅 커버리지)
|
||||
// IDV 정책 가드 지점 (민감 관리자 조회 훅 커버리지)
|
||||
HookManager::doAction('core.dashboard.before_resources');
|
||||
|
||||
// 각 probe 를 개별 격리한다 (공개#40).
|
||||
// 일부 호스팅(open_basedir 제한, disable_functions, /proc 미접근)에서 한 probe 의
|
||||
// 실패(warning → ErrorException)가 리소스 조회 전체를 500 으로 떨어뜨리지 않도록,
|
||||
// probe 별 가드(레이어 a) 위에 safeProbe 격리(레이어 b)를 추가한다.
|
||||
$resources = [
|
||||
'cpu' => $this->getCpuUsage(),
|
||||
'memory' => $this->getMemoryUsage(),
|
||||
'disk' => $this->getDiskUsage(),
|
||||
'cpu' => $this->safeProbe(fn () => $this->getCpuUsage(), $this->fallbackCpu()),
|
||||
'memory' => $this->safeProbe(fn () => $this->getMemoryUsage(), $this->fallbackMemory()),
|
||||
'disk' => $this->safeProbe(fn () => $this->getDiskUsage(), $this->fallbackDisk()),
|
||||
];
|
||||
|
||||
// 훅을 통한 리소스 정보 확장 지원
|
||||
return HookManager::applyFilters('core.dashboard.resources', $resources);
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 리소스 probe 를 안전하게 실행합니다.
|
||||
*
|
||||
* probe 가 예외(ErrorException·Error 포함)를 던지면 전파하지 않고 폴백값을 반환합니다.
|
||||
* 시스템 리소스 수집 실패가 결코 대시보드 리소스 조회 전체를 500 으로 만들지 않게 합니다.
|
||||
*
|
||||
* @param callable $cb 실행할 probe 콜백
|
||||
* @param array $fallback 실패 시 반환할 폴백 구조
|
||||
* @return array probe 결과 또는 폴백
|
||||
*/
|
||||
protected function safeProbe(callable $cb, array $fallback): array
|
||||
{
|
||||
try {
|
||||
return $cb();
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('대시보드 시스템 리소스 수집 실패', ['error' => $e->getMessage()]);
|
||||
|
||||
return $fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CPU 수집 불가 시 폴백 구조를 반환합니다.
|
||||
*
|
||||
* @return array CPU 폴백 (percentage 0, color gray)
|
||||
*/
|
||||
protected function fallbackCpu(): array
|
||||
{
|
||||
return ['percentage' => 0, 'color' => 'gray'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 메모리 수집 불가 시 폴백 구조를 반환합니다.
|
||||
*
|
||||
* @return array 메모리 폴백 (percentage 0, used/total "알 수 없음", color gray)
|
||||
*/
|
||||
protected function fallbackMemory(): array
|
||||
{
|
||||
return [
|
||||
'percentage' => 0,
|
||||
'used' => __('common.unknown'),
|
||||
'total' => __('common.unknown'),
|
||||
'color' => 'gray',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 디스크 수집 불가 시 폴백 구조를 반환합니다.
|
||||
*
|
||||
* @return array 디스크 폴백 (percentage 0, used/total "알 수 없음", color gray)
|
||||
*/
|
||||
protected function fallbackDisk(): array
|
||||
{
|
||||
return [
|
||||
'percentage' => 0,
|
||||
'used' => __('common.unknown'),
|
||||
'total' => __('common.unknown'),
|
||||
'color' => 'gray',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* CPU 사용률을 조회합니다.
|
||||
*
|
||||
@@ -178,8 +299,9 @@ class DashboardService
|
||||
// Linux/Unix: /proc/stat에서 CPU 사용률 계산
|
||||
if (function_exists('sys_getloadavg')) {
|
||||
$load = sys_getloadavg();
|
||||
// 1분 평균 로드를 CPU 코어 수로 나눠서 백분율로 변환
|
||||
$cores = (int) shell_exec('nproc 2>/dev/null') ?: 1;
|
||||
// 1분 평균 로드를 CPU 코어 수로 나눠서 백분율로 변환.
|
||||
// disable_functions 에 shell_exec 가 있으면 호출 자체가 warning → 가드 (공개#40).
|
||||
$cores = function_exists('shell_exec') ? ((int) @shell_exec('nproc 2>/dev/null') ?: 1) : 1;
|
||||
$percentage = min(100, round(($load[0] / $cores) * 100));
|
||||
}
|
||||
}
|
||||
@@ -234,15 +356,19 @@ class DashboardService
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
[$total, $used] = $this->getWindowsMemoryUsage();
|
||||
} else {
|
||||
// Linux: /proc/meminfo에서 메모리 정보 조회
|
||||
if (file_exists('/proc/meminfo')) {
|
||||
$memInfo = file_get_contents('/proc/meminfo');
|
||||
if (preg_match('/MemTotal:\s+(\d+)/', $memInfo, $matches)) {
|
||||
$total = $matches[1] * 1024;
|
||||
}
|
||||
if (preg_match('/MemAvailable:\s+(\d+)/', $memInfo, $matches)) {
|
||||
$available = $matches[1] * 1024;
|
||||
$used = $total - $available;
|
||||
// Linux: /proc/meminfo에서 메모리 정보 조회.
|
||||
// open_basedir 제한 환경에서 file_get_contents 가 warning → ErrorException 이 되지
|
||||
// 않도록 is_readable 가드 + @ 억제 + false 체크 (공개#40, SettingsService::getMemoryUsage 동형).
|
||||
if (PHP_OS_FAMILY === 'Linux' && is_readable('/proc/meminfo')) {
|
||||
$memInfo = @file_get_contents('/proc/meminfo');
|
||||
if ($memInfo !== false) {
|
||||
if (preg_match('/MemTotal:\s+(\d+)/', $memInfo, $matches)) {
|
||||
$total = $matches[1] * 1024;
|
||||
}
|
||||
if (preg_match('/MemAvailable:\s+(\d+)/', $memInfo, $matches)) {
|
||||
$available = $matches[1] * 1024;
|
||||
$used = $total - $available;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,8 +444,12 @@ class DashboardService
|
||||
{
|
||||
$path = PHP_OS_FAMILY === 'Windows' ? 'C:' : '/';
|
||||
|
||||
$total = disk_total_space($path) ?: 0;
|
||||
$free = disk_free_space($path) ?: 0;
|
||||
// open_basedir 로 '/' 가 제한된 환경에서 disk_*_space 가 warning → ErrorException 이
|
||||
// 되지 않도록 @ 억제 + numeric 체크 (공개#40). ?: 0 폴백은 예외 승격 후엔 무력하므로 @ 필수.
|
||||
$totalRaw = @disk_total_space($path);
|
||||
$freeRaw = @disk_free_space($path);
|
||||
$total = is_numeric($totalRaw) ? (float) $totalRaw : 0;
|
||||
$free = is_numeric($freeRaw) ? (float) $freeRaw : 0;
|
||||
$used = $total - $free;
|
||||
|
||||
$percentage = $total > 0 ? round(($used / $total) * 100) : 0;
|
||||
@@ -406,7 +536,7 @@ class DashboardService
|
||||
/**
|
||||
* 활동 액션에 따른 아이콘을 반환합니다.
|
||||
*
|
||||
* @param string|null $action 액션 문자열
|
||||
* @param string|null $action 액션 문자열
|
||||
* @return string 아이콘명
|
||||
*/
|
||||
private function getActivityIcon(?string $action): string
|
||||
@@ -440,4 +570,31 @@ class DashboardService
|
||||
{
|
||||
return HookManager::applyFilters('core.dashboard.alerts', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 발송된 알림 이력을 조회합니다.
|
||||
*
|
||||
* notification_logs 테이블에서 발송 시각 최신순으로 조회하여
|
||||
* 대시보드 "최근 알림" 카드 표시 형식으로 변환합니다.
|
||||
*
|
||||
* @param int $limit 조회할 알림 수
|
||||
* @return array 최근 알림 배열
|
||||
*/
|
||||
public function getRecentNotificationLogs(int $limit = 5): array
|
||||
{
|
||||
$logs = $this->notificationLogRepository->getRecent($limit);
|
||||
|
||||
return $logs->map(function (NotificationLog $log) {
|
||||
return [
|
||||
'id' => $log->id,
|
||||
'type' => $log->notification_type,
|
||||
'channel' => $log->channel,
|
||||
'recipient' => $log->recipientUser?->name ?? $log->recipient_name ?? $log->recipient_identifier,
|
||||
'subject' => Str::limit((string) $log->subject, 50),
|
||||
'status' => $log->status->value,
|
||||
'time' => TimezoneHelper::toUserCarbon($log->sent_at ?? $log->created_at)?->diffForHumans(),
|
||||
'timestamp' => TimezoneHelper::toUserTimezone($log->sent_at ?? $log->created_at),
|
||||
];
|
||||
})->toArray();
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,75 @@ class GeoIpService
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* IP 주소로부터 국가 코드(ISO 3166-1 alpha-2)를 조회합니다.
|
||||
*
|
||||
* getTimezoneByIp 미러: 동일한 MaxMind GeoLite2-City Reader 를 재사용한다.
|
||||
* 비로그인 사용자의 기본 배송국가 추정 등에 사용된다(커머스 ShippingCountryResolver).
|
||||
*
|
||||
* @param string $ip IP 주소
|
||||
* @return string|null 국가 코드 (대문자 2자, 조회 실패 시 null)
|
||||
*/
|
||||
public function getCountryByIp(string $ip): ?string
|
||||
{
|
||||
// GeoIP 비활성화 상태
|
||||
if (! config('geoip.enabled', false)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 캐시 확인 (g7_core_settings 우선, fallback config)
|
||||
$cacheEnabled = (bool) g7_core_settings('cache.geoip_enabled', config('geoip.cache.enabled', true));
|
||||
$cacheKey = 'geoip.country.'.$ip;
|
||||
|
||||
if ($cacheEnabled) {
|
||||
$cached = $this->cache->get($cacheKey);
|
||||
|
||||
if ($cached !== null) {
|
||||
// 빈 문자열은 이전 조회 실패를 의미 (음성 캐시)
|
||||
return $cached === '' ? null : $cached;
|
||||
}
|
||||
}
|
||||
|
||||
// GeoIP 조회
|
||||
$country = $this->lookupCountry($ip);
|
||||
|
||||
// 캐시 저장 (조회 실패 시에도 빈 문자열 저장하여 반복 조회 방지)
|
||||
if ($cacheEnabled) {
|
||||
$ttl = (int) g7_core_settings('cache.geoip_ttl', config('geoip.cache.ttl', 86400));
|
||||
$this->cache->put($cacheKey, $country ?? '', $ttl);
|
||||
}
|
||||
|
||||
return $country;
|
||||
}
|
||||
|
||||
/**
|
||||
* MaxMind DB에서 국가 코드를 조회합니다.
|
||||
*/
|
||||
private function lookupCountry(string $ip): ?string
|
||||
{
|
||||
try {
|
||||
$reader = $this->getReader();
|
||||
|
||||
if ($reader === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$isoCode = $reader->city($ip)->country->isoCode;
|
||||
|
||||
return $isoCode !== null ? strtoupper($isoCode) : null;
|
||||
} catch (AddressNotFoundException $e) {
|
||||
// IP를 찾을 수 없음 (정상적인 케이스)
|
||||
return null;
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('GeoIP country lookup failed', [
|
||||
'ip' => $ip,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MaxMind DB에서 타임존을 조회합니다.
|
||||
*/
|
||||
@@ -121,6 +190,8 @@ class GeoIpService
|
||||
|
||||
/**
|
||||
* GeoIP 데이터베이스가 사용 가능한지 확인합니다.
|
||||
*
|
||||
* @return bool GeoIP 활성화 및 DB 파일 존재 여부
|
||||
*/
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
|
||||
@@ -163,6 +163,12 @@ class IdentityMessageTemplateService
|
||||
}
|
||||
}
|
||||
|
||||
// 템플릿 편집 시 updateTemplate 이 definition.is_default 를 false 로 내렸으므로,
|
||||
// 시드 정의 복원 시 definition 플래그도 함께 true 로 되돌린다 ('기본' 배지/reset 버튼 노출 조건 정상화).
|
||||
if ($updated->definition instanceof IdentityMessageDefinition) {
|
||||
$this->definitionService->markAsDefault($updated->definition);
|
||||
}
|
||||
|
||||
$this->definitionService->invalidateAllCache();
|
||||
|
||||
HookManager::doAction('core.identity.message_template.after_reset', $updated);
|
||||
@@ -191,23 +197,38 @@ class IdentityMessageTemplateService
|
||||
*/
|
||||
protected function getDefaultTemplateData(IdentityMessageTemplate $template): ?array
|
||||
{
|
||||
$definition = $template->definition;
|
||||
$defaultDefinition = $this->getDefaultDefinitionData($template->definition);
|
||||
|
||||
if ($defaultDefinition === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($defaultDefinition['templates'] ?? [] as $defaultTemplate) {
|
||||
if (($defaultTemplate['channel'] ?? null) === $template->channel) {
|
||||
return $defaultTemplate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정의가 시더 기본 정의(시드 정의)에 매칭되면 해당 기본 정의 데이터를 반환합니다.
|
||||
*
|
||||
* 운영자가 추가한 정의(admin definition)는 어떤 기본 정의에도 매칭되지 않아 null 을 반환합니다.
|
||||
*
|
||||
* @param IdentityMessageDefinition|null $definition
|
||||
* @return array|null
|
||||
*/
|
||||
protected function getDefaultDefinitionData(?IdentityMessageDefinition $definition): ?array
|
||||
{
|
||||
if (! $definition instanceof IdentityMessageDefinition) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$allDefaults = $this->collectDefaultDefinitions();
|
||||
|
||||
foreach ($allDefaults as $defaultDefinition) {
|
||||
if (! $this->matchesDefinition($defaultDefinition, $definition)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($defaultDefinition['templates'] ?? [] as $defaultTemplate) {
|
||||
if (($defaultTemplate['channel'] ?? null) === $template->channel) {
|
||||
return $defaultTemplate;
|
||||
}
|
||||
foreach ($this->collectDefaultDefinitions() as $defaultDefinition) {
|
||||
if ($this->matchesDefinition($defaultDefinition, $definition)) {
|
||||
return $defaultDefinition;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -145,12 +145,37 @@ class IdentityPolicyService
|
||||
throw new IdentityVerificationRequiredException(
|
||||
policyKey: $policy->key,
|
||||
purpose: $policy->purpose,
|
||||
providerId: $policy->provider_id,
|
||||
providerId: $this->resolveProviderId($policy),
|
||||
renderHint: $this->resolveRenderHint($policy),
|
||||
returnRequest: $context['return_request'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정책의 provider_id 를 해석합니다.
|
||||
*
|
||||
* 정책에 명시된 provider 가 있으면 우선 사용, 미명시 시 Manager 의 purpose 기반
|
||||
* fallback 체인(환경설정 default_provider → purpose_providers → 등록된 첫 provider)을 따른다.
|
||||
* `resolveRenderHint` 와 동일한 우선순위 체인을 적용하여, 정책에 provider 를 지정하지 않아도
|
||||
* 환경설정의 기본값이 launcher payload 의 provider_id 로 전달되도록 한다.
|
||||
*
|
||||
* @param IdentityPolicy $policy 대상 정책
|
||||
* @return string|null 해석된 provider id (해석 실패 시 정책의 원본 값)
|
||||
*/
|
||||
protected function resolveProviderId(IdentityPolicy $policy): ?string
|
||||
{
|
||||
try {
|
||||
$providerId = $policy->provider_id;
|
||||
if ($providerId && $this->manager->has($providerId)) {
|
||||
return $providerId;
|
||||
}
|
||||
|
||||
return $this->manager->resolveForPurpose($policy->purpose, $providerId)->getId();
|
||||
} catch (\Throwable) {
|
||||
return $policy->provider_id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인이 런타임에 정책을 추가로 등록할 때 사용 (DB 저장 없이).
|
||||
* 현재 구현은 로그에만 남기고, 필터 훅으로 소비되도록 설계.
|
||||
@@ -243,12 +268,12 @@ class IdentityPolicyService
|
||||
* S1d 관리자 UI 의 "↺ 기본값으로 되돌리기" 버튼이 이 메서드를 호출합니다.
|
||||
*
|
||||
* @param IdentityPolicy $policy 대상 정책
|
||||
* @param string $field 복원할 필드명 (enabled|grace_minutes|provider_id|fail_mode|conditions 중 하나)
|
||||
* @param string $field 복원할 필드명 (enabled|grace_minutes|provider_id|fail_mode|conditions|purpose|applies_to|priority 중 하나)
|
||||
* @return bool 성공 여부 (field 미지원 또는 선언 기본값 부재 시 false)
|
||||
*/
|
||||
public function resetFieldOverride(IdentityPolicy $policy, string $field): bool
|
||||
{
|
||||
$allowed = ['enabled', 'grace_minutes', 'provider_id', 'fail_mode', 'conditions'];
|
||||
$allowed = ['enabled', 'grace_minutes', 'provider_id', 'fail_mode', 'conditions', 'purpose', 'applies_to', 'priority'];
|
||||
if (! in_array($field, $allowed, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -112,6 +112,10 @@ class IdentityVerificationService
|
||||
/**
|
||||
* Challenge 를 취소합니다.
|
||||
*
|
||||
* before/after_cancel 훅을 발행하여 외부 plugin 이 자기 record (예: 이니시스의 challenge_mapping)
|
||||
* 를 cancel 시점에 정리할 수 있도록 한다. 다른 라이프사이클 이벤트(before/after_request,
|
||||
* before/after_verify) 와 일관된 hook 페어 구조 유지.
|
||||
*
|
||||
* @param string $challengeId Challenge UUID
|
||||
* @return bool 취소 성공 여부 (대상 challenge 가 없으면 false)
|
||||
*/
|
||||
@@ -119,16 +123,27 @@ class IdentityVerificationService
|
||||
{
|
||||
$log = $this->logRepository->findById($challengeId);
|
||||
|
||||
HookManager::doAction('core.identity.before_cancel', $challengeId, $log);
|
||||
|
||||
if (! $log) {
|
||||
HookManager::doAction('core.identity.after_cancel', $challengeId, null, false);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->manager->get($log->provider_id)->cancel($challengeId);
|
||||
$result = $this->manager->get($log->provider_id)->cancel($challengeId);
|
||||
|
||||
HookManager::doAction('core.identity.after_cancel', $challengeId, $log, $result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* verification_token 을 소비(consume)합니다 — signup_before_submit 정책 통과 시 재사용 방지.
|
||||
*
|
||||
* before/after_consume_token 훅을 발행하여 외부 plugin 이 token 소비 시점에 자기 후속 작업
|
||||
* (예: 이니시스의 가입 완료 후 record 영속화) 을 listener 로 분리할 수 있도록 한다.
|
||||
*
|
||||
* @param string $token IDV 발행 verification_token
|
||||
* @return bool consume 성공 여부 (verified 로그 부재 시 false)
|
||||
*/
|
||||
@@ -136,13 +151,21 @@ class IdentityVerificationService
|
||||
{
|
||||
$log = $this->logRepository->findVerifiedForToken($token, 'signup');
|
||||
|
||||
HookManager::doAction('core.identity.before_consume_token', $token, $log);
|
||||
|
||||
if (! $log) {
|
||||
HookManager::doAction('core.identity.after_consume_token', $token, null, false);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->logRepository->updateById($log->id, [
|
||||
$result = $this->logRepository->updateById($log->id, [
|
||||
'consumed_at' => now(),
|
||||
]);
|
||||
|
||||
HookManager::doAction('core.identity.after_consume_token', $token, $log, $result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,8 +174,11 @@ class IdentityVerificationService
|
||||
* 비동기 검증 흐름(Stripe Identity / 토스인증 push / 외부 redirect 콜백 대기) 에서 클라이언트가
|
||||
* `GET /api/identity/challenges/{id}` 로 상태를 폴링할 때 사용합니다.
|
||||
*
|
||||
* 반환 필드는 시도 횟수·코드 본체·내부 metadata 를 제외한 공개 안전 필드만:
|
||||
* - id / status / render_hint / expires_at / public_payload (요청 폴링에 필요한 최소집합)
|
||||
* 반환 필드는 코드 본체·내부 metadata 를 제외한 공개 안전 필드만:
|
||||
* - id / status / provider_id / purpose / render_hint / expires_at / attempts / max_attempts / public_payload
|
||||
*
|
||||
* attempts/max_attempts 는 프론트 풀페이지 (`auth/identity_challenge.json`) 가 "남은 시도 횟수" UI
|
||||
* 카운트다운에 사용한다. URL 직접 진입(외부 redirect 콜백 후) 흐름에서도 정확한 한도 표시 보장.
|
||||
*
|
||||
* @param string $challengeId Challenge UUID
|
||||
* @return array<string, mixed>|null 공개 상태 또는 null (없는 경우)
|
||||
@@ -175,8 +201,12 @@ class IdentityVerificationService
|
||||
return [
|
||||
'id' => $log->id,
|
||||
'status' => $log->status->value,
|
||||
'provider_id' => $log->provider_id,
|
||||
'purpose' => $log->purpose,
|
||||
'render_hint' => $log->render_hint,
|
||||
'expires_at' => optional($log->expires_at)->toIso8601String(),
|
||||
'attempts' => (int) $log->attempts,
|
||||
'max_attempts' => (int) $log->max_attempts,
|
||||
'public_payload' => $publicPayload,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\LanguagePack;
|
||||
|
||||
/**
|
||||
* 레이아웃 콘텐츠에서 참조되는 커스텀 다국어 키 스캐너.
|
||||
*
|
||||
* 레이아웃 content(JSON 디코드 배열)를 깊이 우선으로 순회하며 모든 문자열
|
||||
* 값에서 `$t:custom.{layout}.{seq}` 형태로 참조되는 커스텀 키를 수집합니다.
|
||||
* 노드의 `text` 뿐 아니라 props 값·표현식 내 `$t:custom.` 문자열도 보수적으로
|
||||
* 전부 스캔합니다(인라인 편집은 `text` 에만 쓰지만, 코드 편집기 경유 props/표현식
|
||||
* 참조도 보존 — 과소 orphaned 방지).
|
||||
*
|
||||
* DB 무접근 순수 함수이므로 단위 테스트가 용이합니다. 좀비(고아) 키 자동 감지
|
||||
* 리스너(MarkOrphanedCustomTranslations)가 본 스캐너로 "사용 중" 키 집합을 얻어
|
||||
* 미참조 키를 orphaned 로 전이시킵니다.
|
||||
*
|
||||
* @since engine-v1.54.0
|
||||
*/
|
||||
class CustomTranslationUsageScanner
|
||||
{
|
||||
/**
|
||||
* `$t:custom.{layoutKey}.{seq}` 매칭 정규식.
|
||||
*
|
||||
* - layoutKey: 영숫자/언더스코어/하이픈 (normalizeLayoutKey 출력과 동형)
|
||||
* - seq: 숫자
|
||||
*/
|
||||
private const CUSTOM_KEY_RE = '/\$t:(custom\.[A-Za-z0-9_\-]+\.\d+)/';
|
||||
|
||||
/**
|
||||
* 레이아웃 content 에서 참조되는 커스텀 키 목록을 수집합니다.
|
||||
*
|
||||
* @param mixed $content 레이아웃 content (배열/객체/문자열 — 보수적으로 전체 순회)
|
||||
* @return array<int, string> 참조된 커스텀 키 목록 (중복 제거, 예: ['custom.home.1'])
|
||||
*/
|
||||
public function collectReferencedKeys(mixed $content): array
|
||||
{
|
||||
$keys = [];
|
||||
$this->walk($content, $keys);
|
||||
|
||||
return array_values(array_unique($keys));
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 이름을 키 네임스페이스로 정규화합니다 (커스텀 키 생성/매칭 SSoT).
|
||||
*
|
||||
* `board/list` → `board_list`. 슬래시/공백을 언더스코어로 치환하고
|
||||
* 키에 안전한 문자만 남깁니다. 키 저장(TemplateCustomTranslationService::createKey)과
|
||||
* 스캐너의 layoutKey 추출이 동일 정규화를 공유하도록 단일 SSoT 로 둡니다.
|
||||
*
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return string 정규화된 키 네임스페이스
|
||||
*/
|
||||
public static function normalizeLayoutKey(string $layoutName): string
|
||||
{
|
||||
$normalized = preg_replace('/[\/\s]+/', '_', trim($layoutName));
|
||||
$normalized = preg_replace('/[^A-Za-z0-9_\-]/', '', (string) $normalized);
|
||||
|
||||
return $normalized === '' ? 'layout' : $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 값을 깊이 우선 순회하며 문자열에서 커스텀 키를 누적합니다.
|
||||
*
|
||||
* @param mixed $value 순회 대상 값
|
||||
* @param array<int, string> $keys 누적 키 (참조 전달)
|
||||
*/
|
||||
private function walk(mixed $value, array &$keys): void
|
||||
{
|
||||
if (is_string($value)) {
|
||||
if (str_contains($value, '$t:custom.') && preg_match_all(self::CUSTOM_KEY_RE, $value, $matches)) {
|
||||
foreach ($matches[1] as $key) {
|
||||
$keys[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
foreach ($value as $item) {
|
||||
$this->walk($item, $keys);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_object($value)) {
|
||||
foreach (get_object_vars($value) as $item) {
|
||||
$this->walk($item, $keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -428,6 +428,43 @@ class LanguagePackSeedInjector
|
||||
return $roles;
|
||||
}
|
||||
|
||||
/**
|
||||
* `{type}.{id}.manifest.translations` 필터 — 모듈/플러그인/템플릿의 manifest name/description
|
||||
* 다국어 필드에 활성 언어팩의 manifest seed(`seed/manifest.json`)를 주입합니다.
|
||||
*
|
||||
* seed 형식은 `{ "name": "ja 번역", "description": "ja 번역" }` 평문이며, 각 활성 비-fallback
|
||||
* locale 팩의 번역을 `$manifest['name'][$locale]`, `$manifest['description'][$locale]` 에 추가합니다.
|
||||
* ko/en 등 기존 키는 보존하며, ja 팩이 없으면 입력을 그대로 반환합니다.
|
||||
*
|
||||
* @param array<string, mixed> $manifest `['name' => <multilingual array>, 'description' => <multilingual array>]`
|
||||
* @param string $targetIdentifier 모듈/플러그인/템플릿 식별자
|
||||
* @param string $scope module|plugin|template
|
||||
* @return array<string, mixed> locale 키가 보강된 manifest 배열
|
||||
*/
|
||||
public function injectExtensionManifest(array $manifest, string $targetIdentifier, string $scope): array
|
||||
{
|
||||
$packs = $this->registry->getActivePacks($scope)
|
||||
->filter(fn (LanguagePack $pack) => $pack->target_identifier === $targetIdentifier);
|
||||
|
||||
foreach ($packs as $pack) {
|
||||
$seed = $this->loadPackSeed($pack, 'manifest');
|
||||
if (! $seed) {
|
||||
continue;
|
||||
}
|
||||
foreach (['name', 'description'] as $field) {
|
||||
if (! isset($seed[$field]) || ! is_string($seed[$field]) || $seed[$field] === '') {
|
||||
continue;
|
||||
}
|
||||
if (! isset($manifest[$field]) || ! is_array($manifest[$field])) {
|
||||
$manifest[$field] = [];
|
||||
}
|
||||
$manifest[$field][$pack->locale] = $seed[$field];
|
||||
}
|
||||
}
|
||||
|
||||
return $manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* `{type}.{id}.permissions.translations` 필터 — 모듈/플러그인의 권한 트리에
|
||||
* 활성 언어팩의 permissions seed 를 주입합니다.
|
||||
@@ -461,7 +498,6 @@ class LanguagePackSeedInjector
|
||||
*
|
||||
* @param array<string, mixed> $config
|
||||
* @param array<string, mixed> $seed identifier ⇒ {name, description} 맵
|
||||
* @param string $locale
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function mergePermissionTranslations(array $config, array $seed, string $locale, ?string $targetIdentifier = null): array
|
||||
@@ -554,7 +590,6 @@ class LanguagePackSeedInjector
|
||||
*
|
||||
* @param array<int, mixed> $menus
|
||||
* @param array<string, mixed> $seed slug ⇒ {name: ...} 맵
|
||||
* @param string $locale
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
private function mergeMenuTranslations(array $menus, array $seed, string $locale): array
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,10 +19,10 @@ class LayoutPreviewService
|
||||
private const DEFAULT_TTL_MINUTES = 30;
|
||||
|
||||
/**
|
||||
* @param LayoutPreviewRepositoryInterface $previewRepository 미리보기 리포지토리
|
||||
* @param LayoutService $layoutService 레이아웃 서비스
|
||||
* @param LayoutExtensionService $layoutExtensionService 레이아웃 확장 서비스
|
||||
* @param TemplateRepositoryInterface $templateRepository 템플릿 리포지토리
|
||||
* @param LayoutPreviewRepositoryInterface $previewRepository 미리보기 리포지토리
|
||||
* @param LayoutService $layoutService 레이아웃 서비스
|
||||
* @param LayoutExtensionService $layoutExtensionService 레이아웃 확장 서비스
|
||||
* @param TemplateRepositoryInterface $templateRepository 템플릿 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly LayoutPreviewRepositoryInterface $previewRepository,
|
||||
@@ -34,10 +34,10 @@ class LayoutPreviewService
|
||||
/**
|
||||
* 미리보기를 생성합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param array $content 편집 중인 레이아웃 JSON
|
||||
* @param int $adminId 관리자 ID
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param array $content 편집 중인 레이아웃 JSON
|
||||
* @param int $adminId 관리자 ID
|
||||
* @return TemplateLayoutPreview 생성된 미리보기 모델
|
||||
*/
|
||||
public function createPreview(int $templateId, string $layoutName, array $content, int $adminId): TemplateLayoutPreview
|
||||
@@ -62,13 +62,54 @@ class LayoutPreviewService
|
||||
return $preview;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 미리보기를 생성합니다.
|
||||
*
|
||||
* 편집 중인 확장 content 를 대표 레이아웃에 임시 적용하여 렌더링하기 위한
|
||||
* 미리보기 레코드를 생성합니다. layout_name 컬럼에 대표 레이아웃명을 저장합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param int $extensionId 레이아웃 확장 ID
|
||||
* @param string $previewLayout 대표 레이아웃 이름
|
||||
* @param array $content 편집 중인 확장 정의 JSON
|
||||
* @param int $adminId 관리자 ID
|
||||
* @return TemplateLayoutPreview 생성된 미리보기 모델
|
||||
*/
|
||||
public function createExtensionPreview(
|
||||
int $templateId,
|
||||
int $extensionId,
|
||||
string $previewLayout,
|
||||
array $content,
|
||||
int $adminId
|
||||
): TemplateLayoutPreview {
|
||||
HookManager::doAction('core.layout_preview.before_generate', $templateId, $previewLayout, $content, $adminId);
|
||||
|
||||
// 기존 동일 조합의 미리보기 삭제
|
||||
$this->previewRepository->deleteByLayoutAndAdmin($templateId, $previewLayout, $adminId);
|
||||
|
||||
$preview = $this->previewRepository->create([
|
||||
'token' => (string) Str::uuid(),
|
||||
'template_id' => $templateId,
|
||||
'layout_name' => $previewLayout,
|
||||
'preview_type' => 'extension',
|
||||
'extension_id' => $extensionId,
|
||||
'content' => $content,
|
||||
'admin_id' => $adminId,
|
||||
'expires_at' => now()->addMinutes(self::DEFAULT_TTL_MINUTES),
|
||||
]);
|
||||
|
||||
HookManager::doAction('core.layout_preview.after_generate', $preview);
|
||||
|
||||
return $preview;
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰으로 미리보기 레이아웃을 조회하고 병합합니다.
|
||||
*
|
||||
* 편집 중인 content에 extends가 있으면 부모 레이아웃과 병합하고,
|
||||
* 모듈/플러그인 extension도 적용합니다.
|
||||
*
|
||||
* @param string $token 미리보기 토큰
|
||||
* @param string $token 미리보기 토큰
|
||||
* @return array|null 병합된 레이아웃 데이터 또는 null
|
||||
*/
|
||||
public function getPreviewLayout(string $token): ?array
|
||||
@@ -79,9 +120,15 @@ class LayoutPreviewService
|
||||
return null;
|
||||
}
|
||||
|
||||
$layoutData = $preview->content;
|
||||
$templateId = $preview->template_id;
|
||||
|
||||
// 레이아웃 확장 미리보기: 편집 중인 확장 content 를 대표 레이아웃에 임시 적용
|
||||
if (($preview->preview_type ?? 'layout') === 'extension') {
|
||||
return $this->renderExtensionPreview($preview, $templateId);
|
||||
}
|
||||
|
||||
$layoutData = $preview->content;
|
||||
|
||||
// extends 상속 병합
|
||||
if (isset($layoutData['extends'])) {
|
||||
$parentLayoutName = $layoutData['extends'];
|
||||
@@ -95,10 +142,42 @@ class LayoutPreviewService
|
||||
return $layoutData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 미리보기를 렌더링합니다.
|
||||
*
|
||||
* 대표 레이아웃을 병합한 뒤, 편집 중인 확장 content 를 해당 확장 자리에
|
||||
* 임시 치환하여 applyExtensions 를 실행합니다.
|
||||
*
|
||||
* @param TemplateLayoutPreview $preview 미리보기 모델
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return array 확장이 적용된 대표 레이아웃
|
||||
*/
|
||||
private function renderExtensionPreview(TemplateLayoutPreview $preview, int $templateId): array
|
||||
{
|
||||
// 대표 레이아웃 병합 (layout_name 컬럼에 저장됨)
|
||||
$layoutData = $this->layoutService->loadAndMergeLayout($templateId, $preview->layout_name);
|
||||
|
||||
// 편집 중인 확장 content 를 임시 적용
|
||||
if ($preview->extension_id) {
|
||||
$this->layoutExtensionService->setPreviewContentOverride(
|
||||
$preview->extension_id,
|
||||
$preview->content
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$layoutData = $this->layoutExtensionService->applyExtensions($layoutData, $templateId);
|
||||
} finally {
|
||||
$this->layoutExtensionService->clearPreviewContentOverrides();
|
||||
}
|
||||
|
||||
return $layoutData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰으로 미리보기의 템플릿 식별자를 조회합니다.
|
||||
*
|
||||
* @param string $token 미리보기 토큰
|
||||
* @param string $token 미리보기 토큰
|
||||
* @return string|null 템플릿 식별자 또는 null
|
||||
*/
|
||||
public function getTemplateIdentifierByToken(string $token): ?string
|
||||
@@ -127,9 +206,9 @@ class LayoutPreviewService
|
||||
/**
|
||||
* 특정 관리자의 특정 레이아웃 미리보기를 삭제합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param int $adminId 관리자 ID
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param int $adminId 관리자 ID
|
||||
* @return int 삭제된 행 수
|
||||
*/
|
||||
public function deleteByLayoutAndAdmin(int $templateId, string $layoutName, int $adminId): int
|
||||
|
||||
+420
-40
@@ -7,11 +7,15 @@ use App\Contracts\Repositories\LayoutRepositoryInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Exceptions\CircularReferenceException;
|
||||
use App\Exceptions\ConcurrentModificationException;
|
||||
use App\Exceptions\LayoutIncludeException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -65,10 +69,14 @@ class LayoutService
|
||||
*
|
||||
* @param array $parentLayout 부모 레이아웃 데이터
|
||||
* @param array $childLayout 자식 레이아웃 데이터
|
||||
* @param array|null $sourceMeta ['kind' => 'base', 'layout' => '부모 레이아웃명'] (편집 모드 전용)
|
||||
* @return array 부모-자식이 병합된 레이아웃 데이터
|
||||
*
|
||||
* @throws \Exception 병합 중 오류 발생 시
|
||||
*
|
||||
* @since engine-v1.50.0 `$sourceMeta` 옵션 추가 — 편집 모드 출처 메타 부여
|
||||
*/
|
||||
public function mergeLayouts(array $parentLayout, array $childLayout): array
|
||||
public function mergeLayouts(array $parentLayout, array $childLayout, ?array $sourceMeta = null): array
|
||||
{
|
||||
// Before 훅 - 병합 전 데이터 검증/변환
|
||||
HookManager::doAction('core.layout.before_merge', $parentLayout, $childLayout);
|
||||
@@ -91,7 +99,8 @@ class LayoutService
|
||||
// 3. components 병합 (부모의 slot을 자식 slots로 교체)
|
||||
$mergedComponents = $this->mergeComponents(
|
||||
$parentLayout['components'] ?? [],
|
||||
$childLayout['slots'] ?? []
|
||||
$childLayout['slots'] ?? [],
|
||||
$sourceMeta
|
||||
);
|
||||
|
||||
// 4. modals 병합 (자식 우선, 부모와 자식 모두 포함)
|
||||
@@ -102,9 +111,16 @@ class LayoutService
|
||||
|
||||
// 5. init_actions/initActions 병합 (부모 먼저, 자식 나중에 실행)
|
||||
// initActions와 init_actions 둘 다 지원 (하위 호환)
|
||||
// 편집 모드($sourceMeta 비-null)면 항목별 __source 출처 부착.
|
||||
$childLayoutName = $childLayout['layout_name'] ?? $childLayout['name'] ?? null;
|
||||
$parentInitActions = $parentLayout['initActions'] ?? $parentLayout['init_actions'] ?? [];
|
||||
$childInitActions = $childLayout['initActions'] ?? $childLayout['init_actions'] ?? [];
|
||||
$mergedInitActions = $this->mergeInitActions($parentInitActions, $childInitActions);
|
||||
$mergedInitActions = $this->mergeInitActions(
|
||||
$parentInitActions,
|
||||
$childInitActions,
|
||||
$sourceMeta,
|
||||
$childLayoutName,
|
||||
);
|
||||
|
||||
// 6. defines 병합 (부모 + 자식, 자식 우선)
|
||||
$mergedDefines = $this->mergeDefines(
|
||||
@@ -117,6 +133,13 @@ class LayoutService
|
||||
$parentLayout['computed'] ?? [],
|
||||
$childLayout['computed'] ?? []
|
||||
);
|
||||
// 편집 모드($sourceMeta 비-null)면 키별 출처 맵을 레이아웃 최상위에 부착.
|
||||
$computedSourceMap = $sourceMeta !== null
|
||||
? $this->buildComputedSourceMap(
|
||||
$parentLayout['computed'] ?? [],
|
||||
$childLayout['computed'] ?? []
|
||||
)
|
||||
: [];
|
||||
|
||||
// 8. initLocal 병합 (부모 + 자식, 자식 우선, 얕은 병합)
|
||||
// state는 initLocal의 deprecated alias
|
||||
@@ -192,6 +215,12 @@ class LayoutService
|
||||
$result['computed'] = $mergedComputed;
|
||||
}
|
||||
|
||||
// 편집 모드 computed 출처 맵 — 레이아웃 최상위(computed 객체 외부)에 부착.
|
||||
// 운영 렌더는 $sourceMeta=null 이라 빈 맵 → 미부착(응답 형식 종전과 동일).
|
||||
if (! empty($computedSourceMap)) {
|
||||
$result['__computedSource'] = $computedSourceMap;
|
||||
}
|
||||
|
||||
// initLocal이 있으면 추가 (빈 배열이 아닌 경우만)
|
||||
if (! empty($mergedInitLocal)) {
|
||||
$result['initLocal'] = $mergedInitLocal;
|
||||
@@ -318,7 +347,7 @@ class LayoutService
|
||||
|
||||
foreach ($childDataSources as $childDataSource) {
|
||||
if (in_array($childDataSource['id'], $existingIds, true)) {
|
||||
throw new \Exception(
|
||||
throw new LayoutIncludeException(
|
||||
__('exceptions.layout.duplicate_data_source_id', ['id' => $childDataSource['id']])
|
||||
);
|
||||
}
|
||||
@@ -332,10 +361,14 @@ class LayoutService
|
||||
|
||||
/**
|
||||
* components 병합 - 부모의 slot 속성을 자식 slots 데이터로 교체
|
||||
*
|
||||
* @param array|null $sourceMeta ['kind' => 'base', 'layout' => '부모 레이아웃명'] 또는 null (편집 모드 전용)
|
||||
*
|
||||
* @since engine-v1.50.0 `$sourceMeta` 옵션 추가
|
||||
*/
|
||||
private function mergeComponents(array $parentComponents, array $childSlots): array
|
||||
private function mergeComponents(array $parentComponents, array $childSlots, ?array $sourceMeta = null): array
|
||||
{
|
||||
return $this->replaceSlots($parentComponents, $childSlots);
|
||||
return $this->replaceSlots($parentComponents, $childSlots, $sourceMeta);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -368,13 +401,50 @@ class LayoutService
|
||||
/**
|
||||
* init_actions 병합 - 부모 액션 먼저, 자식 액션 나중에 실행
|
||||
*
|
||||
* 편집 모드(`$sourceMeta` 비-null)에서는 각 항목에 `__source` 출처 메타를 부착한다
|
||||
* 부모 항목 = `$sourceMeta`(kind:'base'), 자식 항목
|
||||
* = `['kind'=>'route', 'layout'=>$childLayoutName]`. [화면 동작] 탭이 부모/자식
|
||||
* 동작을 출처 배지로 구분하고 부모 항목을 읽기전용으로 표시하는 근거가 된다.
|
||||
* dispatch 는 항목에서 화이트리스트 키만 추출(TemplateApp.ts:4014-4029)하므로
|
||||
* `__source` 부착은 런타임 무영향이고, 저장 시 `stripInheritedFromLayoutContent` 가
|
||||
* `__editor.original` 로 부모분·`__source` 를 제거(기존 경로). 운영 렌더
|
||||
* (`$sourceMeta` null)는 부착하지 않아 응답 형식이 종전과 100% 동일하다.
|
||||
*
|
||||
* @param array $parentActions 부모 레이아웃의 init_actions 배열
|
||||
* @param array $childActions 자식 레이아웃의 init_actions 배열
|
||||
* @param array|null $sourceMeta 부모(base) 출처 메타 — null 이면 운영 렌더(부착 안 함)
|
||||
* @param string|null $childLayoutName 자식 레이아웃명 — 자식 항목 `__source.layout` 에 사용
|
||||
* @return array 병합된 init_actions 배열
|
||||
*/
|
||||
private function mergeInitActions(array $parentActions, array $childActions): array
|
||||
{
|
||||
return array_merge($parentActions, $childActions);
|
||||
private function mergeInitActions(
|
||||
array $parentActions,
|
||||
array $childActions,
|
||||
?array $sourceMeta = null,
|
||||
?string $childLayoutName = null,
|
||||
): array {
|
||||
if ($sourceMeta === null) {
|
||||
// 운영 렌더 경로 — 종전과 동일(부착 없음).
|
||||
return array_merge($parentActions, $childActions);
|
||||
}
|
||||
|
||||
$childMeta = ['kind' => 'route', 'layout' => $childLayoutName];
|
||||
|
||||
$stamp = static function (array $items, array $meta): array {
|
||||
$out = [];
|
||||
foreach ($items as $item) {
|
||||
if (is_array($item)) {
|
||||
$item['__source'] = $meta;
|
||||
}
|
||||
$out[] = $item;
|
||||
}
|
||||
|
||||
return $out;
|
||||
};
|
||||
|
||||
return array_merge(
|
||||
$stamp($parentActions, $sourceMeta),
|
||||
$stamp($childActions, $childMeta),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -396,8 +466,7 @@ class LayoutService
|
||||
/**
|
||||
* computed 병합 - 자식 값이 부모를 오버라이드
|
||||
*
|
||||
* 파생 상태 표현식을 병합합니다.
|
||||
* 동일한 키가 있으면 자식 레이아웃의 표현식이 우선합니다.
|
||||
* 파생 상태 표현식을 병합합니다. 동일한 키가 있으면 자식 레이아웃의 표현식이 우선합니다.
|
||||
*
|
||||
* @param array $parentComputed 부모 레이아웃의 computed 객체
|
||||
* @param array $childComputed 자식 레이아웃의 computed 객체
|
||||
@@ -409,6 +478,39 @@ class LayoutService
|
||||
return array_merge($parentComputed, $childComputed);
|
||||
}
|
||||
|
||||
/**
|
||||
* computed 키별 출처 맵을 만든다.
|
||||
*
|
||||
* 키 출처를 3종으로 구분한다:
|
||||
* - 'base' : 부모(공통)만 선언 — 〔공통〕배지
|
||||
* - 'route' : 자식(이 페이지)만 선언 — 무배지
|
||||
* - 'route-override' : 부모+자식 동시 선언(자식이 부모를 덮음) — 〔이 페이지에서 덮음〕
|
||||
* 승격 배지 + 공통값 되돌리기
|
||||
*
|
||||
* [자동 계산] 탭이 부모/자식 computed 를 배지로 구분하고 덮어쓰기 안내를 표시하는 근거.
|
||||
* 'route'(순수 자식)와 'route-override'(덮음)를 구분해야 ComputedForm 이 되돌리기 버튼을
|
||||
* 덮은 키에만 노출할 수 있다. 본 맵은 **레이아웃 최상위 `__computedSource`** 에 부착되며
|
||||
* (computed 객체 내부 아님), 그래야 calculateComputed/ActionDispatcher/DynamicRenderer 의
|
||||
* computed 키 순회가 메타 키를 표현식으로 오평가하지 않는다(편집 모드 한정 부착).
|
||||
*
|
||||
* @param array $parentComputed 부모 computed 객체
|
||||
* @param array $childComputed 자식 computed 객체
|
||||
* @return array<string,string> 키 → 'base'|'route'|'route-override'
|
||||
*/
|
||||
private function buildComputedSourceMap(array $parentComputed, array $childComputed): array
|
||||
{
|
||||
$map = [];
|
||||
foreach (array_keys($parentComputed) as $key) {
|
||||
$map[$key] = 'base';
|
||||
}
|
||||
foreach (array_keys($childComputed) as $key) {
|
||||
// 부모에도 있던 키를 자식이 다시 선언 = 덮음(override).
|
||||
$map[$key] = isset($map[$key]) ? 'route-override' : 'route';
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* named_actions 병합 - 자식 값이 부모를 오버라이드
|
||||
*
|
||||
@@ -540,11 +642,17 @@ class LayoutService
|
||||
* (슬롯 래퍼 컴포넌트의 id, name, props 등은 유지됨)
|
||||
* - 해당 slot에 대한 데이터가 없으면 slot 속성 유지 (다음 상속에서 사용)
|
||||
*
|
||||
* $sourceMeta 가 전달되면 각 노드에 `__source` 출처 메타를 부여한다
|
||||
* 일반 사이트 렌더는 null 전달 → 메타 미부여.
|
||||
*
|
||||
* @param array $components 컴포넌트 배열
|
||||
* @param array $slots 슬롯 데이터 (슬롯명 => 컴포넌트 배열)
|
||||
* @param array|null $sourceMeta ['kind' => 'base'|'route', 'layout' => '레이아웃명'] 또는 null
|
||||
* @return array 슬롯이 교체된 컴포넌트 배열
|
||||
*
|
||||
* @since engine-v1.50.0 `$sourceMeta` 옵션 추가
|
||||
*/
|
||||
private function replaceSlots(array $components, array $slots): array
|
||||
private function replaceSlots(array $components, array $slots, ?array $sourceMeta = null): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
@@ -580,6 +688,15 @@ class LayoutService
|
||||
$resultComponent['children'] = [$slotComponents];
|
||||
}
|
||||
|
||||
// 슬롯 래퍼 자체는 base 출처(레이아웃이 정의한 컴포넌트). slot children 은 route 출처
|
||||
if ($sourceMeta !== null) {
|
||||
$resultComponent['__source'] = $sourceMeta;
|
||||
$resultComponent['children'] = $this->markSourceMeta(
|
||||
$resultComponent['children'],
|
||||
['kind' => 'route', 'layout' => $sourceMeta['layout'] ?? '']
|
||||
);
|
||||
}
|
||||
|
||||
$result[] = $resultComponent;
|
||||
} else {
|
||||
// slot이 없거나 교체할 데이터가 없으면 그대로 유지 (base 컴포넌트)
|
||||
@@ -589,9 +706,17 @@ class LayoutService
|
||||
// @since engine-v1.24.8
|
||||
$resultComponent['_fromBase'] = true;
|
||||
|
||||
if ($sourceMeta !== null) {
|
||||
$resultComponent['__source'] = $sourceMeta;
|
||||
}
|
||||
|
||||
// children이 있으면 재귀적으로 처리
|
||||
if (isset($component['children']) && is_array($component['children'])) {
|
||||
$resultComponent['children'] = $this->replaceSlots($component['children'], $slots);
|
||||
$resultComponent['children'] = $this->replaceSlots(
|
||||
$component['children'],
|
||||
$slots,
|
||||
$sourceMeta
|
||||
);
|
||||
}
|
||||
|
||||
$result[] = $resultComponent;
|
||||
@@ -601,6 +726,47 @@ class LayoutService
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 컴포넌트 트리에 단일 출처 메타를 재귀적으로 부여합니다.
|
||||
*
|
||||
* `replaceSlots` 의 slot children(라우트 콘텐츠) 트리 전체에 같은 출처 메타를
|
||||
* 부착할 때 사용합니다. 이미 `__source` 가 설정된 노드는 보존(`applyExtensions`
|
||||
* 가 부여한 extension 메타 덮어쓰기 방지).
|
||||
*
|
||||
* @param array $components 컴포넌트 배열
|
||||
* @param array $sourceMeta 부여할 메타 (예: ['kind' => 'route', 'layout' => 'index'])
|
||||
* @return array 메타가 부여된 컴포넌트 배열
|
||||
*
|
||||
* @since engine-v1.50.0
|
||||
*/
|
||||
private function markSourceMeta(array $components, array $sourceMeta): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($components as $component) {
|
||||
if (! is_array($component)) {
|
||||
$result[] = $component;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$resultComponent = $component;
|
||||
|
||||
// 이미 출처 메타가 있으면 보존 (확장 주입 노드 등)
|
||||
if (! isset($resultComponent['__source'])) {
|
||||
$resultComponent['__source'] = $sourceMeta;
|
||||
}
|
||||
|
||||
if (isset($component['children']) && is_array($component['children'])) {
|
||||
$resultComponent['children'] = $this->markSourceMeta($component['children'], $sourceMeta);
|
||||
}
|
||||
|
||||
$result[] = $resultComponent;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 병합 결과에서 불필요한 필드 제거 (extends, slots)
|
||||
*
|
||||
@@ -618,10 +784,20 @@ class LayoutService
|
||||
/**
|
||||
* 레이아웃을 로드하고 상속 구조를 병합합니다. (캐싱 적용)
|
||||
*
|
||||
* `$withSourceMeta` 가 true 면 각 노드에 `__source` 출처 메타를 부여하고,
|
||||
* 메타 포함/미포함 결과는 별도 캐시 키로 분리한다.
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $layoutName 대상 레이아웃 이름
|
||||
* @param bool $withSourceMeta 편집 모드 출처 메타 부여 여부
|
||||
* @return array 부모/자식 상속 병합이 적용된 레이아웃 데이터
|
||||
*
|
||||
* @throws CircularReferenceException 순환 참조 감지 시
|
||||
* @throws \Exception 최대 깊이 초과 시
|
||||
*
|
||||
* @since engine-v1.50.0 `$withSourceMeta` 옵션 추가
|
||||
*/
|
||||
public function loadAndMergeLayout(int $templateId, string $layoutName): array
|
||||
public function loadAndMergeLayout(int $templateId, string $layoutName, bool $withSourceMeta = false): array
|
||||
{
|
||||
// Before 훅 - 로드 전
|
||||
HookManager::doAction('core.layout.before_load', $templateId, $layoutName);
|
||||
@@ -630,13 +806,13 @@ class LayoutService
|
||||
|
||||
// 캐시 비활성 시 매번 병합 실행
|
||||
if (! $cacheEnabled) {
|
||||
$merged = $this->loadAndMergeLayoutInternal($templateId, $layoutName);
|
||||
$merged = $this->loadAndMergeLayoutInternal($templateId, $layoutName, $withSourceMeta);
|
||||
HookManager::doAction('core.layout.after_load', $merged, $templateId, $layoutName, false);
|
||||
|
||||
return $merged;
|
||||
}
|
||||
|
||||
$cacheKey = $this->getMergedLayoutCacheKey($templateId, $layoutName);
|
||||
$cacheKey = $this->getMergedLayoutCacheKey($templateId, $layoutName, $withSourceMeta);
|
||||
|
||||
// 캐시에서 시도
|
||||
$cached = $this->cache->get($cacheKey);
|
||||
@@ -666,7 +842,7 @@ class LayoutService
|
||||
]);
|
||||
|
||||
// 병합된 레이아웃 생성
|
||||
$mergedLayout = $this->loadAndMergeLayoutInternal($templateId, $layoutName);
|
||||
$mergedLayout = $this->loadAndMergeLayoutInternal($templateId, $layoutName, $withSourceMeta);
|
||||
|
||||
// 캐시에 저장
|
||||
$cacheTtl = $this->getCacheTtl();
|
||||
@@ -690,8 +866,10 @@ class LayoutService
|
||||
*
|
||||
* @throws CircularReferenceException 순환 참조 감지 시
|
||||
* @throws \Exception 최대 깊이 초과 시
|
||||
*
|
||||
* @since engine-v1.50.0 `$withSourceMeta` 옵션 추가
|
||||
*/
|
||||
private function loadAndMergeLayoutInternal(int $templateId, string $layoutName): array
|
||||
private function loadAndMergeLayoutInternal(int $templateId, string $layoutName, bool $withSourceMeta = false): array
|
||||
{
|
||||
// 1. 순환 참조 감지
|
||||
if (in_array($layoutName, $this->loadStack, true)) {
|
||||
@@ -712,8 +890,10 @@ class LayoutService
|
||||
'max_depth' => $maxDepth,
|
||||
]);
|
||||
|
||||
throw new \Exception(
|
||||
__('exceptions.max_depth_exceeded', ['max' => $maxDepth])
|
||||
throw new LayoutIncludeException(
|
||||
__('exceptions.max_depth_exceeded', ['max' => $maxDepth]),
|
||||
$layoutName,
|
||||
$this->loadStack,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -755,13 +935,53 @@ class LayoutService
|
||||
}
|
||||
|
||||
// 부모 레이아웃 재귀적으로 로드 및 병합 (캐싱 버전 호출)
|
||||
$parentLayout = $this->loadAndMergeLayout($templateId, $parentLayoutName);
|
||||
$parentLayout = $this->loadAndMergeLayout($templateId, $parentLayoutName, $withSourceMeta);
|
||||
|
||||
// 부모와 자식 병합 (기존 mergeLayouts 메서드 재사용)
|
||||
$mergedLayout = $this->mergeLayouts($parentLayout, $layoutData);
|
||||
// 편집 모드에서는 base 출처 메타를 부여한다 — 부모 레이아웃에서 온 노드 식별
|
||||
$sourceMeta = $withSourceMeta
|
||||
? ['kind' => 'base', 'layout' => $parentLayoutName]
|
||||
: null;
|
||||
$mergedLayout = $this->mergeLayouts($parentLayout, $layoutData, $sourceMeta);
|
||||
|
||||
// 상속 체인 보존 — 자식 서빙 시 base 를 target_layout 으로 하는 overlay
|
||||
// (예: 헤더 통화 슬롯 주입)가 매칭되도록 부모 이름을 비-렌더 메타로 남긴다.
|
||||
// `LayoutExtensionService::applyExtensions` 가 [layoutName] + __extends_chain 을
|
||||
// overlay 매칭 대상에 포함하고, 최종 응답 직전 이 키를 제거하므로 일반/편집 응답
|
||||
// 형식은 종전과 동일하다. 부모가 다단계 상속이면 부모 체인을 이어받아 누적한다.
|
||||
$parentChain = is_array($parentLayout['__extends_chain'] ?? null)
|
||||
? $parentLayout['__extends_chain']
|
||||
: [];
|
||||
$mergedLayout['__extends_chain'] = array_values(array_unique(
|
||||
array_merge([$parentLayoutName], $parentChain)
|
||||
));
|
||||
|
||||
// 편집 모드 응답에는 자식 원본(`$layoutData`) 을 별도 컨테이너로 보존한다
|
||||
// 저장 시 클라이언트가 머지된 트리에서 원본을
|
||||
// 추측 복원하지 않고, 본 메타에서 원본 그대로 가져다 PUT 한다.
|
||||
if ($withSourceMeta) {
|
||||
$mergedLayout['__editor'] = [
|
||||
'original' => $layoutData,
|
||||
];
|
||||
}
|
||||
} else {
|
||||
// 상속이 없으면 현재 레이아웃 그대로 반환
|
||||
$mergedLayout = $layoutData;
|
||||
|
||||
// extends 가 없는 레이아웃의 컴포넌트는 모두 자기 출처 — 'route' 메타 부여
|
||||
// 편집 모드에서만, 일반 사이트 렌더는 메타 미부여
|
||||
if ($withSourceMeta && isset($mergedLayout['components']) && is_array($mergedLayout['components'])) {
|
||||
$mergedLayout['components'] = $this->markSourceMeta(
|
||||
$mergedLayout['components'],
|
||||
['kind' => 'route', 'layout' => $layoutName]
|
||||
);
|
||||
|
||||
// 편집 모드: 독립 레이아웃도 원본 컨테이너를 보존해 저장 시 SSoT 로 사용.
|
||||
// 합본/원본이 같지만 클라이언트의 저장 경로를 단일화하기 위해 항상 부착.
|
||||
$mergedLayout['__editor'] = [
|
||||
'original' => $layoutData,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $mergedLayout;
|
||||
@@ -823,9 +1043,15 @@ class LayoutService
|
||||
* 병합된 레이아웃 캐시 키 생성
|
||||
*
|
||||
* 모듈 레이아웃의 경우 소스 해시를 포함하여 오버라이드 정보를 반영합니다.
|
||||
* `$withSourceMeta` 가 true 면 캐시 키에 `.with_source_meta` 접미사를 붙여
|
||||
* 일반 응답 캐시와 분리합니다.
|
||||
*
|
||||
* @since engine-v1.50.0 `$withSourceMeta` 옵션 추가
|
||||
*/
|
||||
private function getMergedLayoutCacheKey(int $templateId, string $layoutName): string
|
||||
private function getMergedLayoutCacheKey(int $templateId, string $layoutName, bool $withSourceMeta = false): string
|
||||
{
|
||||
$metaSuffix = $withSourceMeta ? '.with_source_meta' : '';
|
||||
|
||||
// 모듈 레이아웃인 경우 소스 정보를 캐시 키에 포함
|
||||
if ($this->isModuleLayoutName($layoutName)) {
|
||||
// 해석 결과를 기반으로 소스 해시 생성
|
||||
@@ -834,23 +1060,28 @@ class LayoutService
|
||||
if ($resolved) {
|
||||
$sourceHash = md5($resolved->source_type?->value.$resolved->source_identifier);
|
||||
|
||||
return "template.{$templateId}.layout.{$layoutName}.{$sourceHash}";
|
||||
return "template.{$templateId}.layout.{$layoutName}.{$sourceHash}{$metaSuffix}";
|
||||
}
|
||||
}
|
||||
|
||||
return "template.{$templateId}.layout.{$layoutName}";
|
||||
return "template.{$templateId}.layout.{$layoutName}{$metaSuffix}";
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 레이아웃의 캐시를 무효화합니다.
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $layoutName 대상 레이아웃 이름
|
||||
*/
|
||||
public function clearLayoutCache(int $templateId, string $layoutName): void
|
||||
{
|
||||
// Before 훅 - 캐시 무효화 전
|
||||
HookManager::doAction('core.layout.before_cache_clear', $templateId, $layoutName);
|
||||
|
||||
$cacheKey = $this->getMergedLayoutCacheKey($templateId, $layoutName);
|
||||
// 일반 응답과 편집 모드(`with_source_meta=1`) 응답 두 캐시 키 모두 무효화
|
||||
$cacheKey = $this->getMergedLayoutCacheKey($templateId, $layoutName, false);
|
||||
$this->cache->forget($cacheKey);
|
||||
$this->cache->forget($this->getMergedLayoutCacheKey($templateId, $layoutName, true));
|
||||
|
||||
// PublicLayoutController 서빙 캐시도 무효화
|
||||
// PublicLayoutController::serve()에서 "layout.{identifier}.{name}.v{version}" 키로 별도 캐싱
|
||||
@@ -890,11 +1121,20 @@ class LayoutService
|
||||
|
||||
$identifier = $template->identifier;
|
||||
$cacheVersion = (int) $this->cache->get('ext.cache_version', 0);
|
||||
|
||||
// PublicLayoutController::serve() 가 일반 응답과 편집 모드(`with_source_meta=1`) 응답을
|
||||
// 별도 캐시 키로 저장한다 (`.meta` 접미사). 본 PR Phase 3 S5a-1 에서 편집 모드 응답 캐시
|
||||
// 키가 추가되었으나 그 무효화는 누락 — 본 결함은 편집기가 저장 후 새로고침해도 stale
|
||||
// 응답을 받는 현상으로 표출된다. 일반/편집 모드 두 키 모두 무효화한다.
|
||||
$this->cache->forget("layout.{$identifier}.{$layoutName}.v{$cacheVersion}");
|
||||
$this->cache->forget("layout.{$identifier}.{$layoutName}.v{$cacheVersion}.meta");
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 레이아웃을 extends하는 모든 자식 레이아웃의 캐시를 재귀적으로 무효화합니다.
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $layoutName 변경된 부모 레이아웃 이름
|
||||
*/
|
||||
public function clearDependentLayoutsCache(int $templateId, string $layoutName): void
|
||||
{
|
||||
@@ -956,9 +1196,19 @@ class LayoutService
|
||||
/**
|
||||
* 템플릿 identifier와 레이아웃 이름으로 병합된 레이아웃 조회
|
||||
*
|
||||
* `$withSourceMeta` 가 true 면 응답의 각 노드 및 data_source 에 `__source` 출처
|
||||
* 메타를 부여한다. 옵션 미사용 시 응답 형식은 종전과 100% 동일.
|
||||
*
|
||||
* @param string $templateIdentifier 템플릿 identifier
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param bool $withSourceMeta 편집 모드 출처 메타 부여 여부
|
||||
* @return array 병합 + 확장 + (옵션 시) 출처 메타가 부여된 레이아웃 데이터
|
||||
*
|
||||
* @throws ModelNotFoundException 템플릿을 찾을 수 없거나 비활성화된 경우
|
||||
*
|
||||
* @since engine-v1.50.0 `$withSourceMeta` 옵션 추가
|
||||
*/
|
||||
public function getLayout(string $templateIdentifier, string $layoutName): array
|
||||
public function getLayout(string $templateIdentifier, string $layoutName, bool $withSourceMeta = false): array
|
||||
{
|
||||
// Before 훅 - 레이아웃 조회 전
|
||||
HookManager::doAction('core.layout.before_get', $templateIdentifier, $layoutName);
|
||||
@@ -983,10 +1233,35 @@ class LayoutService
|
||||
}
|
||||
|
||||
// 레이아웃 로드 및 병합 (캐싱 포함)
|
||||
$layout = $this->loadAndMergeLayout($template->id, $layoutName);
|
||||
$layout = $this->loadAndMergeLayout($template->id, $layoutName, $withSourceMeta);
|
||||
|
||||
// 모듈/플러그인 Extension 적용 (Overlay, Extension Point)
|
||||
$layout = $this->layoutExtensionService->applyExtensions($layout, $template->id);
|
||||
$layout = $this->layoutExtensionService->applyExtensions($layout, $template->id, $withSourceMeta);
|
||||
|
||||
// 편집 모드 응답에 자식 레이아웃의 실제 DB lock_version 동봉.
|
||||
// PublicLayoutController 가 LayoutResource 를 거치지 않고 머지된 배열을 그대로 반환하므로,
|
||||
// 낙관적 잠금 흐름에 필요한 lock_version 을 응답 본문에 직접 부착해야 한다. 일반 사이트
|
||||
// 렌더(`withSourceMeta=false`)는 부착하지 않아 응답 형식이 종전과 100% 동일.
|
||||
if ($withSourceMeta) {
|
||||
$childRow = $this->layoutRepository->findByName($template->id, $layoutName);
|
||||
if ($childRow !== null) {
|
||||
$layout['lock_version'] = (int) ($childRow->lock_version ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
// 편집 모드: data_sources 에 출처 메타(`__source`) 부여.
|
||||
// 같은 data_source id 를 여러 확장이 서로 다른 shape 로 정의할 때, 편집기 캔버스의
|
||||
// 샘플 데이터 해소(sampleDataProvider)가 그 데이터소스의 출처 스펙 샘플을 우선 선택해
|
||||
// 전역 id 충돌을 해소하도록 한다(계획서). 일반 렌더는 부여하지 않아
|
||||
// 운영 화면 영향 0. 이미 __source 가 있는 항목(확장 주입)은 보존.
|
||||
if ($withSourceMeta && isset($layout['data_sources']) && is_array($layout['data_sources'])) {
|
||||
$dsSourceMeta = $this->deriveDataSourceSourceMeta($layoutName, $template->id);
|
||||
foreach ($layout['data_sources'] as $idx => $dataSource) {
|
||||
if (is_array($dataSource) && ! isset($dataSource['__source'])) {
|
||||
$layout['data_sources'][$idx]['__source'] = $dsSourceMeta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// After 훅 - 레이아웃 조회 후
|
||||
HookManager::doAction('core.layout.after_get', $layout, $templateIdentifier, $layoutName, $template);
|
||||
@@ -994,8 +1269,61 @@ class LayoutService
|
||||
return $layout;
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집 모드 data_source 출처 메타 판정.
|
||||
*
|
||||
* 확장 prefix(`{vendor-ext}.{layout}`)를 가진 레이아웃은 소유 확장의 실제
|
||||
* `source_type`(`LayoutResolverService::resolve`)으로 module/plugin 을 구분한다.
|
||||
* - 모듈 레이아웃 → `['kind' => 'module', 'identifier' => 'vendor-ext']`
|
||||
* - 플러그인 레이아웃 → `['kind' => 'plugin', 'identifier' => 'vendor-ext']`
|
||||
* - prefix 없음(템플릿 자체 레이아웃) → `['kind' => 'route', 'identifier' => null]`
|
||||
*
|
||||
* 엔진 `resolveSampleData.resolveSourceKey` 는 module/plugin 만 `{kind}:{identifier}` 로
|
||||
* bySource 를 조회한다. editorSpecLoader 도 동일하게 module 스펙은 `module:{id}`,
|
||||
* plugin 스펙은 `plugin:{id}` 키로 보존하므로, kind 가 정확해야 그 확장의 샘플이
|
||||
* 매칭된다. 이름 패턴만으로는 plugin 레이아웃이 모듈로 오분류되어(둘 다 `{ext}.{layout}`
|
||||
* 형태) `plugin:{id}` 스펙을 빗나가므로,
|
||||
* 해석 결과의 source_type 을 SSoT 로 삼는다. 해석 실패 시 이름 패턴으로 폴백.
|
||||
*
|
||||
* @param string $layoutName 레이아웃 이름 (예: 'sirsoft-gdpr.plugin_settings', 'admin_dashboard')
|
||||
* @param int $templateId 편집 대상 템플릿 ID (source_type 해석용)
|
||||
* @return array{kind: string, identifier: string|null} 출처 메타
|
||||
*/
|
||||
private function deriveDataSourceSourceMeta(string $layoutName, int $templateId): array
|
||||
{
|
||||
// 확장 prefix 추출 — '{vendor-ext}.{layout}' 형태에서 첫 '.' 앞부분
|
||||
$dotPos = strpos($layoutName, '.');
|
||||
if ($dotPos === false) {
|
||||
// prefix 없음 → 템플릿 자체 레이아웃 (엔진에서 'template' 키로 폴백)
|
||||
return ['kind' => 'route', 'identifier' => null];
|
||||
}
|
||||
|
||||
$extensionId = substr($layoutName, 0, $dotPos);
|
||||
|
||||
// 소유 확장의 실제 source_type 으로 module/plugin 정확 분류 (이름 패턴은 둘을 구분 못 함).
|
||||
// `LayoutResolverService::resolve` 는 plugin 행을 반환하지 않으므로(fromModules 스코프가
|
||||
// source_type=Module 만 조회) 레이아웃 행을 직접 조회해 source_type 을 읽는다.
|
||||
$row = $this->layoutRepository->findByName($templateId, $layoutName);
|
||||
$sourceType = $row?->source_type;
|
||||
|
||||
if ($sourceType === LayoutSourceType::Plugin) {
|
||||
return ['kind' => 'plugin', 'identifier' => $extensionId];
|
||||
}
|
||||
if ($sourceType === LayoutSourceType::Module) {
|
||||
return ['kind' => 'module', 'identifier' => $extensionId];
|
||||
}
|
||||
|
||||
// 행/소스타입 부재 — 이름 패턴 폴백 (모듈 패턴이면 module, 아니면 plugin)
|
||||
$kind = $this->isModuleLayoutName($layoutName) ? 'module' : 'plugin';
|
||||
|
||||
return ['kind' => $kind, 'identifier' => $extensionId];
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @return Collection<int, TemplateLayout> 템플릿 소속 레이아웃 컬렉션
|
||||
*/
|
||||
public function getLayoutsByTemplateId(int $templateId)
|
||||
{
|
||||
@@ -1012,6 +1340,10 @@ class LayoutService
|
||||
|
||||
/**
|
||||
* 특정 레이아웃 조회 (이름으로)
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return TemplateLayout|null 조회된 레이아웃 또는 null
|
||||
*/
|
||||
public function getLayoutByName(int $templateId, string $name): ?TemplateLayout
|
||||
{
|
||||
@@ -1029,6 +1361,11 @@ class LayoutService
|
||||
/**
|
||||
* 레이아웃 업데이트
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @param array $data 업데이트할 레이아웃 데이터 (content 키 또는 평면 배열)
|
||||
* @return TemplateLayout 업데이트된 레이아웃 모델
|
||||
*
|
||||
* @throws ModelNotFoundException 레이아웃을 찾을 수 없을 때
|
||||
*/
|
||||
public function updateLayout(int $templateId, string $name, array $data): TemplateLayout
|
||||
@@ -1048,25 +1385,51 @@ class LayoutService
|
||||
);
|
||||
}
|
||||
|
||||
// 낙관적 잠금 — expected_lock_version 검증
|
||||
// FormRequest 가 의무화하므로 누락 시 422 에서 차단되지만, 직접 호출 안전망으로 가드.
|
||||
$expectedVersion = isset($data['expected_lock_version'])
|
||||
? (int) $data['expected_lock_version']
|
||||
: null;
|
||||
$currentVersion = (int) ($layout->lock_version ?? 0);
|
||||
|
||||
if ($expectedVersion !== null && $expectedVersion !== $currentVersion) {
|
||||
throw new ConcurrentModificationException(
|
||||
currentVersion: $currentVersion,
|
||||
expectedVersion: $expectedVersion,
|
||||
resource: "template_layouts:{$layout->id}",
|
||||
);
|
||||
}
|
||||
|
||||
// content 키가 있으면 추출 (UpdateLayoutContentRequest 사용 시)
|
||||
$updateData = $data['content'] ?? $data;
|
||||
|
||||
// 버전 저장 (user 템플릿인 경우에만)
|
||||
$template = $layout->template;
|
||||
$oldContent = $layout->content;
|
||||
|
||||
// 레이아웃 업데이트
|
||||
$layout = $this->layoutRepository->update($layout->id, $updateData);
|
||||
// 레이아웃 업데이트 (lock_version 1 증가)
|
||||
$layout = $this->layoutRepository->updateContent($layout->id, $updateData, $currentVersion + 1);
|
||||
|
||||
// user 템플릿인 경우 버전 히스토리 저장 (이전 버전 + 현재 저장 버전)
|
||||
if ($template->type === 'user') {
|
||||
// 1. 이전 버전 저장 (롤백용)
|
||||
$this->versionRepository->saveVersion($layout->id, $oldContent, $updateData);
|
||||
|
||||
// 2. 현재 저장 버전 저장 (최신 상태 기록)
|
||||
$this->versionRepository->saveVersion($layout->id, $updateData, $updateData);
|
||||
// 버전 히스토리 저장 — 저장 시점 content 스냅샷. 모든 템플릿 유형(admin/user)이 대상이다.
|
||||
// (종전엔 user 템플릿만 버전을 남겼으나, admin/user 구분 없이 모든 템플릿이 편집 가능해진
|
||||
// 현 정책에 맞춰 제한을 제거한다.)
|
||||
// changes_summary 는 직전 저장본 대비 이번 저장본의 변경을 기록한다.
|
||||
// (종전엔 버전 2건을 만들고 그중 하나가 자기 자신과 비교돼 changes_summary 가 항상 0 이었다 —
|
||||
// 최신 버전의 변경 요약이 0 으로 보여 수정 전/후 구분이 불가했던 결함 수정.)
|
||||
// 첫 수정 시 수정 전 원본을 baseline 버전으로 먼저 백업한다(이력이 하나도 없을 때만).
|
||||
// 이게 없으면 첫 수정본만 v1 으로 남아 "수정 전 상태"로 복원할 수 없다.
|
||||
// baseline 의 changes_summary 는 비교 대상이 없어 0(빈 요약) — 최초 원본 표식.
|
||||
$hasHistory = $this->versionRepository->getNextVersion($layout->id) > 1;
|
||||
if (! $hasHistory) {
|
||||
$this->versionRepository->saveVersion($layout->id, $oldContent, null);
|
||||
}
|
||||
|
||||
// 이번 저장본을 새 버전으로 적재 — 직전(oldContent) 대비 변경 요약 기록.
|
||||
$savedVersion = $this->versionRepository->saveVersion($layout->id, $updateData, $oldContent);
|
||||
|
||||
// 저장 응답에 현재(최신) 버전 번호 동봉 — 편집기 라우트 트리 버전
|
||||
// 배지가 저장 직후 재fetch 없이 동기화되도록 transient 속성으로 부착한다
|
||||
// (LayoutResource 가 current_version 으로 직렬화 — DB 컬럼 아님).
|
||||
$layout->setAttribute('current_version', $savedVersion->version);
|
||||
|
||||
// 캐시 무효화
|
||||
$this->clearDependentLayoutsCache($templateId, $name);
|
||||
|
||||
@@ -1083,6 +1446,10 @@ class LayoutService
|
||||
|
||||
/**
|
||||
* 특정 레이아웃의 모든 버전 조회
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return Collection 버전 컬렉션
|
||||
*/
|
||||
public function getLayoutVersions(int $templateId, string $name)
|
||||
{
|
||||
@@ -1109,6 +1476,11 @@ class LayoutService
|
||||
|
||||
/**
|
||||
* 특정 버전의 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @param int $version 버전 번호
|
||||
* @return mixed 조회된 버전 모델
|
||||
*/
|
||||
public function getLayoutVersion(int $templateId, string $name, int $version)
|
||||
{
|
||||
@@ -1142,6 +1514,11 @@ class LayoutService
|
||||
/**
|
||||
* 버전 복원
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @param int $versionId 복원할 버전 ID
|
||||
* @return mixed 새로 저장된 버전 모델
|
||||
*
|
||||
* @throws ModelNotFoundException 레이아웃 또는 버전을 찾을 수 없을 때
|
||||
*/
|
||||
public function restoreVersion(int $templateId, string $name, int $versionId)
|
||||
@@ -1175,6 +1552,9 @@ class LayoutService
|
||||
|
||||
/**
|
||||
* 레이아웃 JSON에서 XSS 및 악의적인 코드를 제거합니다.
|
||||
*
|
||||
* @param array $layout 검증 전 레이아웃 데이터
|
||||
* @return array sanitize 가 적용된 레이아웃 데이터
|
||||
*/
|
||||
public function sanitizeLayoutJson(array $layout): array
|
||||
{
|
||||
|
||||
@@ -2,16 +2,19 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Exceptions\ModuleOperationException;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Exceptions\ModuleOperationException;
|
||||
use App\Extension\Helpers\ChangelogParser;
|
||||
use App\Extension\Helpers\EditorSpecAssembler;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\ZipInstallHelper;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\Module;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -102,7 +105,7 @@ class ModuleService
|
||||
/**
|
||||
* 설치된 모듈 목록을 조회합니다.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Collection 설치된 모듈 목록
|
||||
* @return Collection 설치된 모듈 목록
|
||||
*/
|
||||
public function getInstalledModules()
|
||||
{
|
||||
@@ -112,7 +115,7 @@ class ModuleService
|
||||
/**
|
||||
* 마켓플레이스에서 이용 가능한 모듈 목록을 조회합니다.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Collection 마켓플레이스 모듈 목록
|
||||
* @return Collection 마켓플레이스 모듈 목록
|
||||
*/
|
||||
public function getMarketplaceModules()
|
||||
{
|
||||
@@ -122,7 +125,7 @@ class ModuleService
|
||||
/**
|
||||
* 의존성 정보가 포함된 모든 모듈을 조회합니다.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Collection 의존성 정보가 포함된 모듈 목록
|
||||
* @return Collection 의존성 정보가 포함된 모듈 목록
|
||||
*/
|
||||
public function getAllModulesWithDependencies()
|
||||
{
|
||||
@@ -169,17 +172,16 @@ class ModuleService
|
||||
* 지정된 모듈을 업데이트합니다.
|
||||
*
|
||||
* @param string $moduleName 업데이트할 모듈 identifier
|
||||
* @param \App\Extension\Vendor\VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param string $layoutStrategy 레이아웃 전략 (overwrite|keep)
|
||||
* @return array 업데이트 결과 (identifier, from_version, to_version 등)
|
||||
*
|
||||
* @param bool $force 코어 버전 비호환 강제 우회 (위험 — 사용자 명시 필요)
|
||||
* @return array 업데이트 결과 (identifier, from_version, to_version 등)
|
||||
*
|
||||
* @throws ValidationException 업데이트 실패 시
|
||||
*/
|
||||
public function updateModule(
|
||||
string $moduleName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
VendorMode $vendorMode = VendorMode::Auto,
|
||||
string $layoutStrategy = 'overwrite',
|
||||
bool $force = false,
|
||||
): array {
|
||||
@@ -238,7 +240,7 @@ class ModuleService
|
||||
* 모듈을 시스템에 설치합니다.
|
||||
*
|
||||
* @param string $moduleName 설치할 모듈명
|
||||
* @param \App\Extension\Vendor\VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param bool $force Updating/Failed 등 진행 중 상태도 무시하고 강제 설치 여부
|
||||
* @return array|null 설치된 모듈 정보 또는 null
|
||||
*
|
||||
@@ -246,7 +248,7 @@ class ModuleService
|
||||
*/
|
||||
public function installModule(
|
||||
string $moduleName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
VendorMode $vendorMode = VendorMode::Auto,
|
||||
bool $force = false,
|
||||
): ?array {
|
||||
HookManager::doAction('core.modules.before_install', $moduleName);
|
||||
@@ -736,6 +738,7 @@ class ModuleService
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 업로드된 ZIP 파일로부터 모듈을 추출/검증하고 _pending 으로 이동 후 설치합니다.
|
||||
*
|
||||
@@ -950,6 +953,83 @@ class ModuleService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 편집기 스펙(editor-spec.json) 디코드 결과를 반환합니다.
|
||||
*
|
||||
* 활성 모듈만 대상으로 하며, 활성 디렉토리 → _bundled 폴백 순으로 읽습니다.
|
||||
* editor-spec.json 은 수작업 작성 파일로 모듈 루트(module.json 옆)에 둡니다.
|
||||
* 파일 미존재/미작성 시 spec=null 로 폴백합니다(편집 컨트롤 부재).
|
||||
*
|
||||
* @param string $identifier 모듈 식별자 (vendor-module 형식)
|
||||
* @return array{success: bool, spec: array<string, mixed>|null, error: string|null}
|
||||
*/
|
||||
public function getEditorSpec(string $identifier): array
|
||||
{
|
||||
$module = $this->moduleRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $module || $module->status !== ExtensionStatus::Active->value) {
|
||||
return ['success' => false, 'spec' => null, 'error' => 'module_not_found'];
|
||||
}
|
||||
|
||||
// 분할 editor-spec.json 은 manifest + `$include` 블록으로 구성되므로
|
||||
// 단순 디코드가 아닌 합본이 필요하다. 활성 디렉토리만 기준으로 합본한다
|
||||
// (_bundled 폴백 없음). _bundled 작업분은 module:update 로 활성에
|
||||
// 반영된 뒤에만 런타임에 보인다. 미분할 파일은 원본 그대로(하위 호환).
|
||||
$spec = EditorSpecAssembler::assemble(
|
||||
base_path("modules/{$identifier}/editor-spec.json")
|
||||
);
|
||||
|
||||
return ['success' => true, 'spec' => $spec, 'error' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 컴포넌트 매니페스트(components.json) 디코드 결과를 반환합니다.
|
||||
*
|
||||
* components.json 은 module:build 산출물로 모듈 루트에 둡니다.
|
||||
* 활성 디렉토리 → _bundled 폴백 순으로 읽으며, 미생성(구버전 모듈) 시
|
||||
* components=null 로 폴백합니다(무손실 보존 디그레이드 — 원칙 4.6).
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return array{success: bool, components: array<string, mixed>|null, error: string|null}
|
||||
*/
|
||||
public function getComponents(string $identifier): array
|
||||
{
|
||||
$module = $this->moduleRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $module || $module->status !== ExtensionStatus::Active->value) {
|
||||
return ['success' => false, 'components' => null, 'error' => 'module_not_found'];
|
||||
}
|
||||
|
||||
$components = $this->readJsonWithBundledFallback("modules/{$identifier}/components.json");
|
||||
|
||||
return ['success' => true, 'components' => $components, 'error' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 디렉토리 → _bundled 폴백 순으로 JSON 파일을 읽어 디코드합니다.
|
||||
*
|
||||
* @param string $relativePath base_path 기준 상대 경로 (modules/{id}/file.json)
|
||||
* @return array<string, mixed>|null 디코드된 배열, 미존재/파싱 실패 시 null
|
||||
*/
|
||||
private function readJsonWithBundledFallback(string $relativePath): ?array
|
||||
{
|
||||
// modules/{id}/file.json → modules/_bundled/{id}/file.json 폴백
|
||||
$bundledPath = preg_replace('#^modules/#', 'modules/_bundled/', $relativePath, 1);
|
||||
$candidates = [base_path($relativePath), base_path((string) $bundledPath)];
|
||||
|
||||
foreach ($candidates as $path) {
|
||||
if (! file_exists($path) || ! is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
$decoded = json_decode((string) file_get_contents($path), true);
|
||||
if (is_array($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* MIME 타입 감지
|
||||
*
|
||||
|
||||
@@ -19,7 +19,7 @@ class NotificationChannelService
|
||||
*
|
||||
* config 기본 채널 + Filter 훅으로 플러그인 채널 확장 가능.
|
||||
*
|
||||
* @return array
|
||||
* @return array 채널 메타데이터 배열 (id, name, description, source_label 등)
|
||||
*/
|
||||
public function getAvailableChannels(): array
|
||||
{
|
||||
@@ -47,8 +47,8 @@ class NotificationChannelService
|
||||
/**
|
||||
* 특정 채널이 사용 가능한지 확인합니다.
|
||||
*
|
||||
* @param string $channelId
|
||||
* @return bool
|
||||
* @param string $channelId 채널 식별자
|
||||
* @return bool 사용 가능 여부
|
||||
*/
|
||||
public function isChannelAvailable(string $channelId): bool
|
||||
{
|
||||
@@ -57,6 +57,39 @@ class NotificationChannelService
|
||||
return collect($channels)->contains('id', $channelId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 채널이 비회원(게스트) 발송을 허용하는지 확인합니다.
|
||||
*
|
||||
* 채널 메타데이터의 `allow_guest` 플래그를 조회합니다 (config 기본 채널 +
|
||||
* `core.notification.filter_available_channels` 훅으로 추가된 모듈/플러그인 채널 공통).
|
||||
* 미선언 채널은 기본 `false`(차단) — 비회원 개인정보(이메일 등)가 의도치 않게
|
||||
* 새 프로바이더로 노출되는 것을 방지하기 위한 opt-in 정책입니다.
|
||||
* (확장 단위 채널 활성 `isChannelEnabledForExtension` 의 "미선언=활성" 과 반대 방향)
|
||||
*
|
||||
* `core.notification.channel_guest_allowed` 필터 훅으로 동적 재정의 가능합니다.
|
||||
*
|
||||
* @param string $channelId 채널 식별자 (mail, database, sms 등)
|
||||
* @return bool true = 비회원 발송 허용, false = 차단
|
||||
*/
|
||||
public function isChannelGuestAllowed(string $channelId): bool
|
||||
{
|
||||
$channels = $this->getAvailableChannels();
|
||||
|
||||
$allow = false;
|
||||
foreach ($channels as $channel) {
|
||||
if (($channel['id'] ?? null) === $channelId) {
|
||||
$allow = (bool) ($channel['allow_guest'] ?? false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (bool) HookManager::applyFilters(
|
||||
'core.notification.channel_guest_allowed',
|
||||
$allow,
|
||||
$channelId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장(core/module/plugin) 단위의 채널 전역 활성 여부를 확인합니다.
|
||||
*
|
||||
@@ -68,9 +101,9 @@ class NotificationChannelService
|
||||
*
|
||||
* `core.notification.channel_enabled` 필터 훅으로 재정의 가능합니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입 (core, module, plugin)
|
||||
* @param string|null $extensionIdentifier 확장 식별자 (core는 'core' 허용)
|
||||
* @param string $channelId 채널 식별자 (mail, database 등)
|
||||
* @param string $extensionType 확장 타입 (core, module, plugin)
|
||||
* @param string|null $extensionIdentifier 확장 식별자 (core는 'core' 허용)
|
||||
* @param string $channelId 채널 식별자 (mail, database 등)
|
||||
* @return bool true = 발송 허용, false = 발송 차단
|
||||
*/
|
||||
public function isChannelEnabledForExtension(
|
||||
@@ -102,8 +135,6 @@ class NotificationChannelService
|
||||
|
||||
/**
|
||||
* 메모이제이션 캐시를 초기화합니다. (테스트 및 설정 변경 후 사용)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearChannelEnabledCache(): void
|
||||
{
|
||||
@@ -112,10 +143,6 @@ class NotificationChannelService
|
||||
|
||||
/**
|
||||
* 확장 타입별 notifications.channels 배열을 조회합니다.
|
||||
*
|
||||
* @param string $extensionType
|
||||
* @param string|null $extensionIdentifier
|
||||
* @return array
|
||||
*/
|
||||
private function resolveExtensionChannels(string $extensionType, ?string $extensionIdentifier): array
|
||||
{
|
||||
@@ -157,10 +184,6 @@ class NotificationChannelService
|
||||
* notifications.channels 배열에서 특정 채널의 is_active 값을 추출합니다.
|
||||
*
|
||||
* 엔트리가 없으면 true(기본 활성)를 반환합니다.
|
||||
*
|
||||
* @param array $channels
|
||||
* @param string $channelId
|
||||
* @return bool
|
||||
*/
|
||||
private function extractChannelActive(array $channels, string $channelId): bool
|
||||
{
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Role;
|
||||
use App\Contracts\Notifications\GuestRecipientInterface;
|
||||
use App\Contracts\Repositories\RoleRepositoryInterface;
|
||||
use App\Contracts\Repositories\UserRepositoryInterface;
|
||||
use App\Models\User;
|
||||
use App\Notifications\GuestNotifiable;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -11,23 +14,36 @@ use Illuminate\Support\Facades\Log;
|
||||
* 알림 수신자 해석 서비스
|
||||
*
|
||||
* recipients JSON 규칙 배열을 해석하여
|
||||
* 최종 수신자 User 컬렉션을 반환합니다.
|
||||
* 최종 수신자 컬렉션(회원 User + 비회원 GuestNotifiable)을 반환합니다.
|
||||
*
|
||||
* 수신자 타입:
|
||||
* - trigger_user: 이벤트를 유발한 사용자 (주문자, 가입자 등)
|
||||
* - trigger_user: 이벤트를 유발한 사용자 (주문자, 가입자 등). 회원이면 User,
|
||||
* 비회원이면 컨텍스트의 표준 키 guest_recipient 로 GuestNotifiable 생성.
|
||||
* - related_user: 관련 사용자 (문의 답변 → 문의 작성자)
|
||||
* - role: 특정 역할의 사용자들 (admin, manager 등)
|
||||
* - permission: 특정 권한을 가진 역할에 소속된 사용자들 (예: sirsoft-board.reports.manage)
|
||||
* - specific_users: 지정된 사용자 UUID 목록
|
||||
*
|
||||
* 비회원 수신자는 user_id 없이 이메일/이름/로케일만 가진 1급 Notifiable 로,
|
||||
* 회원과 동일한 발송 경로($notifiable->notify())를 공유합니다.
|
||||
*/
|
||||
class NotificationRecipientResolver
|
||||
{
|
||||
/**
|
||||
* @param UserRepositoryInterface $userRepository 사용자 조회 Repository
|
||||
* @param RoleRepositoryInterface $roleRepository 역할 조회 Repository
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly UserRepositoryInterface $userRepository,
|
||||
private readonly RoleRepositoryInterface $roleRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* recipients 규칙 배열을 해석하여 수신자 목록을 반환합니다.
|
||||
*
|
||||
* @param array $rules 수신자 규칙 배열
|
||||
* @param array $context 컨텍스트 데이터 (trigger_user_id, related_users 등)
|
||||
* @return Collection<int, User>
|
||||
* @param array $rules 수신자 규칙 배열
|
||||
* @param array $context 컨텍스트 데이터 (trigger_user_id, guest_recipient, related_users 등)
|
||||
* @return Collection<int, object> 회원(User) + 비회원(GuestNotifiable) 혼합 가능
|
||||
*/
|
||||
public function resolve(array $rules, array $context): Collection
|
||||
{
|
||||
@@ -60,44 +76,75 @@ class NotificationRecipientResolver
|
||||
}
|
||||
}
|
||||
|
||||
// exclude_trigger_user 규칙 적용
|
||||
// exclude_trigger_user 규칙 적용 (회원 유발자 기준 — 게스트는 user_id 가 없어 자연 비대상)
|
||||
if ($triggerUserId) {
|
||||
$shouldExclude = collect($rules)->contains(fn ($rule) => ! empty($rule['exclude_trigger_user']));
|
||||
if ($shouldExclude) {
|
||||
$recipients = $recipients->filter(fn (User $user) => $user->id !== $triggerUserId);
|
||||
$recipients = $recipients->reject(
|
||||
fn (object $recipient) => isset($recipient->id) && $recipient->id === $triggerUserId
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $recipients->unique('id')->values();
|
||||
// 중복 제거: 회원(user:{id})과 비회원(guest:{hash}) 키 네임스페이스를 분리해
|
||||
// null-id 게스트가 하나로 뭉개지는 것을 방지한다.
|
||||
return $recipients->unique(fn (object $recipient) => $this->recipientDedupKey($recipient))->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* 수신자 중복 제거 키를 반환합니다.
|
||||
*
|
||||
* 회원은 `user:{id}`, 비회원(게스트)은 `guest:{이메일 해시}` 네임스페이스를 사용해
|
||||
* 서로 충돌하지 않게 합니다.
|
||||
*
|
||||
* @param object $recipient 수신자 (User 또는 GuestNotifiable)
|
||||
* @return string 중복 제거 키
|
||||
*/
|
||||
private function recipientDedupKey(object $recipient): string
|
||||
{
|
||||
if ($recipient instanceof GuestRecipientInterface && $recipient->isGuest()) {
|
||||
return (string) $recipient->getKey();
|
||||
}
|
||||
|
||||
return 'user:'.($recipient->id ?? spl_object_id($recipient));
|
||||
}
|
||||
|
||||
/**
|
||||
* 이벤트 유발자를 수신자에 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $context 컨텍스트
|
||||
* @return void
|
||||
* 회원이면 trigger_user_id 로 User 를, 비회원이면 컨텍스트의 표준 키
|
||||
* guest_recipient({email, name, locale})로 GuestNotifiable 을 생성해 추가합니다.
|
||||
* 템플릿의 {"type":"trigger_user"} 규칙이 회원/비회원 분기 없이 동작합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $context 컨텍스트
|
||||
*/
|
||||
private function addTriggerUser(Collection $recipients, array $context): void
|
||||
{
|
||||
$triggerUserId = $context['trigger_user_id'] ?? null;
|
||||
if (! $triggerUserId) {
|
||||
|
||||
if ($triggerUserId) {
|
||||
$user = $context['trigger_user'] ?? $this->userRepository->findById($triggerUserId);
|
||||
if ($user) {
|
||||
$recipients->push($user);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$user = $context['trigger_user'] ?? User::find($triggerUserId);
|
||||
if ($user) {
|
||||
$recipients->push($user);
|
||||
// 비회원 폴백: user_id 가 없으면 표준 guest_recipient 키로 1급 게스트 수신자 생성
|
||||
$guest = $context['guest_recipient'] ?? null;
|
||||
if (is_array($guest) && ($notifiable = GuestNotifiable::fromContext($guest)) !== null) {
|
||||
$recipients->push($notifiable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 관련 사용자를 수신자에 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $context 컨텍스트
|
||||
* @param array $rule 수신자 규칙 (relation 키 필요)
|
||||
* @return void
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $context 컨텍스트
|
||||
* @param array $rule 수신자 규칙 (relation 키 필요)
|
||||
*/
|
||||
private function addRelatedUser(Collection $recipients, array $context, array $rule): void
|
||||
{
|
||||
@@ -119,9 +166,8 @@ class NotificationRecipientResolver
|
||||
/**
|
||||
* 역할 기반 수신자를 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = role identifier)
|
||||
* @return void
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = role identifier)
|
||||
*/
|
||||
private function addByRole(Collection $recipients, array $rule): void
|
||||
{
|
||||
@@ -130,12 +176,11 @@ class NotificationRecipientResolver
|
||||
return;
|
||||
}
|
||||
|
||||
$role = Role::where('identifier', $roleIdentifier)->first();
|
||||
$roleUsers = $role ? $role->users()->get() : collect();
|
||||
$roleUsers = $this->roleRepository->getUsersByIdentifier($roleIdentifier);
|
||||
|
||||
// 역할 사용자가 없으면 superAdmin 폴백
|
||||
if ($roleUsers->isEmpty()) {
|
||||
$superAdmin = User::superAdmins()->first();
|
||||
$superAdmin = $this->userRepository->findSuperAdmin();
|
||||
if ($superAdmin) {
|
||||
$roleUsers = collect([$superAdmin]);
|
||||
}
|
||||
@@ -151,8 +196,8 @@ class NotificationRecipientResolver
|
||||
* role 기반 수신자와 달리 "권한을 가진 자" 기준이므로 테스트에서 권한을 제거하면
|
||||
* 자동으로 수신자 목록에서 제외됩니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = permission identifier)
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = permission identifier)
|
||||
*/
|
||||
private function addByPermission(Collection $recipients, array $rule): void
|
||||
{
|
||||
@@ -161,27 +206,15 @@ class NotificationRecipientResolver
|
||||
return;
|
||||
}
|
||||
|
||||
$permission = \App\Models\Permission::where('identifier', $permissionIdentifier)->first();
|
||||
if (! $permission) {
|
||||
return;
|
||||
}
|
||||
|
||||
$roleIds = $permission->roles()->pluck('roles.id');
|
||||
$userIds = \DB::table('user_roles')
|
||||
->whereIn('role_id', $roleIds)
|
||||
->pluck('user_id')
|
||||
->unique();
|
||||
|
||||
$users = User::whereIn('id', $userIds)->get();
|
||||
$users = $this->userRepository->findManyByPermissionIdentifier($permissionIdentifier);
|
||||
$recipients->push(...$users->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 사용자 UUID 목록을 수신자에 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = user UUID 배열)
|
||||
* @return void
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = user UUID 배열)
|
||||
*/
|
||||
private function addSpecificUsers(Collection $recipients, array $rule): void
|
||||
{
|
||||
@@ -190,7 +223,7 @@ class NotificationRecipientResolver
|
||||
return;
|
||||
}
|
||||
|
||||
$users = User::whereIn('uuid', $userIds)->get();
|
||||
$users = $this->userRepository->findManyByUuids($userIds);
|
||||
$recipients->push(...$users->all());
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,6 @@ class NotificationTemplateService
|
||||
{
|
||||
/**
|
||||
* 캐시 키 접두사 (드라이버 접두사 `g7:core:` 다음에 붙음).
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $cachePrefix = 'notification.template.';
|
||||
|
||||
@@ -27,9 +25,9 @@ class NotificationTemplateService
|
||||
}
|
||||
|
||||
/**
|
||||
* @param NotificationTemplateRepositoryInterface $templateRepository
|
||||
* @param NotificationDefinitionRepositoryInterface $definitionRepository
|
||||
* @param CacheInterface $cache
|
||||
* @param NotificationTemplateRepositoryInterface $templateRepository
|
||||
* @param NotificationDefinitionRepositoryInterface $definitionRepository
|
||||
* @param CacheInterface $cache
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly NotificationTemplateRepositoryInterface $templateRepository,
|
||||
@@ -40,8 +38,8 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 알림 타입 + 채널로 활성 템플릿 조회 (캐싱).
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @return NotificationTemplate|null
|
||||
*/
|
||||
public function resolve(string $type, string $channel): ?NotificationTemplate
|
||||
@@ -57,7 +55,7 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 특정 알림 정의의 모든 템플릿 조회.
|
||||
*
|
||||
* @param int $definitionId
|
||||
* @param int $definitionId
|
||||
* @return Collection
|
||||
*/
|
||||
public function getByDefinitionId(int $definitionId): Collection
|
||||
@@ -68,9 +66,9 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 템플릿 수정.
|
||||
*
|
||||
* @param NotificationTemplate $template
|
||||
* @param array $data
|
||||
* @param int|null $userId
|
||||
* @param NotificationTemplate $template
|
||||
* @param array $data
|
||||
* @param int|null $userId
|
||||
* @return NotificationTemplate
|
||||
*/
|
||||
public function updateTemplate(NotificationTemplate $template, array $data, ?int $userId = null): NotificationTemplate
|
||||
@@ -112,7 +110,7 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 활성/비활성 토글.
|
||||
*
|
||||
* @param NotificationTemplate $template
|
||||
* @param NotificationTemplate $template
|
||||
* @return NotificationTemplate
|
||||
*/
|
||||
public function toggleActive(NotificationTemplate $template): NotificationTemplate
|
||||
@@ -136,16 +134,25 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 기본값으로 복원.
|
||||
*
|
||||
* @param NotificationTemplate $template
|
||||
* @param array $defaultData
|
||||
* @param NotificationTemplate $template
|
||||
* @param array $defaultData
|
||||
* @return NotificationTemplate
|
||||
*/
|
||||
public function resetToDefault(NotificationTemplate $template, array $defaultData): NotificationTemplate
|
||||
{
|
||||
$updated = $this->templateRepository->update($template, array_merge($defaultData, [
|
||||
'is_default' => true,
|
||||
'user_overrides' => null,
|
||||
]));
|
||||
// 복원은 사용자 수정이 아니므로 seeding 컨텍스트로 감싸 HasUserOverrides 의
|
||||
// updating 자동 기록을 비활성화한다. 이 가드가 없으면 복원되는 trackable 필드
|
||||
// (subject/body/click_url/recipients)가 dirty 로 감지되어 user_overrides 가
|
||||
// 즉시 재기록되고, 복원이 무효화된다.
|
||||
app()->instance('user_overrides.seeding', true);
|
||||
try {
|
||||
$updated = $this->templateRepository->update($template, array_merge($defaultData, [
|
||||
'is_default' => true,
|
||||
'user_overrides' => null,
|
||||
]));
|
||||
} finally {
|
||||
app()->forgetInstance('user_overrides.seeding');
|
||||
}
|
||||
|
||||
$definition = $updated->definition;
|
||||
if ($definition) {
|
||||
@@ -158,8 +165,8 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 시더에서 기본 템플릿 데이터를 조회합니다.
|
||||
*
|
||||
* @param string $type 알림 정의 타입
|
||||
* @param string $channel 채널명
|
||||
* @param string $type 알림 정의 타입
|
||||
* @param string $channel 채널명
|
||||
* @return array 기본 템플릿 데이터 (subject, body)
|
||||
*/
|
||||
public function getDefaultTemplateData(string $type, string $channel): array
|
||||
@@ -189,6 +196,8 @@ class NotificationTemplateService
|
||||
return [
|
||||
'subject' => $tpl['subject'] ?? null,
|
||||
'body' => $tpl['body'],
|
||||
'click_url' => $tpl['click_url'] ?? null,
|
||||
'recipients' => $tpl['recipients'] ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -204,7 +213,7 @@ class NotificationTemplateService
|
||||
* definition_id가 제공되면 해당 정의의 변수 메타데이터를 조회하여
|
||||
* 샘플 값으로 치환합니다.
|
||||
*
|
||||
* @param array $data
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
public function getPreview(array $data): array
|
||||
@@ -223,7 +232,7 @@ class NotificationTemplateService
|
||||
$key = $var['key'] ?? '';
|
||||
if ($key !== '') {
|
||||
$description = $var['description'] ?? $key;
|
||||
$replacements['{' . $key . '}'] = '[' . $description . ']';
|
||||
$replacements['{'.$key.'}'] = '['.$description.']';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,7 +240,7 @@ class NotificationTemplateService
|
||||
|
||||
// 명시적으로 전달된 variables가 있으면 덮어쓰기
|
||||
foreach ($data['variables'] ?? [] as $key => $value) {
|
||||
$replacements['{' . $key . '}'] = (string) $value;
|
||||
$replacements['{'.$key.'}'] = (string) $value;
|
||||
}
|
||||
|
||||
return [
|
||||
@@ -243,8 +252,8 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 특정 타입+채널의 캐시 무효화.
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @return void
|
||||
*/
|
||||
public function invalidateCache(string $type, string $channel): void
|
||||
@@ -255,12 +264,12 @@ class NotificationTemplateService
|
||||
/**
|
||||
* 캐시 키 생성.
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @return string
|
||||
*/
|
||||
private function getCacheKey(string $type, string $channel): string
|
||||
{
|
||||
return $this->cachePrefix . $type . '.' . $channel;
|
||||
return $this->cachePrefix.$type.'.'.$channel;
|
||||
}
|
||||
}
|
||||
@@ -223,6 +223,51 @@ class PermissionService
|
||||
return $this->permissionRepository->getAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 편집기 표시 권한 후보 목록을 반환합니다.
|
||||
*
|
||||
* 코어 + 활성 확장 권한 전체를 `{key, name}` 형태로 평탄화합니다. `key` 는 권한
|
||||
* 식별자(예: `core.users.read`), `name` 은 지정 로케일 친화 표시명(다국어 array
|
||||
* 의 해당 로케일 → 첫 값 → 식별자 순 폴백)입니다. 편집기 속성 모달의 표시 권한
|
||||
* TagInput 후보로 사용됩니다.
|
||||
*
|
||||
* 자식을 가진 상위(카테고리) 권한은 실제 할당 불가하므로 제외하고, 리프 노드
|
||||
* (`isAssignable` — 자식 없음)만 후보로 반환합니다. 카테고리 행이 후보에 섞여
|
||||
* 표시되던 결함을 차단합니다.
|
||||
*
|
||||
* @param string $locale 표시명 로케일
|
||||
* @return array<int, array{key: string, name: string}> 권한 후보 목록 (리프 권한)
|
||||
*/
|
||||
public function getPermissionCandidates(string $locale): array
|
||||
{
|
||||
$all = $this->permissionRepository->getAll();
|
||||
|
||||
// 다른 권한의 parent_id 로 참조되는 ID 집합 = 카테고리(자식 보유). N+1 회피를 위해
|
||||
// 메모리에서 1회 계산한다(getAll 로 이미 전량 로드됨).
|
||||
$parentIds = $all
|
||||
->pluck('parent_id')
|
||||
->filter(fn ($id): bool => $id !== null)
|
||||
->unique()
|
||||
->flip();
|
||||
|
||||
return $all
|
||||
->reject(fn (Permission $permission): bool => $parentIds->has($permission->id))
|
||||
->map(function (Permission $permission) use ($locale): array {
|
||||
$name = $permission->name;
|
||||
$label = is_array($name)
|
||||
? ($name[$locale] ?? (reset($name) ?: $permission->identifier))
|
||||
: (is_string($name) && $name !== '' ? $name : $permission->identifier);
|
||||
|
||||
return [
|
||||
'key' => (string) $permission->identifier,
|
||||
'name' => (string) $label,
|
||||
];
|
||||
})
|
||||
->filter(fn (array $row): bool => $row['key'] !== '')
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 권한을 ID로 조회합니다.
|
||||
*
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Exceptions\PluginOperationException;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Exceptions\PluginOperationException;
|
||||
use App\Extension\Helpers\ChangelogParser;
|
||||
use App\Extension\Helpers\EditorSpecAssembler;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\ZipInstallHelper;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -106,11 +108,12 @@ class PluginService
|
||||
|
||||
return $this->pluginManager->getPluginUninstallInfo($pluginName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인을 설치합니다 (before/after_install 훅 발화 + ValidationException 변환).
|
||||
*
|
||||
* @param string $pluginName 플러그인 식별자
|
||||
* @param \App\Extension\Vendor\VendorMode $vendorMode vendor 설치 모드 (Auto/Composer/Bundled)
|
||||
* @param VendorMode $vendorMode vendor 설치 모드 (Auto/Composer/Bundled)
|
||||
* @param bool $force Updating/Failed 등 진행 중 상태도 무시하고 강제 설치 여부
|
||||
* @return array|null 설치된 플러그인 정보 또는 설치 실패 시 null
|
||||
*
|
||||
@@ -118,7 +121,7 @@ class PluginService
|
||||
*/
|
||||
public function installPlugin(
|
||||
string $pluginName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
VendorMode $vendorMode = VendorMode::Auto,
|
||||
bool $force = false,
|
||||
): ?array {
|
||||
HookManager::doAction('core.plugins.before_install', $pluginName);
|
||||
@@ -143,6 +146,7 @@ class PluginService
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인을 활성화합니다 (before/after_activate 훅 발화 + ValidationException 변환).
|
||||
*
|
||||
@@ -185,6 +189,7 @@ class PluginService
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인을 비활성화합니다 (before/after_deactivate 훅 발화 + ValidationException 변환).
|
||||
*
|
||||
@@ -225,6 +230,7 @@ class PluginService
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인을 제거합니다 (before/after_uninstall 훅 발화).
|
||||
*
|
||||
@@ -483,7 +489,7 @@ class PluginService
|
||||
* 지정된 플러그인을 업데이트합니다.
|
||||
*
|
||||
* @param string $pluginName 업데이트할 플러그인 identifier
|
||||
* @param \App\Extension\Vendor\VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param string $layoutStrategy 레이아웃 전략 (overwrite|keep)
|
||||
* @param bool $force 코어 버전 비호환 강제 우회 (위험 — 사용자 명시 필요)
|
||||
* @return array 업데이트 결과 (identifier, from_version, to_version 등)
|
||||
@@ -492,7 +498,7 @@ class PluginService
|
||||
*/
|
||||
public function updatePlugin(
|
||||
string $pluginName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
VendorMode $vendorMode = VendorMode::Auto,
|
||||
string $layoutStrategy = 'overwrite',
|
||||
bool $force = false,
|
||||
): array {
|
||||
@@ -613,6 +619,82 @@ class PluginService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 편집기 스펙(editor-spec.json) 디코드 결과를 반환합니다.
|
||||
*
|
||||
* 활성 플러그인만 대상으로 하며, 활성 디렉토리 → _bundled 폴백 순으로 읽습니다.
|
||||
* editor-spec.json 은 수작업 작성 파일로 플러그인 루트(plugin.json 옆)에 둡니다.
|
||||
* 파일 미존재/미작성 시 spec=null 로 폴백합니다(편집 컨트롤 부재).
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자 (vendor-plugin 형식)
|
||||
* @return array{success: bool, spec: array<string, mixed>|null, error: string|null}
|
||||
*/
|
||||
public function getEditorSpec(string $identifier): array
|
||||
{
|
||||
$plugin = $this->pluginRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $plugin || $plugin->status !== ExtensionStatus::Active->value) {
|
||||
return ['success' => false, 'spec' => null, 'error' => 'plugin_not_found'];
|
||||
}
|
||||
|
||||
// 분할 editor-spec.json 은 manifest + `$include` 블록으로 구성되므로
|
||||
// 단순 디코드가 아닌 합본이 필요하다. 활성 디렉토리만 기준으로 합본한다
|
||||
// (_bundled 폴백 없음). _bundled 작업분은 plugin:update 로 활성에
|
||||
// 반영된 뒤에만 런타임에 보인다. 미분할 파일은 원본 그대로(하위 호환).
|
||||
$spec = EditorSpecAssembler::assemble(
|
||||
base_path("plugins/{$identifier}/editor-spec.json")
|
||||
);
|
||||
|
||||
return ['success' => true, 'spec' => $spec, 'error' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 컴포넌트 매니페스트(components.json) 디코드 결과를 반환합니다.
|
||||
*
|
||||
* components.json 은 plugin:build 산출물로 플러그인 루트에 둡니다.
|
||||
* 활성 디렉토리 → _bundled 폴백 순으로 읽으며, 미생성(구버전 플러그인) 시
|
||||
* components=null 로 폴백합니다(무손실 보존 디그레이드 — 원칙 4.6).
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return array{success: bool, components: array<string, mixed>|null, error: string|null}
|
||||
*/
|
||||
public function getComponents(string $identifier): array
|
||||
{
|
||||
$plugin = $this->pluginRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $plugin || $plugin->status !== ExtensionStatus::Active->value) {
|
||||
return ['success' => false, 'components' => null, 'error' => 'plugin_not_found'];
|
||||
}
|
||||
|
||||
$components = $this->readJsonWithBundledFallback("plugins/{$identifier}/components.json");
|
||||
|
||||
return ['success' => true, 'components' => $components, 'error' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 디렉토리 → _bundled 폴백 순으로 JSON 파일을 읽어 디코드합니다.
|
||||
*
|
||||
* @param string $relativePath base_path 기준 상대 경로 (plugins/{id}/file.json)
|
||||
* @return array<string, mixed>|null 디코드된 배열, 미존재/파싱 실패 시 null
|
||||
*/
|
||||
private function readJsonWithBundledFallback(string $relativePath): ?array
|
||||
{
|
||||
$bundledPath = preg_replace('#^plugins/#', 'plugins/_bundled/', $relativePath, 1);
|
||||
$candidates = [base_path($relativePath), base_path((string) $bundledPath)];
|
||||
|
||||
foreach ($candidates as $path) {
|
||||
if (! file_exists($path) || ! is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
$decoded = json_decode((string) file_get_contents($path), true);
|
||||
if (is_array($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* MIME 타입 감지
|
||||
*
|
||||
@@ -773,6 +855,7 @@ class PluginService
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 업로드된 ZIP 파일로부터 플러그인을 추출/검증하고 _pending 으로 이동 후 설치합니다.
|
||||
*
|
||||
|
||||
@@ -423,6 +423,12 @@ class SettingsService
|
||||
return $firstImage?->download_url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 환경설정 값을 저장합니다.
|
||||
*
|
||||
* @param array $settings 카테고리별 설정 데이터
|
||||
* @return bool 저장 성공 여부
|
||||
*/
|
||||
public function saveSettings(array $settings): bool
|
||||
{
|
||||
// Before 훅
|
||||
@@ -612,6 +618,13 @@ class SettingsService
|
||||
return $this->configRepository->get($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 설정 값을 저장합니다.
|
||||
*
|
||||
* @param string $key 설정 키 (예: 'general.site_name')
|
||||
* @param mixed $value 저장할 값
|
||||
* @return bool 저장 성공 여부
|
||||
*/
|
||||
public function setSetting(string $key, mixed $value): bool
|
||||
{
|
||||
// Before 훅
|
||||
@@ -1012,9 +1025,24 @@ class SettingsService
|
||||
private function getDiskUsage(): array
|
||||
{
|
||||
$path = PHP_OS_FAMILY === 'Windows' ? 'C:' : '/';
|
||||
$total = disk_total_space($path);
|
||||
$free = disk_free_space($path);
|
||||
$used = $total - $free;
|
||||
|
||||
// open_basedir 제한 환경에서 disk_*_space 가 warning → ErrorException 이 되지 않도록
|
||||
// @ 억제 + numeric 체크 (공개#40, getMemoryUsage 폴백 패턴 재사용).
|
||||
$totalRaw = @disk_total_space($path);
|
||||
$freeRaw = @disk_free_space($path);
|
||||
$total = is_numeric($totalRaw) ? (int) $totalRaw : 0;
|
||||
$free = is_numeric($freeRaw) ? (int) $freeRaw : 0;
|
||||
|
||||
if ($total <= 0) {
|
||||
return [
|
||||
'total' => __('common.unknown'),
|
||||
'used' => __('common.unknown'),
|
||||
'free' => __('common.unknown'),
|
||||
'percentage' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$used = max(0, $total - $free);
|
||||
|
||||
return [
|
||||
'total' => $this->formatBytes($total),
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\TemplateCustomTranslationRepositoryInterface;
|
||||
use App\Exceptions\ConcurrentModificationException;
|
||||
use App\Models\TemplateCustomTranslation;
|
||||
use App\Services\LanguagePack\CustomTranslationUsageScanner;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Database\QueryException;
|
||||
|
||||
/**
|
||||
* 템플릿 커스텀 다국어 키 서비스.
|
||||
*
|
||||
* 레이아웃 편집기 인라인 편집에서 평문을 `$t:custom.{layout}.{seq}` 키로
|
||||
* 전환할 때 사용하는 동적 다국어 키의 생성/수정/삭제를 담당합니다.
|
||||
*
|
||||
* 책임:
|
||||
* - 키 자동 생성 (`custom.{layoutKey}.{seq}`)
|
||||
* - seq 충돌 시 재시도 (unique 제약 위반 → seq 증가)
|
||||
* - 신규 키 생성 시 모든 활성 로케일에 폴백 시드
|
||||
* - 낙관적 잠금 (`lock_version` — update 경로)
|
||||
* - 커스텀 키 CRUD 시 다국어 캐시 무효화
|
||||
*/
|
||||
class TemplateCustomTranslationService
|
||||
{
|
||||
/**
|
||||
* seq 충돌 재시도 최대 횟수.
|
||||
*/
|
||||
private const MAX_SEQ_RETRY = 5;
|
||||
|
||||
/**
|
||||
* @param TemplateCustomTranslationRepositoryInterface $repository 커스텀 다국어 키 리포지토리
|
||||
* @param CacheInterface $cache 캐시 드라이버
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly TemplateCustomTranslationRepositoryInterface $repository,
|
||||
private readonly CacheInterface $cache,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 커스텀 다국어 키 목록을 조회합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $layoutName 레이아웃 이름 필터
|
||||
* @param string|null $status 상태 필터
|
||||
* @return Collection<int, TemplateCustomTranslation> 커스텀 키 컬렉션
|
||||
*/
|
||||
public function getList(int $templateId, ?string $layoutName = null, ?string $status = null): Collection
|
||||
{
|
||||
return $this->repository->getByTemplateId($templateId, $layoutName, $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 커스텀 다국어 키를 조회합니다.
|
||||
*
|
||||
* @param int $id 커스텀 키 ID
|
||||
* @return TemplateCustomTranslation|null 찾은 모델 또는 null
|
||||
*/
|
||||
public function find(int $id): ?TemplateCustomTranslation
|
||||
{
|
||||
return $this->repository->findById($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 다국어 키를 생성합니다.
|
||||
*
|
||||
* 키는 `custom.{layoutKey}.{seq}` 형식으로 자동 생성하며, unique 제약
|
||||
* (template_id + translation_key) 위반 시 seq 를 증가시켜 재시도합니다.
|
||||
* `values` 는 모든 활성 로케일 키를 채우되 편집 로케일엔 입력값,
|
||||
* 나머지 로케일엔 동일 입력값을 폴백 시드합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 생성 출처 레이아웃 이름 (예: board/list)
|
||||
* @param string $locale 편집 로케일
|
||||
* @param string $value 편집 로케일의 입력값 (평문)
|
||||
* @param int|null $createdBy 생성자 ID
|
||||
* @return TemplateCustomTranslation 생성된 모델
|
||||
*/
|
||||
public function createKey(
|
||||
int $templateId,
|
||||
string $layoutName,
|
||||
string $locale,
|
||||
string $value,
|
||||
?int $createdBy = null,
|
||||
): TemplateCustomTranslation {
|
||||
$layoutKey = $this->normalizeLayoutKey($layoutName);
|
||||
$values = $this->seedLocaleValues($locale, $value);
|
||||
|
||||
$seq = $this->repository->getMaxSeq($templateId, $layoutKey) + 1;
|
||||
|
||||
for ($attempt = 0; $attempt < self::MAX_SEQ_RETRY; $attempt++) {
|
||||
$translationKey = "custom.{$layoutKey}.{$seq}";
|
||||
|
||||
try {
|
||||
$model = $this->repository->create([
|
||||
'template_id' => $templateId,
|
||||
'layout_name' => $layoutName,
|
||||
'translation_key' => $translationKey,
|
||||
'values' => $values,
|
||||
'status' => 'active',
|
||||
'created_by' => $createdBy,
|
||||
'updated_by' => $createdBy,
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$this->invalidateLanguageCache();
|
||||
|
||||
return $model;
|
||||
} catch (QueryException $e) {
|
||||
// unique(template_id, translation_key) 위반 → seq 증가 재시도.
|
||||
if (! $this->isUniqueViolation($e)) {
|
||||
throw $e;
|
||||
}
|
||||
$seq++;
|
||||
}
|
||||
}
|
||||
|
||||
// 재시도 한도 초과 — 마지막 시도는 예외를 그대로 전파.
|
||||
$translationKey = "custom.{$layoutKey}.{$seq}";
|
||||
$model = $this->repository->create([
|
||||
'template_id' => $templateId,
|
||||
'layout_name' => $layoutName,
|
||||
'translation_key' => $translationKey,
|
||||
'values' => $values,
|
||||
'status' => 'active',
|
||||
'created_by' => $createdBy,
|
||||
'updated_by' => $createdBy,
|
||||
'lock_version' => 0,
|
||||
]);
|
||||
|
||||
$this->invalidateLanguageCache();
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 다국어 키의 로케일별 값을 수정합니다 (낙관적 잠금).
|
||||
*
|
||||
* `expectedLockVersion` 이 현재 `lock_version` 과 다르면
|
||||
* ConcurrentModificationException 을 던집니다.
|
||||
*
|
||||
* @param int $id 커스텀 키 ID
|
||||
* @param array<string, string> $values 로케일별 번역 값
|
||||
* @param int $expectedLockVersion 편집기가 보유한 lock_version
|
||||
* @param int|null $updatedBy 수정자 ID
|
||||
* @return TemplateCustomTranslation 수정된 모델
|
||||
*
|
||||
* @throws ConcurrentModificationException 잠금 버전 불일치 시
|
||||
*/
|
||||
public function updateValues(
|
||||
int $id,
|
||||
array $values,
|
||||
int $expectedLockVersion,
|
||||
?int $updatedBy = null,
|
||||
): TemplateCustomTranslation {
|
||||
$model = $this->repository->findById($id);
|
||||
|
||||
if ($model === null) {
|
||||
throw new ModelNotFoundException(
|
||||
"Custom translation not found: id={$id}"
|
||||
);
|
||||
}
|
||||
|
||||
$currentVersion = (int) ($model->lock_version ?? 0);
|
||||
|
||||
if ($expectedLockVersion !== $currentVersion) {
|
||||
throw new ConcurrentModificationException(
|
||||
currentVersion: $currentVersion,
|
||||
expectedVersion: $expectedLockVersion,
|
||||
resource: "template_custom_translations:{$model->id}",
|
||||
);
|
||||
}
|
||||
|
||||
$updated = $this->repository->update(
|
||||
$id,
|
||||
[
|
||||
'values' => $values,
|
||||
'updated_by' => $updatedBy,
|
||||
],
|
||||
$currentVersion + 1,
|
||||
);
|
||||
|
||||
$this->invalidateLanguageCache();
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 다국어 키를 삭제합니다.
|
||||
*
|
||||
* @param int $id 커스텀 키 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function deleteKey(int $id): bool
|
||||
{
|
||||
$deleted = $this->repository->delete($id);
|
||||
|
||||
if ($deleted) {
|
||||
$this->invalidateLanguageCache();
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 다국어 키를 일괄 삭제합니다 (관리 모달 "선택 삭제"/"미사용 전체 삭제").
|
||||
*
|
||||
* 각 ID 를 Repository 위임으로 삭제하고, 1건 이상 삭제 시 다국어 캐시를
|
||||
* 1회만 무효화합니다 (개별 deleteKey 의 N회 무효화 회피).
|
||||
*
|
||||
* @param array<int, int> $ids 삭제할 커스텀 키 ID 목록
|
||||
* @return int 실제 삭제된 행 수
|
||||
*/
|
||||
public function deleteKeys(array $ids): int
|
||||
{
|
||||
$deleted = 0;
|
||||
|
||||
foreach ($ids as $id) {
|
||||
if ($this->repository->delete((int) $id)) {
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($deleted > 0) {
|
||||
$this->invalidateLanguageCache();
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 이름을 키 네임스페이스로 정규화합니다.
|
||||
*
|
||||
* `board/list` → `board_list`. 정규화 규칙은 스캐너와 단일 SSoT 를 공유합니다
|
||||
* (좀비 감지 시 키에서 추출한 layoutKey 와 일관 매칭되도록 —.2).
|
||||
*
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return string 정규화된 키 네임스페이스
|
||||
*/
|
||||
private function normalizeLayoutKey(string $layoutName): string
|
||||
{
|
||||
return CustomTranslationUsageScanner::normalizeLayoutKey($layoutName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 신규 키의 모든 활성 로케일 값을 시드합니다.
|
||||
*
|
||||
* 편집 로케일엔 입력값을, 나머지 활성 로케일엔 동일 입력값을 폴백으로
|
||||
* 채웁니다 (평문 → $t:key 전환 시 폴백 시드).
|
||||
*
|
||||
* @param string $editLocale 편집 로케일
|
||||
* @param string $value 편집 로케일 입력값
|
||||
* @return array<string, string> 로케일별 값
|
||||
*/
|
||||
private function seedLocaleValues(string $editLocale, string $value): array
|
||||
{
|
||||
$locales = $this->activeLocales();
|
||||
$values = [];
|
||||
|
||||
foreach ($locales as $locale) {
|
||||
$values[$locale] = $value;
|
||||
}
|
||||
|
||||
// 편집 로케일이 supported_locales 에 없더라도 안전하게 포함.
|
||||
$values[$editLocale] = $value;
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성(지원) 로케일 목록을 반환합니다.
|
||||
*
|
||||
* @return array<int, string> 로케일 목록
|
||||
*/
|
||||
private function activeLocales(): array
|
||||
{
|
||||
$locales = config('app.supported_locales', ['ko', 'en']);
|
||||
|
||||
return is_array($locales) && $locales !== [] ? array_values($locales) : ['ko', 'en'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 캐시를 무효화합니다.
|
||||
*
|
||||
* `serveLanguage` 캐시 키가 `template.language.{id}.{locale}.v{cacheVersion}`
|
||||
* 형태로 `ext.cache_version` 을 포함하므로, 이 값을 갱신하면 다음
|
||||
* `loadTranslations` 가 재fetch 합니다.
|
||||
*/
|
||||
private function invalidateLanguageCache(): void
|
||||
{
|
||||
$this->cache->put('ext.cache_version', time());
|
||||
}
|
||||
|
||||
/**
|
||||
* QueryException 이 unique 제약 위반인지 판별합니다.
|
||||
*
|
||||
* @param QueryException $e 쿼리 예외
|
||||
* @return bool unique 위반 여부
|
||||
*/
|
||||
private function isUniqueViolation(QueryException $e): bool
|
||||
{
|
||||
// SQLSTATE 23000 (integrity constraint violation). MySQL 1062 / SQLite UNIQUE.
|
||||
return (string) ($e->errorInfo[0] ?? '') === '23000';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Contracts\Repositories\TemplateLayoutAttachmentRepositoryInterface;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Models\TemplateLayoutAttachment;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* 템플릿 레이아웃 첨부 파일 서비스
|
||||
*
|
||||
* 레이아웃 편집 중 업로드되는 파일(배경 이미지 등)의 업로드·조회·삭제를 처리한다.
|
||||
* 파일 저장은 코어 StorageInterface(CoreStorageDriver)를 통해서만 수행하고,
|
||||
* 저장 위치(disk/path)와 메타데이터를 template_layout_attachments 에 기록한다.
|
||||
* (Storage::disk() 직접 호출 금지 — CLAUDE.md 스토리지 규칙)
|
||||
*/
|
||||
class TemplateLayoutAttachmentService
|
||||
{
|
||||
/** 스토리지 카테고리 — {category}/{path} 경로 패턴의 prefix */
|
||||
private const STORAGE_CATEGORY = 'template-layout-attachments';
|
||||
|
||||
/**
|
||||
* @param TemplateLayoutAttachmentRepositoryInterface $repository 첨부 리포지토리
|
||||
* @param TemplateRepositoryInterface $templateRepository 템플릿 리포지토리
|
||||
* @param StorageInterface $storage 코어 스토리지 드라이버
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateLayoutAttachmentRepositoryInterface $repository,
|
||||
private TemplateRepositoryInterface $templateRepository,
|
||||
private StorageInterface $storage,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 첨부 파일을 업로드하고 행을 생성합니다.
|
||||
*
|
||||
* @param string $templateIdentifier 템플릿 식별자 (vendor-name 형식)
|
||||
* @param UploadedFile $file 업로드 파일
|
||||
* @param string|null $layoutName 사용 출처 레이아웃 이름
|
||||
* @return array{success: bool, attachment: TemplateLayoutAttachment|null, url: string|null, error: string|null}
|
||||
*/
|
||||
public function upload(string $templateIdentifier, UploadedFile $file, ?string $layoutName = null): array
|
||||
{
|
||||
$template = $this->templateRepository->findByIdentifier($templateIdentifier);
|
||||
if (! $template) {
|
||||
return ['success' => false, 'attachment' => null, 'url' => null, 'error' => 'template_not_found'];
|
||||
}
|
||||
|
||||
// 저장 경로 — 템플릿 식별자/날짜별 디렉토리 + UUID 파일명 (충돌 회피)
|
||||
$storedFilename = Str::uuid().'.'.$file->getClientOriginalExtension();
|
||||
$relativePath = "{$templateIdentifier}/".date('Y/m/d')."/{$storedFilename}";
|
||||
|
||||
$disk = config('attachment.disk', 'attachments');
|
||||
$stored = $this->storage
|
||||
->withDisk($disk)
|
||||
->put(self::STORAGE_CATEGORY, $relativePath, file_get_contents($file->getRealPath()));
|
||||
|
||||
if (! $stored) {
|
||||
return ['success' => false, 'attachment' => null, 'url' => null, 'error' => 'storage_failed'];
|
||||
}
|
||||
|
||||
$attachment = $this->repository->create([
|
||||
'template_id' => $template->id,
|
||||
'layout_name' => $layoutName,
|
||||
'disk' => $disk,
|
||||
'path' => $relativePath,
|
||||
'original_name' => $file->getClientOriginalName(),
|
||||
'mime_type' => $file->getMimeType(),
|
||||
'size' => $file->getSize(),
|
||||
'created_by' => Auth::id(),
|
||||
]);
|
||||
|
||||
Log::info('레이아웃 첨부 파일 업로드 완료', [
|
||||
'attachment_id' => $attachment->id,
|
||||
'template_id' => $template->id,
|
||||
'path' => $relativePath,
|
||||
]);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'attachment' => $attachment,
|
||||
'url' => $this->resolveUrl($attachment),
|
||||
'error' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿(+선택적 레이아웃)별 첨부 파일 목록을 조회합니다.
|
||||
*
|
||||
* @param string $templateIdentifier 템플릿 식별자
|
||||
* @param string|null $layoutName 레이아웃 이름 (null 이면 템플릿 전체)
|
||||
* @return array{success: bool, attachments: Collection<int, TemplateLayoutAttachment>|null, error: string|null}
|
||||
*/
|
||||
public function list(string $templateIdentifier, ?string $layoutName = null): array
|
||||
{
|
||||
$template = $this->templateRepository->findByIdentifier($templateIdentifier);
|
||||
if (! $template) {
|
||||
return ['success' => false, 'attachments' => null, 'error' => 'template_not_found'];
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'attachments' => $this->repository->listForTemplate($template->id, $layoutName),
|
||||
'error' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부 파일을 삭제합니다 — 스토리지 파일 실삭제 후 DB 행 삭제.
|
||||
*
|
||||
* DB CASCADE 에 의존하지 않고 스토리지 파일을 명시적으로 삭제한다
|
||||
* (CLAUDE.md "DB CASCADE 의존 삭제 금지" — 파일 정리 보장).
|
||||
*
|
||||
* @param TemplateLayoutAttachment $attachment 삭제할 첨부 파일
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(TemplateLayoutAttachment $attachment): bool
|
||||
{
|
||||
// 1. 스토리지 파일 실삭제 (명시적 — CASCADE 미의존)
|
||||
$this->storage
|
||||
->withDisk($attachment->disk)
|
||||
->delete(self::STORAGE_CATEGORY, $attachment->path);
|
||||
|
||||
// 2. DB 행 삭제
|
||||
return $this->repository->delete($attachment);
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부 파일의 공개 접근 URL을 생성합니다.
|
||||
*
|
||||
* 첨부 파일은 비공개 `attachments` 디스크에 저장되어 직접 공개 URL 이 없다
|
||||
* (`StorageInterface::url()` 은 public 디스크 전용). 발행된 배경 이미지는 일반
|
||||
* 사이트 방문자에게도 로드되어야 하므로, 인증 불필요한 공개 서빙 라우트
|
||||
* (`PublicTemplateController::serveFile`)의 URL 을 돌려준다. 라우트는 첨부 id 로
|
||||
* 키되며 서빙 시 첨부가 해당 템플릿 소속인지 검증한다.
|
||||
*
|
||||
* @param TemplateLayoutAttachment $attachment 첨부 파일
|
||||
* @return string 공개 서빙 URL
|
||||
*/
|
||||
public function resolveUrl(TemplateLayoutAttachment $attachment): string
|
||||
{
|
||||
$template = $attachment->template;
|
||||
$identifier = $template?->identifier ?? (string) $attachment->template_id;
|
||||
|
||||
return route('api.public.templates.layout-attachment-file', [
|
||||
'identifier' => $identifier,
|
||||
'attachment' => $attachment->id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 서빙 가능한 첨부 파일의 절대 경로를 돌려줍니다.
|
||||
*
|
||||
* 첨부가 주어진 템플릿 소속인지 검증하고, 스토리지에 파일이 실제로 존재하면
|
||||
* 컨트롤러가 스트림할 수 있는 절대 파일시스템 경로를 반환한다. 소속 불일치 /
|
||||
* 파일 부재 시 null (컨트롤러가 404).
|
||||
*
|
||||
* @param string $templateIdentifier 요청 경로의 템플릿 식별자
|
||||
* @param TemplateLayoutAttachment $attachment 서빙 대상 첨부
|
||||
* @return string|null 절대 파일 경로 또는 null
|
||||
*/
|
||||
public function getServableFilePath(string $templateIdentifier, TemplateLayoutAttachment $attachment): ?string
|
||||
{
|
||||
$template = $this->templateRepository->findByIdentifier($templateIdentifier);
|
||||
// 경로 식별자와 첨부의 소속 템플릿이 일치해야 한다 (교차 템플릿 접근 차단).
|
||||
if (! $template || $attachment->template_id !== $template->id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$driver = $this->storage->withDisk($attachment->disk);
|
||||
if (! $driver->exists(self::STORAGE_CATEGORY, $attachment->path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 절대 경로 — {category base}/{relative path}. fileResponse 가 절대 경로를 요구.
|
||||
return rtrim($driver->getBasePath(self::STORAGE_CATEGORY), '/\\').'/'.$attachment->path;
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Exceptions\TemplateOperationException;
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Contracts\Extension\TemplateManagerInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Exceptions\TemplateNotFoundException;
|
||||
use App\Exceptions\TemplateOperationException;
|
||||
use App\Extension\Helpers\ChangelogParser;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\Helpers\ZipInstallHelper;
|
||||
@@ -27,7 +28,8 @@ class TemplateService
|
||||
private TemplateRepositoryInterface $templateRepository,
|
||||
private TemplateManagerInterface $templateManager,
|
||||
private ModuleManagerInterface $moduleManager,
|
||||
private PluginManagerInterface $pluginManager
|
||||
private PluginManagerInterface $pluginManager,
|
||||
private LayoutVersionRepositoryInterface $layoutVersionRepository
|
||||
) {
|
||||
// TemplateManager 초기화 (템플릿 스캔)
|
||||
$this->templateManager->loadTemplates();
|
||||
@@ -846,11 +848,28 @@ class TemplateService
|
||||
// 4. 활성화된 플러그인들의 다국어 데이터 병합 (fragment 해석 포함)
|
||||
$pluginLangData = $this->loadActivePluginsLanguageData($locale);
|
||||
|
||||
// 5. 템플릿 데이터와 모듈/플러그인 데이터 병합
|
||||
$mergedData = array_merge($templateLangData, $moduleLangData, $pluginLangData);
|
||||
// 5. 코어 자체의 프론트엔드 다국어 자원 로드 (베이스 레이어)
|
||||
// 어떤 템플릿이 부팅되든 코어 키(`core.*`) 가 자동 노출되도록
|
||||
// 가장 낮은 우선순위로 합류시킨다.
|
||||
$coreLangData = $this->loadCoreFrontendLanguageData($locale);
|
||||
|
||||
// 6. 활성 언어팩의 frontend/*.json 병합 (가장 높은 우선순위 — 코어/모듈/플러그인 모두 덮어쓸 수 있음)
|
||||
$mergedData = \App\Extension\HookManager::applyFilters(
|
||||
// 6. 병합 순서: 코어 → 템플릿 → 모듈 → 플러그인 (코어가 가장 낮은 우선순위)
|
||||
// 모듈/플러그인은 식별자 wrap 으로 충돌 없음. 코어 키는 `core.*` prefix 컨벤션.
|
||||
//
|
||||
// deep merge 사용: 동일 top-level 키(예: `layout_editor`) 의
|
||||
// 하위 트리를 재귀 병합한다. 과거 array_merge 는 shallow 라서 템플릿이
|
||||
// `layout_editor.palette` 만 정의해도 코어의 `layout_editor.chrome` 등
|
||||
// 전체 트리가 통째로 교체되어 chrome/device/zoom 키가 미해석되었다.
|
||||
// leaf 충돌 시 우선순위는 기존과 동일(코어 < 템플릿 < 모듈 < 플러그인).
|
||||
$mergedData = $this->deepMergeLanguageData(
|
||||
$coreLangData,
|
||||
$templateLangData,
|
||||
$moduleLangData,
|
||||
$pluginLangData
|
||||
);
|
||||
|
||||
// 7. 활성 언어팩의 frontend/*.json 병합 (가장 높은 우선순위 — 코어/모듈/플러그인 모두 덮어쓸 수 있음)
|
||||
$mergedData = HookManager::applyFilters(
|
||||
'template.language.merge',
|
||||
$mergedData,
|
||||
$identifier,
|
||||
@@ -864,6 +883,107 @@ class TemplateService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어/템플릿/모듈/플러그인 다국어 데이터를 재귀 병합합니다.
|
||||
*
|
||||
* PHP `array_merge` 는 shallow merge 라서 동일 top-level 키(예: `layout_editor`) 가
|
||||
* 양쪽에 있으면 뒤에 오는 쪽이 트리 전체를 통째로 교체한다. 본 helper 는 연관
|
||||
* 배열(assoc) 끼리는 재귀적으로 leaf 까지 내려가며 병합하고, 시퀀셜 배열(list)
|
||||
* 이나 scalar leaf 는 뒤에 오는 값으로 덮어쓴다.
|
||||
*
|
||||
* 우선순위(낮음 → 높음): 코어 < 템플릿 < 모듈 < 플러그인. 같은 키에 leaf 충돌
|
||||
* 시 뒤에 오는 입력 우선. 이 정책은 기존 `array_merge` 호출 순서와 동일.
|
||||
*
|
||||
* 시퀀셜 배열 판정: 키가 `0, 1, 2, ...` 연속 정수 → list. 그 외 → assoc.
|
||||
* lang JSON 은 본질적으로 assoc 트리(`{ "layout_editor": { "chrome": { ... } } }`)
|
||||
* 이고 leaf 가 string 인 게 일반적이라 list 케이스는 드물지만, 어떤 키가 검증
|
||||
* 룰 배열(`["required", "string"]`) 같은 list 를 leaf 로 둘 수 있어 명시적으로
|
||||
* 분기한다.
|
||||
*
|
||||
* @param array ...$layers 병합할 lang 배열들 (낮은 우선순위 → 높은 우선순위)
|
||||
* @return array 병합된 lang 데이터
|
||||
*/
|
||||
private function deepMergeLanguageData(array ...$layers): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($layers as $layer) {
|
||||
$result = $this->deepMergeTwo($result, $layer);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 두 배열을 재귀 병합합니다 (deepMergeLanguageData 의 내부 helper).
|
||||
*
|
||||
* @param array $base 기존 누적 결과 (낮은 우선순위)
|
||||
* @param array $override 새로 합칠 입력 (높은 우선순위)
|
||||
* @return array 병합 결과
|
||||
*/
|
||||
private function deepMergeTwo(array $base, array $override): array
|
||||
{
|
||||
foreach ($override as $key => $value) {
|
||||
if (
|
||||
array_key_exists($key, $base)
|
||||
&& is_array($base[$key])
|
||||
&& is_array($value)
|
||||
&& $this->isAssocArray($base[$key])
|
||||
&& $this->isAssocArray($value)
|
||||
) {
|
||||
// 양쪽이 assoc 트리 → 재귀
|
||||
$base[$key] = $this->deepMergeTwo($base[$key], $value);
|
||||
} else {
|
||||
// list, scalar, 일방만 array → 덮어쓰기
|
||||
$base[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $base;
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열이 연관 배열(assoc) 인지 판정합니다.
|
||||
*
|
||||
* 빈 배열은 assoc 으로 취급해 양쪽이 빈 경우에도 재귀 호출이 안전하게 종료
|
||||
* 되도록 한다. 키가 `0, 1, 2, ...` 연속 정수 sequence 면 list 로 판정.
|
||||
*
|
||||
* @param array $arr 검사할 배열
|
||||
* @return bool assoc 여부
|
||||
*/
|
||||
private function isAssocArray(array $arr): bool
|
||||
{
|
||||
if ($arr === []) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ! array_is_list($arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 자체의 프론트엔드 다국어 자원을 로드합니다.
|
||||
*
|
||||
* 어떤 템플릿이 부팅되든 코어 키(`core.*`) 가 자동 노출되도록
|
||||
* 1단계(템플릿 lang) 앞에서 베이스 데이터로 로드됩니다.
|
||||
*
|
||||
* 모듈/플러그인/템플릿과 동일한 디렉토리 구조(`lang/{locale}.json` +
|
||||
* `lang/partial/`) 를 사용하며, $partial 디렉티브 해석도 동일하게 처리됩니다.
|
||||
*
|
||||
* @param string $locale 로케일 (ko, en 등)
|
||||
* @return array 코어 프론트엔드 다국어 데이터
|
||||
*/
|
||||
private function loadCoreFrontendLanguageData(string $locale): array
|
||||
{
|
||||
$coreLangPath = base_path("lang/{$locale}.json");
|
||||
|
||||
if (! file_exists($coreLangPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$data = $this->loadLanguageFileWithFragments($coreLangPath);
|
||||
|
||||
return is_array($data) ? $data : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 파일을 로드하고 $partial 디렉티브를 해석합니다.
|
||||
*
|
||||
@@ -1009,9 +1129,16 @@ class TemplateService
|
||||
? $this->loadActivePluginsRoutesData()
|
||||
: [];
|
||||
|
||||
// 9. 템플릿 routes와 모듈/플러그인 routes 병합
|
||||
// 9. 템플릿 자체 라우트에 source 태깅
|
||||
// 모듈/플러그인 라우트는 각 로더(loadActive*RoutesData)에서 이미 source 부여됨
|
||||
$templateRoutes = array_map(function ($route) {
|
||||
$route['source'] = ['kind' => 'template', 'identifier' => null];
|
||||
|
||||
return $route;
|
||||
}, $templateRoutesData['routes'] ?? []);
|
||||
|
||||
$mergedRoutes = array_merge(
|
||||
$templateRoutesData['routes'] ?? [],
|
||||
$templateRoutes,
|
||||
$moduleRoutes,
|
||||
$pluginRoutes
|
||||
);
|
||||
@@ -1024,7 +1151,18 @@ class TemplateService
|
||||
$identifier
|
||||
);
|
||||
|
||||
// 11. 최종 데이터 구성
|
||||
// 11. 필터 단계에서 주입된 시스템 라우트(preview 등)에 source 메타 fallback 부여
|
||||
// (라우트 트리 그룹핑은 template/module/plugin 3종만 표시,
|
||||
// source.kind='core' 인 라우트는 트리에서 제외)
|
||||
$mergedRoutes = array_map(function ($route) {
|
||||
if (! isset($route['source'])) {
|
||||
$route['source'] = ['kind' => 'core', 'identifier' => null];
|
||||
}
|
||||
|
||||
return $route;
|
||||
}, $mergedRoutes);
|
||||
|
||||
// 12. 최종 데이터 구성
|
||||
$resultData = [
|
||||
'version' => $templateRoutesData['version'] ?? '1.0.0',
|
||||
'routes' => $mergedRoutes,
|
||||
@@ -1037,6 +1175,448 @@ class TemplateService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 편집기용 routes 데이터를 source 태깅과 함께 반환합니다.
|
||||
*
|
||||
* `getRoutesDataWithModules` 와 동일하게 템플릿/모듈/플러그인 라우트에 `source`
|
||||
* (`{kind, identifier}`)를 태깅하지만, 편집기 요구사항에 맞춰 두 가지가 다르다:
|
||||
* - 활성/비활성 무관: 설치돼 있으나 비활성인 템플릿도 편집 가능해야 하므로
|
||||
* 활성 상태 가드를 적용하지 않는다.
|
||||
* - `_bundled` 폴백: 활성 디렉토리에 routes.json 이 없으면 `_bundled` 원본을 읽는다.
|
||||
*
|
||||
* source 태깅이 없으면 편집기 `buildRouteTree`(useRouteTree)가 `route.source.kind`
|
||||
* 접근에서 throw 하여 라우트 트리 전체가 network 에러로 무너진다 — 본 메서드가
|
||||
* 편집기 진입 routes 응답의 SSoT 다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return array{success: bool, data: array|null, error: string|null}
|
||||
*/
|
||||
public function getEditorRoutesDataWithModules(string $identifier): array
|
||||
{
|
||||
// 1. routes.json 경로 — 활성 디렉토리 우선, _bundled 폴백 (활성/비활성 무관).
|
||||
$candidates = [
|
||||
base_path("templates/{$identifier}/routes.json"),
|
||||
base_path("templates/_bundled/{$identifier}/routes.json"),
|
||||
];
|
||||
$routesFilePath = null;
|
||||
foreach ($candidates as $candidate) {
|
||||
if (file_exists($candidate)) {
|
||||
$routesFilePath = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($routesFilePath === null) {
|
||||
return ['success' => false, 'data' => null, 'error' => 'routes_not_found'];
|
||||
}
|
||||
|
||||
// 2. routes.json 디코드
|
||||
$templateRoutesData = json_decode((string) file_get_contents($routesFilePath), true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE || ! is_array($templateRoutesData)) {
|
||||
return ['success' => false, 'data' => null, 'error' => 'invalid_json'];
|
||||
}
|
||||
|
||||
// 3. 템플릿 타입(admin/user) — 모듈/플러그인 라우트 병합 분기에 사용.
|
||||
// DB 모델(비활성 포함) → 매니페스트 info → 'user' 순으로 폴백.
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
$templateType = $template->type
|
||||
?? ($this->getTemplateInfo($identifier)['type'] ?? 'user');
|
||||
|
||||
// 4. 템플릿 라우트에 source 태깅 (모듈/플러그인 로더는 자체 source 부여).
|
||||
$templateRoutes = array_map(function ($route) {
|
||||
$route['source'] = ['kind' => 'template', 'identifier' => null];
|
||||
|
||||
return $route;
|
||||
}, $templateRoutesData['routes'] ?? []);
|
||||
|
||||
$moduleRoutes = $this->loadActiveModulesRoutesData($templateType);
|
||||
$pluginRoutes = ($templateType === 'admin')
|
||||
? $this->loadActivePluginsRoutesData()
|
||||
: [];
|
||||
|
||||
$mergedRoutes = array_merge($templateRoutes, $moduleRoutes, $pluginRoutes);
|
||||
|
||||
// 5. 시스템 라우트 주입 필터 (getRoutesDataWithModules 와 동일 확장점).
|
||||
$mergedRoutes = HookManager::applyFilters(
|
||||
'core.routes.filter_merged',
|
||||
$mergedRoutes,
|
||||
$templateType,
|
||||
$identifier
|
||||
);
|
||||
|
||||
// 6. source 미부여 라우트(필터 주입 시스템 라우트 등)에 core fallback.
|
||||
$mergedRoutes = array_map(function ($route) {
|
||||
if (! isset($route['source'])) {
|
||||
$route['source'] = ['kind' => 'core', 'identifier' => null];
|
||||
}
|
||||
|
||||
return $route;
|
||||
}, $mergedRoutes);
|
||||
|
||||
// 7. base 레이아웃 + 인라인 모달 수집 — 위지윅
|
||||
// 편집기 라우트 트리의 `[공통 레이아웃]` · `[모달]` 그룹 SSoT. routes.json 에는
|
||||
// base/modal 정보가 없으므로 레이아웃 파일에서 직접 수집한다. 모듈/플러그인
|
||||
// 수집은 라우트 로더와 동일하게 템플릿 타입(admin/user)으로 필터링한다.
|
||||
$baseAndModals = $this->collectEditorBaseAndModals($identifier, $templateType);
|
||||
|
||||
// 8. 레이아웃별 현재(최신) 저장 버전 맵 — 라우트 트리 버전 배지.
|
||||
// 버전 이력이 있는 레이아웃만 포함(미저장 = 원본 → 배지 미표시). 템플릿이
|
||||
// DB 에 없으면(파일만 존재) 버전 이력도 없으므로 빈 맵.
|
||||
$layoutVersions = $template
|
||||
? $this->layoutVersionRepository->getCurrentVersionsByTemplateId($template->id)
|
||||
: [];
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'version' => $templateRoutesData['version'] ?? '1.0.0',
|
||||
'routes' => $mergedRoutes,
|
||||
'base_layouts' => $baseAndModals['base_layouts'],
|
||||
'modals' => $baseAndModals['modals'],
|
||||
'layout_versions' => $layoutVersions,
|
||||
],
|
||||
'error' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 라우트 트리의 `[공통 레이아웃]` · `[모달]` 그룹용 base 레이아웃 + 모달
|
||||
* 목록을 템플릿 + 활성 모듈/플러그인 레이아웃 파일에서 수집합니다.
|
||||
*
|
||||
* 다음 세 출처의 `layouts/` 를 재귀 순회해 수집한다(계획서 8.4.5 — "대상 템플릿의
|
||||
* 모든 레이아웃의 modals 섹션을 스캔"):
|
||||
* - 템플릿: `templates/{id}/layouts/` (활성 → `_bundled` 폴백). host_layout 접두사 없음.
|
||||
* - 활성 모듈: `modules/{id}/resources/layouts/`. host_layout 에 `{moduleId}.` 접두사.
|
||||
* - 활성 플러그인: `plugins/{id}/resources/layouts/`. host_layout 에 `{pluginId}.` 접두사.
|
||||
*
|
||||
* 각 레이아웃에서:
|
||||
* - `meta.is_base === true` → base 레이아웃 항목(`{layout_name, label}`).
|
||||
* - `modals[]` 의 모달(인라인 정의 + `{"partial": "..."}` 참조 모두) → 모달 항목
|
||||
* (`{modal_id, host_layout, label}`). partial 참조는 참조 파일을 읽어 id/title 추출.
|
||||
*
|
||||
* host_layout 접두사 규약은 라우트 트리 layout 규약(`loadActiveModulesRoutesData`
|
||||
* 의 `{moduleId}.{layout}`)과 일치시켜 트리에서 호스트 화면 노드와 매칭되게 한다.
|
||||
*
|
||||
* 모듈/플러그인 레이아웃은 라우트 로더(`routes/{admin|user}.json` 분기)와 동일하게
|
||||
* 템플릿 타입(admin/user)으로 필터링한다 — `layouts/{admin|user}/` 서브디렉토리만
|
||||
* 순회한다. 이를 누락하면 user 템플릿 편집기에 admin 레이아웃의 모달이(또는 그 반대로)
|
||||
* 새어 들어와 트리에 노출된다. 타입 서브디렉토리가 없는 출처는 라우트 로더와 동형으로
|
||||
* 건너뛴다(타입 미일치 레이아웃 비노출). 템플릿 자체 레이아웃은 그 템플릿 전용이므로
|
||||
* 타입 필터 없이 전부 수집한다.
|
||||
*
|
||||
* 라벨은 base 는 `meta.editor_label`/`layout_name`, 모달은 `modal.meta.editor_label`/
|
||||
* `modal.title`/`modal.id` 우선순위로 해석한다(편집기 클라이언트 라벨 규칙과 동형).
|
||||
* 활성/비활성 무관(편집은 비활성 템플릿도 허용), 파일 부재/파싱 실패는
|
||||
* 조용히 건너뛴다(라우트 그룹은 정상 표시).
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param string $templateType 템플릿 타입(`admin`/`user`) — 모듈/플러그인 레이아웃 타입 필터
|
||||
* @return array{base_layouts: array<int, array{layout_name: string, label: string|null}>, modals: array<int, array{modal_id: string, host_layout: string, label: string|null}>}
|
||||
*/
|
||||
private function collectEditorBaseAndModals(string $identifier, string $templateType): array
|
||||
{
|
||||
$baseLayouts = [];
|
||||
$modals = [];
|
||||
|
||||
// 1. 템플릿 레이아웃 (활성 → _bundled 폴백). host_layout 접두사 없음.
|
||||
// 템플릿 레이아웃은 해당 템플릿 전용이므로 타입 필터 없이 전부 수집한다.
|
||||
$templateDir = null;
|
||||
foreach ([
|
||||
base_path("templates/{$identifier}/layouts"),
|
||||
base_path("templates/_bundled/{$identifier}/layouts"),
|
||||
] as $candidate) {
|
||||
if (File::isDirectory($candidate)) {
|
||||
$templateDir = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($templateDir !== null) {
|
||||
$collected = $this->collectBaseAndModalsFromLayoutDir($templateDir, '');
|
||||
$baseLayouts = array_merge($baseLayouts, $collected['base_layouts']);
|
||||
$modals = array_merge($modals, $collected['modals']);
|
||||
}
|
||||
|
||||
// 2. 활성 모듈 레이아웃. host_layout 에 `{moduleId}.` 접두사(라우트 규약 동형).
|
||||
// 라우트 로더와 동일하게 `layouts/{templateType}/` 서브디렉토리만 순회한다.
|
||||
foreach ($this->moduleManager->getActiveModules() as $module) {
|
||||
$moduleId = $module->getIdentifier();
|
||||
$moduleDir = base_path("modules/{$moduleId}/resources/layouts/{$templateType}");
|
||||
if (! File::isDirectory($moduleDir)) {
|
||||
continue;
|
||||
}
|
||||
$collected = $this->collectBaseAndModalsFromLayoutDir($moduleDir, $moduleId.'.');
|
||||
$baseLayouts = array_merge($baseLayouts, $collected['base_layouts']);
|
||||
$modals = array_merge($modals, $collected['modals']);
|
||||
}
|
||||
|
||||
// 3. 활성 플러그인 레이아웃. host_layout 에 `{pluginId}.` 접두사.
|
||||
// 플러그인 라우트는 admin 템플릿에만 포함되므로(라우트 로더 규약), 모달도
|
||||
// admin 템플릿에서만 `layouts/{templateType}/` 서브디렉토리를 순회한다.
|
||||
if ($templateType === 'admin') {
|
||||
foreach ($this->pluginManager->getActivePlugins() as $plugin) {
|
||||
$pluginId = $plugin->getIdentifier();
|
||||
$pluginDir = base_path("plugins/{$pluginId}/resources/layouts/{$templateType}");
|
||||
if (! File::isDirectory($pluginDir)) {
|
||||
continue;
|
||||
}
|
||||
$collected = $this->collectBaseAndModalsFromLayoutDir($pluginDir, $pluginId.'.');
|
||||
$baseLayouts = array_merge($baseLayouts, $collected['base_layouts']);
|
||||
$modals = array_merge($modals, $collected['modals']);
|
||||
}
|
||||
}
|
||||
|
||||
return ['base_layouts' => $baseLayouts, 'modals' => $modals];
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 `layouts/` 디렉토리를 재귀 순회해 base 레이아웃 + 모달을 수집합니다.
|
||||
*
|
||||
* `collectEditorBaseAndModals` 의 출처별(템플릿/모듈/플러그인) 공통 수집 본체.
|
||||
* `partials/` 디렉토리는 모달 본체(partial)일 뿐 호스트 레이아웃이 아니므로 제외한다
|
||||
* — partial 모달은 각 호스트의 `modals[]` 참조로 수집된다.
|
||||
*
|
||||
* @param string $layoutDir 스캔할 layouts 디렉토리 절대 경로
|
||||
* @param string $hostPrefix host_layout/layout_name 에 붙일 접두사(예 `sirsoft-ecommerce.`). 템플릿은 빈 문자열.
|
||||
* @return array{base_layouts: array<int, array{layout_name: string, label: string|null}>, modals: array<int, array{modal_id: string, host_layout: string, label: string|null}>}
|
||||
*/
|
||||
private function collectBaseAndModalsFromLayoutDir(string $layoutDir, string $hostPrefix): array
|
||||
{
|
||||
$baseLayouts = [];
|
||||
$modals = [];
|
||||
|
||||
// 라우트 레이아웃은 하위 디렉토리(`auth/`, `shop/`, `admin/` 등)에 있으므로 재귀 순회한다
|
||||
// (File::files 는 최상위만 읽어 하위 레이아웃의 모달을 누락한다).
|
||||
$partialsDirPrefix = $layoutDir.DIRECTORY_SEPARATOR.'partials';
|
||||
foreach (File::allFiles($layoutDir) as $file) {
|
||||
if ($file->getExtension() !== 'json') {
|
||||
continue;
|
||||
}
|
||||
if (str_starts_with($file->getPathname(), $partialsDirPrefix)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$decoded = json_decode((string) File::get($file->getPathname()), true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE || ! is_array($decoded)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// layout_name 미선언 시 layouts 디렉토리 기준 상대 경로(확장자 제외)로 폴백한다
|
||||
// — 라우트 layoutName 규약(`auth/register`)과 일치시켜 host_layout 매칭을 보장.
|
||||
$relativeName = str_replace(
|
||||
['\\', '.json'],
|
||||
['/', ''],
|
||||
$file->getRelativePathname()
|
||||
);
|
||||
$layoutBaseName = is_string($decoded['layout_name'] ?? null) && $decoded['layout_name'] !== ''
|
||||
? $decoded['layout_name']
|
||||
: $relativeName;
|
||||
// 모듈/플러그인은 라우트 트리 layout 규약(`{id}.{layout}`)과 동일하게 접두사를 붙인다.
|
||||
$layoutName = $hostPrefix.$layoutBaseName;
|
||||
|
||||
// base 레이아웃
|
||||
if (($decoded['meta']['is_base'] ?? false) === true) {
|
||||
$baseLayouts[] = [
|
||||
'layout_name' => $layoutName,
|
||||
'label' => $this->resolveEditorTreeLabel($decoded['meta'] ?? [], null),
|
||||
];
|
||||
}
|
||||
|
||||
// 모달 수집 — 인라인 정의 + partial 참조 모두.
|
||||
//
|
||||
// 호스트 레이아웃의 `modals[]` 에 선언된 모달은 인라인/partial 여부와 무관하게
|
||||
// 동일한 모달이다(런타임/DB 에서는 partial 이 펼쳐져 호스트 content 의 완전한
|
||||
// 모달 노드로 저장된다). 편집기 트리에 노출돼야 호스트 하위 "이 화면의 모달"
|
||||
// 그룹·전체 `[모달]` 그룹에서 편집 가능하다. partial 참조는 그 파일을 읽어
|
||||
// id/title 을 추출한다.
|
||||
$layoutModals = $decoded['modals'] ?? null;
|
||||
if (is_array($layoutModals)) {
|
||||
foreach ($layoutModals as $modal) {
|
||||
if (! is_array($modal)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// partial 참조 모달 → 참조 파일을 읽어 모달 노드를 끌어온다.
|
||||
// partial 경로는 호스트 파일 디렉토리 기준(1순위) → layouts 루트(폴백)로 해석한다.
|
||||
if (isset($modal['partial']) && is_string($modal['partial'])) {
|
||||
$resolved = $this->resolveModalPartial($modal['partial'], $layoutDir, $file->getPath());
|
||||
if ($resolved === null) {
|
||||
continue;
|
||||
}
|
||||
$modal = $resolved;
|
||||
}
|
||||
|
||||
$modalId = $modal['id'] ?? $modal['modal_id'] ?? null;
|
||||
if (! is_string($modalId) || $modalId === '') {
|
||||
continue;
|
||||
}
|
||||
// 라벨 fallback: 모달 노드 최상위 `title` → Modal 컴포넌트 `props.title`.
|
||||
// G7 모달은 제목을 Modal 컴포넌트의 `props.title` 로 두는 것이 일반적이므로
|
||||
// (최상위 `title` 키는 거의 쓰이지 않음), props.title 까지 fallback 으로 읽어야
|
||||
// 편집기 트리에 modal_id 원문 대신 친화 제목(대개 `$t:` 키)이 표시된다.
|
||||
$modalTitle = $modal['title']
|
||||
?? (is_array($modal['props'] ?? null) ? ($modal['props']['title'] ?? null) : null);
|
||||
$modals[] = [
|
||||
'modal_id' => $modalId,
|
||||
'host_layout' => $layoutName,
|
||||
'label' => $this->resolveEditorTreeLabel($modal['meta'] ?? [], is_string($modalTitle) ? $modalTitle : null),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['base_layouts' => $baseLayouts, 'modals' => $modals];
|
||||
}
|
||||
|
||||
/**
|
||||
* 호스트 레이아웃 `modals[]` 의 partial 참조를 실제 모달 노드로 해석합니다.
|
||||
*
|
||||
* 편집기 트리 모달 수집은 레이아웃 파일 raw 를 읽으므로, partial 참조 모달은 그 자체엔
|
||||
* `id`/`title` 이 없다(`{"partial": "..."}` 뿐). 참조 파일을 읽어 모달 노드를 끌어와
|
||||
* 인라인 모달과 동일하게 다룬다. 경로 규약은 레이아웃 partial 해석과 동형: 호스트 파일
|
||||
* 디렉토리 기준 상대 경로, `partials/` 시작 시 layouts 루트 폴백. layouts 디렉토리 밖
|
||||
* 참조는 거부(경로 traversal 방지). 파일 부재/파싱 실패는 null(조용히 건너뜀).
|
||||
*
|
||||
* @param string $partialPath modals[].partial 값 (예: `partials/auth/_modal_terms.json`)
|
||||
* @param string $layoutDir layouts 디렉토리 절대 경로(보안 경계 + 루트 폴백 기준)
|
||||
* @param string $hostFileDir 호스트 레이아웃 파일이 위치한 디렉토리 절대 경로(1순위 기준)
|
||||
* @return array<string, mixed>|null 해석된 모달 노드 배열 또는 null
|
||||
*/
|
||||
private function resolveModalPartial(string $partialPath, string $layoutDir, string $hostFileDir): ?array
|
||||
{
|
||||
$layoutDirReal = realpath($layoutDir);
|
||||
if ($layoutDirReal === false) {
|
||||
return null;
|
||||
}
|
||||
$normalize = static fn (string $p): string => str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $p);
|
||||
|
||||
// 경로 해석 규약(레이아웃 partial 과 동형): ① 호스트 파일 디렉토리 기준 →
|
||||
// ② layouts 루트 기준 폴백. 두 결합을 순서대로 시도해 먼저 존재하는 파일을 채택한다.
|
||||
// - 호스트 기준: 예) layouts/admin/admin_ecommerce_order_detail.json 의
|
||||
// `partials/.../x.json` → layouts/admin/partials/.../x.json
|
||||
// - 루트 폴백: 예) layouts/auth/register.json 의 `partials/auth/x.json`
|
||||
// → layouts/partials/auth/x.json
|
||||
$resolved = false;
|
||||
foreach ([$hostFileDir, $layoutDirReal] as $baseDir) {
|
||||
$candidate = realpath($baseDir.DIRECTORY_SEPARATOR.$partialPath);
|
||||
if ($candidate === false) {
|
||||
continue;
|
||||
}
|
||||
// 보안 — layouts 디렉토리 밖 참조 거부(경로 traversal 방지).
|
||||
if (! str_starts_with($normalize($candidate), $normalize($layoutDirReal))) {
|
||||
continue;
|
||||
}
|
||||
$resolved = $candidate;
|
||||
break;
|
||||
}
|
||||
|
||||
if ($resolved === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decoded = json_decode((string) File::get($resolved), true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE || ! is_array($decoded)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 트리 노드 라벨을 해석합니다 (base/modal 공용).
|
||||
*
|
||||
* `meta.editor_label`(다국어 `$t:` 키 허용) → 전달된 fallback(모달 title 등) →
|
||||
* null 순으로 해석한다. 클라이언트(useRouteTree.resolveLabel)와 동일하게 `$t:` 키는
|
||||
* 그대로 전달해 프론트가 해석하도록 한다.
|
||||
*
|
||||
* @param array $meta 레이아웃/모달 meta 배열
|
||||
* @param string|null $fallback meta.editor_label 부재 시 사용할 라벨(모달 title 등)
|
||||
* @return string|null 해석된 라벨 또는 null
|
||||
*/
|
||||
private function resolveEditorTreeLabel(array $meta, ?string $fallback): ?string
|
||||
{
|
||||
$editorLabel = $meta['editor_label'] ?? null;
|
||||
if (is_string($editorLabel) && $editorLabel !== '') {
|
||||
return $editorLabel;
|
||||
}
|
||||
|
||||
return is_string($fallback) && $fallback !== '' ? $fallback : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿의 레이아웃 이름 → 라우트 path 매핑을 반환합니다.
|
||||
*
|
||||
* 코드 편집기가 파일 선택 시 `?route=` URL 동기화 / 위지윅 편집기에서 넘어온
|
||||
* `?route=` 로 해당 레이아웃을 복원하는 데 사용한다. path 내 `{{...}}` 표현식은
|
||||
* 위지윅 편집기(클라이언트 useEditorRoutes)와 동일하게 모듈 설정 기반으로 해석해
|
||||
* 양쪽 path 가 일치하도록 한다. redirect / layout 미지정 / 해석 불가 라우트는
|
||||
* 매핑에서 제외하며, 동일 레이아웃을 여러 라우트가 공유하면 먼저 선언된 path 를 채택한다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return array<string, string> 레이아웃 이름 → 라우트 path
|
||||
*/
|
||||
public function getLayoutRoutePathMap(string $identifier): array
|
||||
{
|
||||
$routesData = $this->getRoutesDataWithModules($identifier);
|
||||
$routes = $routesData['data']['routes'] ?? [];
|
||||
|
||||
$map = [];
|
||||
foreach ($routes as $route) {
|
||||
$layout = $route['layout'] ?? null;
|
||||
$path = $route['path'] ?? null;
|
||||
if (! is_string($layout) || $layout === '' || ! is_string($path) || $path === '') {
|
||||
continue;
|
||||
}
|
||||
$resolvedPath = $this->resolveRoutePathExpressions($path);
|
||||
if ($resolvedPath === '') {
|
||||
continue;
|
||||
}
|
||||
if (! isset($map[$layout])) {
|
||||
$map[$layout] = $resolvedPath;
|
||||
}
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 라우트 path 내 `{{...}}` 표현식을 위지윅 편집기와 동일하게 해석합니다.
|
||||
*
|
||||
* 위지윅 편집기는 클라이언트에서 `_global.modules` 컨텍스트로 path 표현식을 평가해
|
||||
* selectedRoute.path 를 만든다(useEditorRoutes.resolveEditorRouteExpressions).
|
||||
* 코드 편집기의 `?route=` 가 그 값과 매칭되려면 서버 맵도 동일하게 해석해야 한다.
|
||||
* 모듈 route_path 토글 패턴을 g7_module_settings 로 치환하고, 평가 불가한 표현식은
|
||||
* 클라이언트 fallback 과 동일하게 비운다.
|
||||
*
|
||||
* @param string $path 원본 라우트 path
|
||||
* @return string 해석된 path (선행 `*` 제거, 중복 슬래시 정규화)
|
||||
*/
|
||||
private function resolveRoutePathExpressions(string $path): string
|
||||
{
|
||||
$path = ltrim($path, '*');
|
||||
|
||||
$resolved = (string) preg_replace_callback('/\{\{(.+?)\}\}/', function (array $m): string {
|
||||
$expr = trim($m[1]);
|
||||
if (preg_match("/modules\?\.\['([^']+)'\]\?\.([\\w?.]+)\s*\?\?\s*'([^']+)'/", $expr, $mm)) {
|
||||
$moduleId = $mm[1];
|
||||
$settingKey = str_replace('?.', '.', $mm[2]);
|
||||
$default = $mm[3];
|
||||
if (preg_match('/\.no_route\s*\?/', $expr) && g7_module_settings($moduleId, 'basic_info.no_route')) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return (string) (g7_module_settings($moduleId, $settingKey) ?? $default);
|
||||
}
|
||||
|
||||
return '';
|
||||
}, $path);
|
||||
|
||||
$resolved = (string) preg_replace('#/+#', '/', $resolved);
|
||||
if ($resolved !== '/') {
|
||||
$resolved = rtrim($resolved, '/');
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성화된 모든 모듈의 routes 데이터를 템플릿 타입에 맞게 로드합니다.
|
||||
*
|
||||
@@ -1081,11 +1661,12 @@ class TemplateService
|
||||
|
||||
// JSON 파싱 성공 시 routes 배열 병합
|
||||
if (json_last_error() === JSON_ERROR_NONE && isset($data['routes']) && is_array($data['routes'])) {
|
||||
// 모듈 routes의 layout 필드에 moduleIdentifier 접두사 추가
|
||||
// 모듈 routes의 layout 필드에 moduleIdentifier 접두사 추가 + source 태깅
|
||||
$moduleRoutes = array_map(function ($route) use ($moduleIdentifier) {
|
||||
if (isset($route['layout'])) {
|
||||
$route['layout'] = $moduleIdentifier.'.'.$route['layout'];
|
||||
}
|
||||
$route['source'] = ['kind' => 'module', 'identifier' => $moduleIdentifier];
|
||||
|
||||
return $route;
|
||||
}, $data['routes']);
|
||||
@@ -1118,11 +1699,12 @@ class TemplateService
|
||||
|
||||
// JSON 파싱 성공 시 routes 배열 병합
|
||||
if (json_last_error() === JSON_ERROR_NONE && isset($data['routes']) && is_array($data['routes'])) {
|
||||
// 플러그인 routes의 layout 필드에 pluginIdentifier 접두사 추가
|
||||
// 플러그인 routes의 layout 필드에 pluginIdentifier 접두사 추가 + source 태깅
|
||||
$pluginRoutes = array_map(function ($route) use ($pluginIdentifier) {
|
||||
if (isset($route['layout'])) {
|
||||
$route['layout'] = $pluginIdentifier.'.'.$route['layout'];
|
||||
}
|
||||
$route['source'] = ['kind' => 'plugin', 'identifier' => $pluginIdentifier];
|
||||
|
||||
return $route;
|
||||
}, $data['routes']);
|
||||
@@ -1144,6 +1726,7 @@ class TemplateService
|
||||
'title' => '$t:'.$pluginIdentifier.'.settings.title',
|
||||
'permission' => 'core.plugins.read',
|
||||
],
|
||||
'source' => ['kind' => 'plugin', 'identifier' => $pluginIdentifier],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1262,6 +1845,7 @@ class TemplateService
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 업로드된 ZIP 파일로부터 템플릿을 추출/검증하고 _pending 으로 이동 후 설치합니다.
|
||||
*
|
||||
@@ -1270,7 +1854,6 @@ class TemplateService
|
||||
* @param UploadedFile $file 사용자가 업로드한 템플릿 ZIP 파일
|
||||
* @return array 설치 결과 (identifier/version/installed_at 포함)
|
||||
*/
|
||||
|
||||
public function installFromZipFile(UploadedFile $file): array
|
||||
{
|
||||
$tempPath = storage_path('app/temp/templates');
|
||||
|
||||
Reference in new issue
Block a user