v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -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