v7.0.0 release

This commit is contained in:
HeuJung committed 2026-07-01 10:30:32 +09:00
1 parent 0e7fa04b03
commit c4ea9a6cd1
3582 files changed
+626189 -160151

No files matched your search

+420 -40
View File
@@ -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
{