chore(payment): NHN KCP와 NICE 결제 플러그인 개발 브랜치 분리
정식 develop에서는 기본 번들 정책에 따라 제거된 결제 플러그인을 별도 개발 브랜치에서 계속 유지보수할 수 있도록 복원한다.
This commit is contained in:
1 parent
49b21e788c
commit
657f546efc
651 files changed
+49118
-20476
No files matched your search
@@ -885,16 +885,7 @@ class CoreUpdateService
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 업데이트 대상 파일을 덮어씁니다.
|
||||
*
|
||||
* 기본(증분) 모드 — `$applyList` 가 주어지고 `$prune === false`:
|
||||
* - 코어(신 버전)가 실제로 추가·변경한 파일만 적용한다(3-way 판정 산출물).
|
||||
* - 코어가 건드리지 않은 파일은 복사·chmod·chown·mtime 갱신을 전부 스킵하여 현재
|
||||
* 디스크 상태(사용자 수정 포함 가능)를 그대로 보존한다.
|
||||
* - orphan(소스에 없는 대상 파일) 삭제를 하지 않는다 — 사용자가 추가한 신규 파일 보존.
|
||||
*
|
||||
* prune 모드 — `$prune === true` 또는 `$applyList === null`(백업 부재 fallback):
|
||||
* - targets 전체를 무조건 덮어쓰고, 소스에 없는 orphan 을 삭제한다(기존 동작).
|
||||
* 코어 업데이트 대상 파일만 선택적으로 덮어씁니다.
|
||||
*
|
||||
* 주의: ExtensionPendingHelper::copyToActive()는 PHP copy()를 사용하여
|
||||
* 파일 퍼미션/소유자를 보존하지 않으므로, 코어 업데이트에서는 사용하지 않습니다.
|
||||
@@ -902,29 +893,12 @@ class CoreUpdateService
|
||||
*
|
||||
* @param string $sourcePath 소스 경로 (_pending 내)
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @param bool $prune true 면 전체 덮어쓰기 + orphan 삭제(기존 동작), false 면 증분 적용
|
||||
* @param array<int, string>|null $applyList 적용 대상 상대경로 목록(target 접두사 포함).
|
||||
* `CoreBackupHelper::computeApplyList()` 산출물. null 이면 증분 불가로 판단해 전체 덮어쓰기.
|
||||
*/
|
||||
public function applyUpdate(string $sourcePath, ?\Closure $onProgress = null, bool $prune = false, ?array $applyList = null): void
|
||||
public function applyUpdate(string $sourcePath, ?\Closure $onProgress = null): void
|
||||
{
|
||||
$targets = config('app.update.targets', []);
|
||||
$excludes = config('app.update.excludes', []);
|
||||
|
||||
// 증분 모드 여부: prune 이 아니고 적용 목록이 주어진 경우에만 증분 적용.
|
||||
// applyList 가 null 이면(백업 부재 등) 안전을 위해 전체 덮어쓰기로 회귀한다.
|
||||
$incremental = ! $prune && $applyList !== null;
|
||||
|
||||
// 증분 모드에서 각 target 하위 파일을 O(1) 로 조회하기 위한 lookup 맵.
|
||||
// computeApplyList 는 target 접두사를 포함한 상대경로(예: 'public/.htaccess')를
|
||||
// 반환하므로, 그대로 정규화 키로 담는다.
|
||||
$applySet = [];
|
||||
if ($incremental) {
|
||||
foreach ($applyList as $rel) {
|
||||
$applySet[$this->normalizeRelativePath((string) $rel)] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$applied = [];
|
||||
|
||||
foreach ($targets as $target) {
|
||||
@@ -935,45 +909,21 @@ class CoreUpdateService
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalizedTarget = $this->normalizeRelativePath($target);
|
||||
|
||||
$onProgress?->__invoke('apply', $target);
|
||||
|
||||
if (File::isDirectory($src)) {
|
||||
// 증분 모드: 이 target 하위의 적용 대상만 추린 뒤, target 접두사를 벗겨
|
||||
// copyDirectory 의 내부 상대경로($itemRelativePath)와 직접 매칭되는
|
||||
// 화이트리스트 맵을 만든다.
|
||||
$targetApplyList = null;
|
||||
if ($incremental) {
|
||||
$targetApplyList = $this->buildTargetApplyList($applySet, $normalizedTarget);
|
||||
}
|
||||
|
||||
// `{domain}/_bundled` 타깃은 최상위 한 레벨의 orphan 을 보존한다 — 사용자가
|
||||
// `_bundled/` 바로 아래에 직접 만든 커스텀 확장 디렉토리/파일이 코어 업데이트
|
||||
// 소스(번들 확장만 포함)에 없다는 이유로 삭제되던 결함 차단.
|
||||
// 번들 확장 디렉토리 *내부* stale 정리는 prune 모드에서만 수행된다.
|
||||
$preserveTopLevelOrphans = str_ends_with($normalizedTarget, '_bundled');
|
||||
FilePermissionHelper::copyDirectory(
|
||||
$src,
|
||||
$dest,
|
||||
$onProgress,
|
||||
$excludes,
|
||||
removeOrphans: $prune,
|
||||
preserveTopLevelOrphans: $preserveTopLevelOrphans,
|
||||
applyList: $targetApplyList,
|
||||
);
|
||||
// 번들 확장 디렉토리 *내부* stale 정리는 그대로 유지된다.
|
||||
$preserveTopLevelOrphans = str_ends_with($this->normalizeRelativePath($target), '_bundled');
|
||||
FilePermissionHelper::copyDirectory($src, $dest, $onProgress, $excludes, removeOrphans: true, preserveTopLevelOrphans: $preserveTopLevelOrphans);
|
||||
} else {
|
||||
// 단일 파일 target — 증분 모드에서는 적용 목록에 있을 때만 복사.
|
||||
if ($incremental && ! isset($applySet[$normalizedTarget])) {
|
||||
$applied[$normalizedTarget] = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
File::ensureDirectoryExists(dirname($dest));
|
||||
FilePermissionHelper::copyFile($src, $dest);
|
||||
}
|
||||
|
||||
$applied[$normalizedTarget] = true;
|
||||
$applied[$this->normalizeRelativePath($target)] = true;
|
||||
}
|
||||
|
||||
// 자동 발견 폴백 — 부모 프로세스(구버전) 의 stale `app.update.targets` 가
|
||||
@@ -1055,31 +1005,6 @@ class CoreUpdateService
|
||||
return trim(str_replace(['\\', '/'], '/', $path), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 적용 집합에서 특정 target 하위 항목만 추려, target 접두사를 제거한
|
||||
* `copyDirectory` 내부 상대경로 화이트리스트 맵을 만듭니다.
|
||||
*
|
||||
* `computeApplyList` 는 target 접두사를 포함한 경로(예: `public/.htaccess`)를 담지만,
|
||||
* `copyDirectory` 는 target 루트 기준 상대경로(`.htaccess`)로 항목을 순회하므로 접두사를
|
||||
* 벗겨야 매칭된다.
|
||||
*
|
||||
* @param array<string, bool> $applySet 전체 적용 대상 정규화 경로 lookup 맵
|
||||
* @param string $normalizedTarget 정규화된 target 경로 (예: `public`)
|
||||
* @return array<string, bool> target 내부 상대경로 화이트리스트 (빈 맵일 수 있음 → 전부 스킵)
|
||||
*/
|
||||
private function buildTargetApplyList(array $applySet, string $normalizedTarget): array
|
||||
{
|
||||
$prefix = $normalizedTarget.'/';
|
||||
$out = [];
|
||||
foreach ($applySet as $rel => $_) {
|
||||
if (str_starts_with((string) $rel, $prefix)) {
|
||||
$out[substr((string) $rel, strlen($prefix))] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정규화된 path 가 이미 처리된 상위/하위 path 와 관계가 있는지 검사합니다.
|
||||
*
|
||||
@@ -1633,9 +1558,8 @@ class CoreUpdateService
|
||||
* @param string $toVersion 종료 버전
|
||||
* @param \Closure|null $onStep 각 스텝 실행 시 콜백 (버전 문자열 전달)
|
||||
* @param bool $force true 시 fromVersion == toVersion이면 해당 버전 스텝도 포함
|
||||
* @param \Closure|null $onDiscovered 범위 내 발견된 스텝 파일 수를 실행 전 1회 통지 (int 전달)
|
||||
*/
|
||||
public function runUpgradeSteps(string $fromVersion, string $toVersion, ?\Closure $onStep = null, bool $force = false, ?\Closure $onDiscovered = null): void
|
||||
public function runUpgradeSteps(string $fromVersion, string $toVersion, ?\Closure $onStep = null, bool $force = false): void
|
||||
{
|
||||
// 부모 in-process fallback 진입 시 stale 메모리 가드.
|
||||
//
|
||||
@@ -1673,9 +1597,6 @@ class CoreUpdateService
|
||||
$upgradesPath = base_path('upgrades');
|
||||
|
||||
if (! File::isDirectory($upgradesPath)) {
|
||||
// upgrades 디렉토리 자체가 없으면 발견된 스텝 0건 — 정상 통지 후 종료.
|
||||
$onDiscovered?->__invoke(0);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1735,12 +1656,6 @@ class CoreUpdateService
|
||||
|
||||
uksort($steps, 'version_compare');
|
||||
|
||||
// 범위 내에서 발견된 스텝 파일 수(discovered)를 먼저 통지한다.
|
||||
// 호출자(spawn 자식)는 이 값으로 "스텝 파일이 애초에 없어 0건(정상)" 과 "스텝 파일은
|
||||
// 있는데 실행이 0건(비정상 — gnuboard/g7#28 silent skip)" 을 구분한다. onStep 은 실제 실행
|
||||
// 건마다 호출되므로 executed 수만 세며, discovered 는 실행 전에 1회 통지한다.
|
||||
$onDiscovered?->__invoke(count($steps));
|
||||
|
||||
$context = new UpgradeContext($fromVersion, $toVersion);
|
||||
|
||||
foreach ($steps as $version => $step) {
|
||||
|
||||
@@ -1,475 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\Storage\CoreStorageDriver;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Http\View\Composers\TemplateComposer;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인) 프론트엔드 IIFE/CSS 번들 병합 서비스
|
||||
*
|
||||
* 활성 모듈/플러그인의 개별 IIFE JS·CSS 에셋을 타입별로 하나의 번들 파일로
|
||||
* 이어붙여(concat) 서빙 오버헤드(HTTP 요청 수)를 줄인다. 각 확장 IIFE 는
|
||||
* 자체 클로저에서 자가등록(`window.G7ModuleRegistry`/`G7PluginRegistry` +
|
||||
* 핸들러/리스너)을 수행하므로, N개 IIFE 를 priority 순으로 이어붙여 1개
|
||||
* `<script>` 로 실행해도 등록 로직은 동일하게 동작한다.
|
||||
*
|
||||
* 정렬/필터(`hasAssets()` && strategy==='global' + `uasort(priority)`) 는
|
||||
* TemplateComposer 와 공유하는 SSoT 로 이 서비스에 둔다(drift 방지).
|
||||
*
|
||||
* 경로는 절대경로 게터(`getBuiltAssetAbsolutePaths()`)를 재사용한다 —
|
||||
* `ModuleService::getAssetFilePath()` 의 `base_path("modules/{id}/...")`
|
||||
* 하드코딩을 복제하지 않아야 `_bundled` 확장에서도 정확히 읽는다(제약 4).
|
||||
*
|
||||
* @see TemplateComposer
|
||||
*/
|
||||
class ExtensionBundleService
|
||||
{
|
||||
// ext.cache_version 게터 재사용 — 트레이트를 use 해 self:: 로 호출(트레이트명
|
||||
// 직접 정적 호출은 PHP 8.3+ deprecated). 인스턴스 캐시 무효화 메서드는 미사용.
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
/**
|
||||
* 번들 캐시 파일이 저장되는 스토리지 디스크(= storage/app/ext-bundles).
|
||||
*/
|
||||
private const BUNDLE_DISK = 'ext-bundles';
|
||||
|
||||
/**
|
||||
* 서비스 주입
|
||||
*
|
||||
* @param ModuleManager $moduleManager 모듈 매니저
|
||||
* @param PluginManager $pluginManager 플러그인 매니저
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly ModuleManager $moduleManager,
|
||||
private readonly PluginManager $pluginManager
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 확장 타입별 global 전략 에셋을 priority 오름차순으로 정렬해 반환합니다.
|
||||
*
|
||||
* TemplateComposer 의 개별 에셋 URL 생성과 번들러의 concat 이 동일한
|
||||
* 필터/정렬을 쓰도록 하는 SSoT. 순서 제어는 오직 manifest
|
||||
* `loading.priority` 숫자 오름차순뿐이며 특정 확장 이름 하드코딩은 없다(제약 1).
|
||||
*
|
||||
* @param string $type 'module' | 'plugin'
|
||||
* @return array<string, array{jsAbsPath: ?string, cssAbsPath: ?string, priority: int}>
|
||||
* identifier => 절대경로/우선순위 (priority 오름차순 정렬)
|
||||
*/
|
||||
public function getOrderedGlobalAssetPaths(string $type): array
|
||||
{
|
||||
$extensions = $type === 'plugin'
|
||||
? $this->pluginManager->getActivePlugins()
|
||||
: $this->moduleManager->getActiveModules();
|
||||
|
||||
$ordered = [];
|
||||
|
||||
foreach ($extensions as $extension) {
|
||||
if (! $extension->hasAssets()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$loadingConfig = $extension->getAssetLoadingConfig();
|
||||
|
||||
// global 전략만 번들 대상 (layout, lazy 는 레이아웃에서 개별 처리)
|
||||
if (($loadingConfig['strategy'] ?? 'global') !== 'global') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$absolutePaths = $extension->getBuiltAssetAbsolutePaths();
|
||||
|
||||
$jsAbsPath = $absolutePaths['js'] ?? null;
|
||||
$cssAbsPath = $absolutePaths['css'] ?? null;
|
||||
|
||||
// JS/CSS 둘 다 없으면 번들에 기여할 것이 없으므로 제외
|
||||
if ($jsAbsPath === null && $cssAbsPath === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ordered[$extension->getIdentifier()] = [
|
||||
'jsAbsPath' => $jsAbsPath,
|
||||
'cssAbsPath' => $cssAbsPath,
|
||||
'priority' => (int) ($loadingConfig['priority'] ?? 100),
|
||||
];
|
||||
}
|
||||
|
||||
// priority 오름차순 (낮을수록 먼저) — 개별 로딩과 동일 규칙
|
||||
uasort($ordered, fn ($a, $b) => $a['priority'] <=> $b['priority']);
|
||||
|
||||
return $ordered;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 타입의 JS 번들 문자열을 생성합니다.
|
||||
*
|
||||
* priority 순으로 각 IIFE 파일을 읽어 `\n;\n` 구분자로 이어붙인다(제약 2 —
|
||||
* ASI 경계 보호). 각 파일 끝의 `//# sourceMappingURL` 주석은 prod 에서는
|
||||
* strip(맵 생략), dev 에서는 개별 에셋 서빙 절대 URL 로 rewrite 한다(제약 3).
|
||||
*
|
||||
* 확장별 fine-grained try/catch — 파일 읽기 실패 시 해당 확장만 skip +
|
||||
* Log::warning, 나머지 병합 지속(한 확장 실패가 번들 전체를 붕괴시키지 않음).
|
||||
*
|
||||
* @param string $type 'module' | 'plugin'
|
||||
* @return string 병합된 JS (활성 global 에셋이 없으면 빈 문자열)
|
||||
*/
|
||||
public function buildJsBundle(string $type): string
|
||||
{
|
||||
$ordered = $this->getOrderedGlobalAssetPaths($type);
|
||||
$isProduction = app()->environment('production');
|
||||
$segments = [];
|
||||
|
||||
foreach ($ordered as $identifier => $paths) {
|
||||
if (empty($paths['jsAbsPath'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$content = @file_get_contents($paths['jsAbsPath']);
|
||||
|
||||
if ($content === false) {
|
||||
Log::warning('확장 JS 번들 병합: 파일 읽기 실패, 해당 확장 skip', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'path' => $paths['jsAbsPath'],
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$segments[] = $this->processJsSourceMap($content, $type, $identifier, $isProduction);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('확장 JS 번들 병합 중 오류, 해당 확장 skip', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return implode("\n;\n", $segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 타입의 CSS 번들 문자열을 생성합니다.
|
||||
*
|
||||
* priority 순으로 각 CSS 파일을 읽어 `\n` 구분자로 이어붙인다. 상대경로
|
||||
* `url(...)` 참조가 있는 CSS 는 병합 시 경로가 깨지므로 번들에서 제외하고
|
||||
* 경고 로그를 남긴다(안전장치 — 현재 번들 CSS 는 url() 0건).
|
||||
*
|
||||
* @param string $type 'module' | 'plugin'
|
||||
* @return string 병합된 CSS (활성 global 에셋이 없으면 빈 문자열)
|
||||
*/
|
||||
public function buildCssBundle(string $type): string
|
||||
{
|
||||
$ordered = $this->getOrderedGlobalAssetPaths($type);
|
||||
$segments = [];
|
||||
|
||||
foreach ($ordered as $identifier => $paths) {
|
||||
if (empty($paths['cssAbsPath'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$content = @file_get_contents($paths['cssAbsPath']);
|
||||
|
||||
if ($content === false) {
|
||||
Log::warning('확장 CSS 번들 병합: 파일 읽기 실패, 해당 확장 skip', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'path' => $paths['cssAbsPath'],
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 상대경로 url() 참조가 있으면 병합 시 폰트/이미지 경로가 깨진다.
|
||||
// 절대/data URI 는 안전하므로 상대경로만 검출해 해당 CSS 제외.
|
||||
if ($this->hasRelativeUrl($content)) {
|
||||
Log::warning('확장 CSS 에 상대경로 url() 존재 — 번들에서 제외(개별 폴백 유지)', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$segments[] = $content;
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('확장 CSS 번들 병합 중 오류, 해당 확장 skip', [
|
||||
'type' => $type,
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return implode("\n", $segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시된 번들 파일의 절대 경로를 반환합니다(없으면 build → 원자적 write).
|
||||
*
|
||||
* 파일명에 version 을 포함(`{type}.{version}.{js|css}`)하므로 활성 조합이
|
||||
* 바뀌어 version 이 bump 되면 새 파일명으로 자연 무효화된다. 프로덕션에서만
|
||||
* 디스크 캐시하며, 비프로덕션(dev/watch)에서는 캐시하지 않고 매 요청 build 해
|
||||
* rebuild 를 즉시 반영한다.
|
||||
*
|
||||
* @param string $type 'module' | 'plugin'
|
||||
* @param string $kind 'js' | 'css'
|
||||
* @param int $version 확장 캐시 버전(ClearsTemplateCaches::getExtensionCacheVersion)
|
||||
* @return string 캐시(또는 방금 build 한) 파일의 절대 경로. 병합 결과가 빈 문자열이면 빈 문자열.
|
||||
*/
|
||||
public function getBundleFilePath(string $type, string $kind, int $version): string
|
||||
{
|
||||
$content = $kind === 'css'
|
||||
? $this->buildCssBundle($type)
|
||||
: $this->buildJsBundle($type);
|
||||
|
||||
// 병합할 에셋이 하나도 없으면 파일을 만들지 않는다(호출측이 빈 문자열로 판단).
|
||||
if ($content === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$storage = $this->bundleStorage();
|
||||
$relativeName = $this->bundleFileName($type, $kind, $version);
|
||||
|
||||
// 비프로덕션은 캐시하지 않고 임시 파일로 매번 build → rebuild 즉시 반영
|
||||
if (! app()->environment('production')) {
|
||||
return $this->writeAtomically($storage, $relativeName, $content, cache: false);
|
||||
}
|
||||
|
||||
// 프로덕션: 동일 version 캐시가 있으면 그대로 사용
|
||||
if ($storage->exists('', $relativeName)) {
|
||||
return $storage->getBasePath('').'/'.$relativeName;
|
||||
}
|
||||
|
||||
return $this->writeAtomically($storage, $relativeName, $content, cache: true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 version 외의 오래된 번들 파일을 삭제하고 삭제 건수를 반환합니다.
|
||||
*
|
||||
* @param int $currentVersion 보존할 현재 캐시 버전
|
||||
* @return int 삭제된 파일 수
|
||||
*/
|
||||
public function cleanupStaleBundles(int $currentVersion): int
|
||||
{
|
||||
$storage = $this->bundleStorage();
|
||||
$deleted = 0;
|
||||
|
||||
foreach ($storage->files('', '') as $file) {
|
||||
$name = basename($file);
|
||||
|
||||
// 현재 version 파일과 .gitignore 는 보존
|
||||
if ($name === '.gitignore' || $this->matchesVersion($name, $currentVersion)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->isBundleFile($name) && $storage->delete('', $name)) {
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 번들 캐시 파일을 삭제합니다(cache-clear 커맨드용).
|
||||
*
|
||||
* @param string|null $type 'module' | 'plugin' 지정 시 해당 타입만, null 이면 전체
|
||||
* @return int 삭제된 파일 수
|
||||
*/
|
||||
public function clearBundles(?string $type = null): int
|
||||
{
|
||||
$storage = $this->bundleStorage();
|
||||
$deleted = 0;
|
||||
|
||||
foreach ($storage->files('', '') as $file) {
|
||||
$name = basename($file);
|
||||
|
||||
if ($name === '.gitignore' || ! $this->isBundleFile($name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 타입 필터 (파일명 접두사 `{type}.`)
|
||||
if ($type !== null && ! str_starts_with($name, $type.'.')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($storage->delete('', $name)) {
|
||||
$deleted++;
|
||||
}
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 번들 파일명을 생성합니다(`{type}.{version}.{kind}`).
|
||||
*
|
||||
* @param string $type 'module' | 'plugin'
|
||||
* @param string $kind 'js' | 'css'
|
||||
* @param int $version 캐시 버전
|
||||
* @return string 파일명 (디렉토리 제외)
|
||||
*/
|
||||
private function bundleFileName(string $type, string $kind, int $version): string
|
||||
{
|
||||
return "{$type}.{$version}.{$kind}";
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일명이 번들 파일 패턴(`{type}.{version}.{kind}`)인지 확인합니다.
|
||||
*
|
||||
* @param string $name 파일명
|
||||
* @return bool 번들 파일이면 true
|
||||
*/
|
||||
private function isBundleFile(string $name): bool
|
||||
{
|
||||
return (bool) preg_match('/^(module|plugin)\.\d+\.(js|css)$/', $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일명이 지정한 version 의 번들인지 확인합니다.
|
||||
*
|
||||
* @param string $name 파일명
|
||||
* @param int $version 비교할 버전
|
||||
* @return bool 해당 version 파일이면 true
|
||||
*/
|
||||
private function matchesVersion(string $name, int $version): bool
|
||||
{
|
||||
return (bool) preg_match('/^(module|plugin)\.'.preg_quote((string) $version, '/').'\.(js|css)$/', $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 병합 결과를 원자적으로(임시 파일 → rename) 기록하고 절대 경로를 반환합니다.
|
||||
*
|
||||
* @param CoreStorageDriver $storage 번들 디스크 스토리지
|
||||
* @param string $relativeName 대상 파일명
|
||||
* @param string $content 기록할 내용
|
||||
* @param bool $cache true 면 version 파일명 유지, false 면 임시 파일 사용
|
||||
* @return string 기록된 파일의 절대 경로
|
||||
*/
|
||||
private function writeAtomically(CoreStorageDriver $storage, string $relativeName, string $content, bool $cache): string
|
||||
{
|
||||
$basePath = $storage->getBasePath('');
|
||||
|
||||
if (! is_dir($basePath)) {
|
||||
@mkdir($basePath, 0o755, true);
|
||||
}
|
||||
|
||||
$finalPath = $basePath.'/'.$relativeName;
|
||||
|
||||
if (! $cache) {
|
||||
// 비프로덕션: 매 요청 덮어써도 무방(원자성 불요), 그대로 write
|
||||
$storage->put('', $relativeName, $content);
|
||||
|
||||
return $finalPath;
|
||||
}
|
||||
|
||||
// 프로덕션: 임시 파일에 쓴 뒤 rename 으로 원자적 게시(부분 파일 서빙 방지)
|
||||
$tmpName = $relativeName.'.tmp.'.getmypid();
|
||||
$storage->put('', $tmpName, $content);
|
||||
|
||||
$tmpPath = $basePath.'/'.$tmpName;
|
||||
|
||||
if (! @rename($tmpPath, $finalPath)) {
|
||||
// rename 실패 시(경합으로 이미 존재 등) 임시 파일 정리 후 최종 경로 사용
|
||||
$storage->delete('', $tmpName);
|
||||
}
|
||||
|
||||
return $finalPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* IIFE 소스맵 주석을 환경에 맞게 처리합니다.
|
||||
*
|
||||
* prod: `//# sourceMappingURL` 라인 strip(맵 생략).
|
||||
* dev: 개별 에셋 서빙 절대 URL(`/api/{type}s/assets/{id}/dist/js/*.map`)로
|
||||
* rewrite → 브라우저가 확장별 원본 맵을 추적(완벽한 통합 맵은 아님).
|
||||
*
|
||||
* @param string $content 원본 IIFE 내용
|
||||
* @param string $type 'module' | 'plugin'
|
||||
* @param string $identifier 확장 식별자
|
||||
* @param bool $isProduction 프로덕션 여부
|
||||
* @return string 처리된 내용
|
||||
*/
|
||||
private function processJsSourceMap(string $content, string $type, string $identifier, bool $isProduction): string
|
||||
{
|
||||
// 구분자로 `~` 사용 — 패턴 자체에 `#`(`//#`)가 포함되어 `#` 구분자는 못 씀
|
||||
$pattern = '~//# sourceMappingURL=(\S+)~';
|
||||
|
||||
if ($isProduction) {
|
||||
// prod: 맵 참조 제거
|
||||
return preg_replace($pattern, '', $content) ?? $content;
|
||||
}
|
||||
|
||||
// dev: 상대 맵 파일명을 개별 에셋 서빙 절대 URL 로 rewrite
|
||||
$typeSegment = $type === 'plugin' ? 'plugins' : 'modules';
|
||||
|
||||
return preg_replace_callback($pattern, function (array $m) use ($typeSegment, $identifier) {
|
||||
$mapFile = ltrim($m[1], './');
|
||||
|
||||
return '//# sourceMappingURL=/api/'.$typeSegment.'/assets/'.$identifier.'/dist/js/'.basename($mapFile);
|
||||
}, $content) ?? $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* CSS 내용에 상대경로 url() 참조가 있는지 확인합니다.
|
||||
*
|
||||
* 절대 URL(http/https), 루트 절대경로(/), data URI 는 병합에 안전하므로
|
||||
* 그 외의 url() 참조만 상대경로로 간주한다.
|
||||
*
|
||||
* @param string $css CSS 내용
|
||||
* @return bool 상대경로 url() 이 하나라도 있으면 true
|
||||
*/
|
||||
private function hasRelativeUrl(string $css): bool
|
||||
{
|
||||
if (! preg_match_all('/url\(\s*[\'"]?([^\'")]+)[\'"]?\s*\)/i', $css, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($matches[1] as $url) {
|
||||
$url = trim($url);
|
||||
|
||||
if ($url === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$isAbsolute = str_starts_with($url, 'http://')
|
||||
|| str_starts_with($url, 'https://')
|
||||
|| str_starts_with($url, '//')
|
||||
|| str_starts_with($url, '/')
|
||||
|| str_starts_with($url, 'data:');
|
||||
|
||||
if (! $isAbsolute) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 번들 디스크용 스토리지 드라이버를 반환합니다(StorageInterface 경유).
|
||||
*
|
||||
* @return CoreStorageDriver ext-bundles 디스크 스토리지
|
||||
*/
|
||||
private function bundleStorage(): CoreStorageDriver
|
||||
{
|
||||
return (new CoreStorageDriver)->withDisk(self::BUNDLE_DISK);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 확장 캐시 버전을 반환합니다.
|
||||
*
|
||||
* @return int 캐시 버전
|
||||
*/
|
||||
public function getCurrentVersion(): int
|
||||
{
|
||||
return self::getExtensionCacheVersion();
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Support\ConfigCacheHelper;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -369,8 +369,8 @@ class GeoIpDatabaseService
|
||||
$current['last_updated_at'] = now()->toIso8601String();
|
||||
$this->configRepository->saveCategory('geoip', $current);
|
||||
|
||||
// config 캐시 재로드 강제 + 즉시 재생성 (clear 만 하면 캐시 비활성 잔존).
|
||||
ConfigCacheHelper::rebuild();
|
||||
// Laravel config 캐시 재로드 강제
|
||||
Artisan::call('config:clear');
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('GeoIP last_updated_at 갱신 실패', ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
@@ -807,12 +807,6 @@ class LayoutService
|
||||
// 캐시 비활성 시 매번 병합 실행
|
||||
if (! $cacheEnabled) {
|
||||
$merged = $this->loadAndMergeLayoutInternal($templateId, $layoutName, $withSourceMeta);
|
||||
|
||||
// 공개 서빙 응답에서 개발자용 comment 필드 제거 (편집 모드는 보존)
|
||||
if (! $withSourceMeta) {
|
||||
$merged = $this->stripDeveloperComments($merged);
|
||||
}
|
||||
|
||||
HookManager::doAction('core.layout.after_load', $merged, $templateId, $layoutName, false);
|
||||
|
||||
return $merged;
|
||||
@@ -850,12 +844,6 @@ class LayoutService
|
||||
// 병합된 레이아웃 생성
|
||||
$mergedLayout = $this->loadAndMergeLayoutInternal($templateId, $layoutName, $withSourceMeta);
|
||||
|
||||
// 공개 서빙 응답에서 개발자용 comment 필드 제거 (편집 모드는 보존).
|
||||
// withSourceMeta 가 캐시 키에 반영되므로 공개/편집 캐시가 분리되어 안전.
|
||||
if (! $withSourceMeta) {
|
||||
$mergedLayout = $this->stripDeveloperComments($mergedLayout);
|
||||
}
|
||||
|
||||
// 캐시에 저장
|
||||
$cacheTtl = $this->getCacheTtl();
|
||||
$this->cache->put($cacheKey, $mergedLayout, $cacheTtl);
|
||||
@@ -1613,30 +1601,6 @@ class LayoutService
|
||||
}, $components);
|
||||
}
|
||||
|
||||
/**
|
||||
* 병합된 레이아웃에서 개발자용 comment 필드를 재귀적으로 제거합니다.
|
||||
*
|
||||
* 레이아웃 JSON 의 `comment` / `_comment` 키는 편집기(layout-editor)와 개발자를 위한
|
||||
* 설명 주석으로, 프론트엔드 런타임 렌더러(DynamicRenderer)는 이를 참조하지 않는다.
|
||||
* 공개 서빙 응답에서만 제거하여 전송 크기를 줄이며, 편집 모드(withSourceMeta)에서는
|
||||
* 호출하지 않아 보존한다. 배열/객체 노드를 재귀 순회하며 두 키만 unset 한다.
|
||||
*
|
||||
* @param array $node 정리 대상 레이아웃(또는 하위) 배열
|
||||
* @return array comment 필드가 제거된 배열
|
||||
*/
|
||||
private function stripDeveloperComments(array $node): array
|
||||
{
|
||||
unset($node['comment'], $node['_comment']);
|
||||
|
||||
foreach ($node as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$node[$key] = $this->stripDeveloperComments($value);
|
||||
}
|
||||
}
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
/**
|
||||
* 컴포넌트의 props를 sanitize합니다.
|
||||
*
|
||||
|
||||
@@ -7,7 +7,6 @@ use App\Contracts\Repositories\AttachmentRepositoryInterface;
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Http\Resources\AttachmentResource;
|
||||
use App\Support\ConfigCacheHelper;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -33,14 +32,11 @@ class SettingsService
|
||||
* 시스템 설정 캐시를 무효화합니다.
|
||||
*
|
||||
* 설정 저장 시 4곳에서 중복되던 로직을 단일 메서드로 통합했습니다.
|
||||
* config 캐시는 clear 후 즉시 재생성한다(ConfigCacheHelper). config:clear 만
|
||||
* 하면 config:cache 가 비워진 채 재생성되지 않아 이후 모든 요청이 config 파일을
|
||||
* 재파싱하는 성능 손실이 발생하기 때문이다.
|
||||
*/
|
||||
private function invalidateSettingsCache(): void
|
||||
{
|
||||
$this->cache->forget('settings.system');
|
||||
ConfigCacheHelper::rebuild();
|
||||
Artisan::call('config:clear');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -826,74 +822,30 @@ class SettingsService
|
||||
private function buildSystemInfo(): array
|
||||
{
|
||||
return [
|
||||
// php_uname / ini_get 은 disable_functions 로 차단될 수 있어 개별 격리한다.
|
||||
'os_info' => $this->safeSystemProbe('os_info', fn () => php_uname('s').' '.php_uname('r'), __('common.unknown')),
|
||||
'os_info' => php_uname('s').' '.php_uname('r'),
|
||||
'web_server' => $_SERVER['SERVER_SOFTWARE'] ?? __('common.unknown'),
|
||||
'php_version' => PHP_VERSION,
|
||||
'mysql_version' => $this->safeSystemProbe('mysql_version', fn () => $this->getDatabaseInfo(), __('common.unknown')),
|
||||
'mysql_version' => $this->getDatabaseInfo(),
|
||||
'g7_version' => config('app.version', '1.0.0'),
|
||||
'g7_release_year' => config('app.release_year', '2026'),
|
||||
'laravel_version' => app()->version(),
|
||||
'environment' => app()->environment(),
|
||||
'cpu_info' => $this->safeSystemProbe('cpu_info', fn () => $this->getCpuInfo(), __('common.unknown')),
|
||||
'memory_usage' => $this->safeSystemProbe('memory_usage', fn () => $this->getMemoryUsage(), $this->unknownUsage()),
|
||||
'disk_usage' => $this->safeSystemProbe('disk_usage', fn () => $this->getDiskUsage(), $this->unknownUsage()),
|
||||
'php_memory_limit' => $this->safeSystemProbe('php_memory_limit', fn () => ini_get('memory_limit'), __('common.unknown')),
|
||||
'max_execution_time' => $this->safeSystemProbe('max_execution_time', fn () => ini_get('max_execution_time').__('settings.seconds'), __('common.unknown')),
|
||||
'upload_max_filesize' => $this->safeSystemProbe('upload_max_filesize', fn () => ini_get('upload_max_filesize'), __('common.unknown')),
|
||||
'cpu_info' => $this->getCpuInfo(),
|
||||
'memory_usage' => $this->getMemoryUsage(),
|
||||
'disk_usage' => $this->getDiskUsage(),
|
||||
'php_memory_limit' => ini_get('memory_limit'),
|
||||
'max_execution_time' => ini_get('max_execution_time').__('settings.seconds'),
|
||||
'upload_max_filesize' => ini_get('upload_max_filesize'),
|
||||
'install_path' => base_path(),
|
||||
'config_path' => storage_path('app/settings'),
|
||||
'log_path' => storage_path('logs'),
|
||||
'upload_path' => storage_path('app/public'),
|
||||
'php_extensions' => $this->safeSystemProbe('php_extensions', fn () => $this->getPhpExtensions(), ['required' => [], 'optional' => []]),
|
||||
'database_config' => $this->safeSystemProbe('database_config', fn () => $this->getDatabaseConfig(), ['has_read_write_split' => false, 'write' => [], 'read' => []]),
|
||||
'php_extensions' => $this->getPhpExtensions(),
|
||||
'database_config' => $this->getDatabaseConfig(),
|
||||
'timezone' => config('app.timezone'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 정보 probe 를 안전하게 실행합니다.
|
||||
*
|
||||
* probe 가 예외(ErrorException·Error·disable_functions 로 인한 Error 포함)를
|
||||
* 던지면 전파하지 않고 폴백값을 반환하고 경고 로그를 남깁니다. 개별 항목 수집
|
||||
* 실패가 system-info API 전체를 500 으로 만들지 않도록 격리합니다.
|
||||
*
|
||||
* @param string $label 실패 로그 식별용 항목명 (예: 'cpu_info')
|
||||
* @param callable $cb 실행할 probe 콜백
|
||||
* @param mixed $fallback 실패 시 반환할 폴백 값
|
||||
* @return mixed probe 결과 또는 폴백
|
||||
*/
|
||||
private function safeSystemProbe(string $label, callable $cb, mixed $fallback): mixed
|
||||
{
|
||||
try {
|
||||
return $cb();
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('시스템 정보 수집 실패', [
|
||||
'item' => $label,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 메모리/디스크 사용량 조회 실패 시 사용할 폴백 배열을 반환합니다.
|
||||
*
|
||||
* total/used/free/percentage 형식을 memory_usage·disk_usage 와 동일하게 유지합니다.
|
||||
*
|
||||
* @return array 사용량 폴백 배열
|
||||
*/
|
||||
private function unknownUsage(): array
|
||||
{
|
||||
return [
|
||||
'total' => __('common.unknown'),
|
||||
'used' => __('common.unknown'),
|
||||
'free' => __('common.unknown'),
|
||||
'percentage' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 캐시를 정리합니다.
|
||||
*
|
||||
@@ -907,12 +859,10 @@ class SettingsService
|
||||
}
|
||||
|
||||
Artisan::call('cache:clear');
|
||||
Artisan::call('config:clear');
|
||||
Artisan::call('route:clear');
|
||||
Artisan::call('view:clear');
|
||||
|
||||
// config 는 clear 후 즉시 재생성 (비운 채 두면 이후 모든 요청이 config 재파싱).
|
||||
ConfigCacheHelper::rebuild();
|
||||
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
@@ -958,8 +908,7 @@ class SettingsService
|
||||
$envContent = preg_replace('/^APP_KEY=.*/m', 'APP_KEY='.$newKey, $envContent);
|
||||
file_put_contents($envPath, $envContent);
|
||||
|
||||
// .env 변경 반영 + config 캐시 재생성 (clear 만 하면 캐시 비활성 상태로 잔존).
|
||||
ConfigCacheHelper::rebuild();
|
||||
Artisan::call('config:clear');
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
@@ -1000,16 +949,11 @@ class SettingsService
|
||||
try {
|
||||
$connection = DB::connection();
|
||||
$driver = $connection->getDriverName();
|
||||
$version = $connection->select('SELECT VERSION() as version')[0]->version ?? __('common.unknown');
|
||||
$version = $connection->select('SELECT VERSION() as version')[0]->version ?? 'Unknown';
|
||||
|
||||
return ucfirst($driver).' '.$version;
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('시스템 정보 수집 실패', [
|
||||
'item' => 'mysql_version',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return __('common.unknown');
|
||||
} catch (\Exception $e) {
|
||||
return 'Unknown';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1055,7 +999,12 @@ class SettingsService
|
||||
}
|
||||
|
||||
if ($total <= 0) {
|
||||
return $this->unknownUsage();
|
||||
return [
|
||||
'total' => __('common.unknown'),
|
||||
'used' => __('common.unknown'),
|
||||
'free' => __('common.unknown'),
|
||||
'percentage' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$used = max(0, $total - $free);
|
||||
@@ -1085,7 +1034,12 @@ class SettingsService
|
||||
$free = is_numeric($freeRaw) ? (int) $freeRaw : 0;
|
||||
|
||||
if ($total <= 0) {
|
||||
return $this->unknownUsage();
|
||||
return [
|
||||
'total' => __('common.unknown'),
|
||||
'used' => __('common.unknown'),
|
||||
'free' => __('common.unknown'),
|
||||
'percentage' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$used = max(0, $total - $free);
|
||||
@@ -1123,7 +1077,7 @@ class SettingsService
|
||||
*
|
||||
* @return string CPU 정보 문자열
|
||||
*/
|
||||
protected function getCpuInfo(): string
|
||||
private function getCpuInfo(): string
|
||||
{
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
$output = @shell_exec('powershell -NoProfile -NonInteractive -Command "(Get-CimInstance Win32_Processor | Select-Object -First 1).Name" 2>&1');
|
||||
|
||||
@@ -18,7 +18,7 @@ use Illuminate\Support\Str;
|
||||
* 레이아웃 편집 중 업로드되는 파일(배경 이미지 등)의 업로드·조회·삭제를 처리한다.
|
||||
* 파일 저장은 코어 StorageInterface(CoreStorageDriver)를 통해서만 수행하고,
|
||||
* 저장 위치(disk/path)와 메타데이터를 template_layout_attachments 에 기록한다.
|
||||
* (Storage::disk() 직접 호출 금지 — 코어 스토리지 규칙)
|
||||
* (Storage::disk() 직접 호출 금지 — CLAUDE.md 스토리지 규칙)
|
||||
*/
|
||||
class TemplateLayoutAttachmentService
|
||||
{
|
||||
@@ -114,7 +114,7 @@ class TemplateLayoutAttachmentService
|
||||
* 첨부 파일을 삭제합니다 — 스토리지 파일 실삭제 후 DB 행 삭제.
|
||||
*
|
||||
* DB CASCADE 에 의존하지 않고 스토리지 파일을 명시적으로 삭제한다
|
||||
* (코어 규정: DB CASCADE 의존 삭제 금지 — 파일 정리 보장).
|
||||
* (CLAUDE.md "DB CASCADE 의존 삭제 금지" — 파일 정리 보장).
|
||||
*
|
||||
* @param TemplateLayoutAttachment $attachment 삭제할 첨부 파일
|
||||
* @return bool 삭제 성공 여부
|
||||
|
||||
Reference in new issue
Block a user