v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repositories\Concerns;
|
||||
|
||||
/**
|
||||
* JSON 콘텐츠 diff 계산 trait
|
||||
*
|
||||
* 레이아웃·레이아웃 확장 등 JSON 스냅샷 기반 버전 저장소가 공유하는 순수 JSON diff
|
||||
* 알고리즘을 제공합니다. 도메인 종속성이 없습니다.
|
||||
*
|
||||
* 측정 단위는 "라인"이다. 두 content 를 키 정렬 pretty-print JSON 으로 직렬화한 뒤
|
||||
* 라인 단위 LCS(최장 공통 부분수열)로 추가/삭제 라인을 센다. 이는 버전 비교 diff
|
||||
* 뷰(프론트엔드 lineDiff.ts)와 동일한 알고리즘·동일한 직렬화·동일한 단위이므로,
|
||||
* 버전 목록의 변경량과 diff 뷰의 +추가/-삭제 숫자가 항상 일치한다.
|
||||
*
|
||||
* 종전에는 백엔드가 JSON "키 경로" 단위로 세고 diff 뷰는 "라인" 단위로 세어 같은
|
||||
* 변경에도 숫자가 달랐다(예: 객체 1개 추가 = 키 경로 6 vs 라인 8). 키 경로는 구조
|
||||
* 문자({}[])를 세지 않으므로 라인 수와 구조적으로 일치할 수 없어, 라인 LCS 를
|
||||
* 단일 SSoT 로 삼는다.
|
||||
*/
|
||||
trait CalculatesJsonContentDiff
|
||||
{
|
||||
/**
|
||||
* LCS 변경 영역 상한 — 프론트 lineDiff.ts 의 DIFF_MAX_LINES 와 동일.
|
||||
*
|
||||
* 트리밍 후 변경 영역이 이 값을 넘으면 O(n·m) DP 를 회피하고 라인 집합 차집합으로
|
||||
* 근사한다(비정상적으로 큰 변경에서만 발동, 인접 버전 비교는 해당 없음).
|
||||
*/
|
||||
private const int DIFF_MAX_LINES = 4000;
|
||||
|
||||
/**
|
||||
* JSON content 변경사항 카운트 계산 (라인 단위 LCS)
|
||||
*
|
||||
* 버전 목록에 표시할 변경량은 "추가 라인 수 / 삭제 라인 수 / 문자 수 변화" 세 정수뿐이다.
|
||||
* 따라서 라인 원문을 저장하지 않고 카운트만 반환한다(종전엔 라인 원문 배열을 통째로
|
||||
* 저장해 건당 수십 KB 가 적재되던 비효율을 제거). 측정은 버전 비교 diff
|
||||
* 뷰(프론트 lineDiff.ts)와 동일한 라인 단위 LCS 라 두 화면의 숫자가 항상 일치한다.
|
||||
*
|
||||
* 라인 단위 diff 에는 "수정(modified)" 개념이 없다 — 값이 바뀐 라인은 삭제+추가로
|
||||
* 표현된다(diff 뷰의 -/+ 와 동일). 따라서 modified 카운트는 두지 않는다.
|
||||
*
|
||||
* 반환 키는 원 설계(시더·마이그레이션 주석의 `{added: int, removed: int}`)와 동일하게
|
||||
* added/removed 에 카운트(정수)를 담는다.
|
||||
*
|
||||
* @param array $oldContent 이전 콘텐츠
|
||||
* @param array $newContent 새 콘텐츠
|
||||
* @return array{added: int, removed: int, char_diff: int}
|
||||
*/
|
||||
public function calculateChanges(array $oldContent, array $newContent): array
|
||||
{
|
||||
$oldLines = $this->contentToLines($oldContent);
|
||||
$newLines = $this->contentToLines($newContent);
|
||||
|
||||
[$addedCount, $removedCount] = $this->diffLineCounts($oldLines, $newLines);
|
||||
|
||||
// 문자 수 변화 — 직렬화된 본문 기준(diff 뷰와 동일 직렬화).
|
||||
$charDiff = mb_strlen(implode("\n", $newLines)) - mb_strlen(implode("\n", $oldLines));
|
||||
|
||||
return [
|
||||
'added' => $addedCount,
|
||||
'removed' => $removedCount,
|
||||
'char_diff' => $charDiff,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* content 객체를 diff 비교용 안정 pretty-print JSON 라인 배열로 직렬화한다.
|
||||
*
|
||||
* 키를 재귀 정렬(객체만, 배열 순서는 보존)하고 2-space 들여쓰기로 직렬화한다.
|
||||
* 프론트엔드 lineDiff.ts 의 stableStringify 와 동일 규칙이라 양측 라인 집합이
|
||||
* 일치한다.
|
||||
*
|
||||
* @param array $content 대상 content
|
||||
* @return array<string> 라인 배열(개행 제외)
|
||||
*/
|
||||
private function contentToLines(array $content): array
|
||||
{
|
||||
$sorted = $this->sortKeysDeep($content);
|
||||
// JSON_PRETTY_PRINT 는 4-space 이므로 2-space 로 환산(라인 수는 폭과 무관하지만
|
||||
// 라인 내용 비교 일관성을 위해 프론트와 동일 폭으로 맞춘다).
|
||||
$json = json_encode($sorted, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
|
||||
if ($json === false) {
|
||||
$json = '';
|
||||
}
|
||||
$json = $this->reindentToTwoSpaces($json);
|
||||
|
||||
$lines = explode("\n", $json);
|
||||
// 끝 개행으로 생긴 빈 마지막 요소 제거 (프론트 splitLines 와 동일 normalize)
|
||||
if ($lines !== [] && end($lines) === '') {
|
||||
array_pop($lines);
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP json_encode 의 4-space 들여쓰기를 2-space 로 환산한다.
|
||||
*
|
||||
* 각 라인의 선행 공백(4의 배수)을 절반으로 줄인다. 문자열 값 내부의 공백은
|
||||
* 라인 선두가 아니므로 영향받지 않는다.
|
||||
*
|
||||
* @param string $json 4-space pretty JSON
|
||||
* @return string 2-space pretty JSON
|
||||
*/
|
||||
private function reindentToTwoSpaces(string $json): string
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/^( +)/m',
|
||||
fn (array $m) => str_repeat(' ', (int) (strlen($m[1]) / 2)),
|
||||
$json
|
||||
) ?? $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 키를 재귀적으로 정렬(객체만, list 순서는 보존)
|
||||
*
|
||||
* @param mixed $value 대상 값
|
||||
* @return mixed 정렬된 값
|
||||
*/
|
||||
private function sortKeysDeep(mixed $value): mixed
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$isList = array_is_list($value);
|
||||
$mapped = array_map(fn ($v) => $this->sortKeysDeep($v), $value);
|
||||
if (! $isList) {
|
||||
ksort($mapped);
|
||||
}
|
||||
|
||||
return $mapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* 라인 배열 두 개의 LCS diff — 추가/삭제 라인 "수"를 반환한다.
|
||||
*
|
||||
* 공통 prefix/suffix 를 먼저 트리밍해 LCS DP 입력을 변경 영역으로 축소한다(큰
|
||||
* content 의 작은 변경도 빠르게 처리). 라인 원문은 누적하지 않고 카운트만 세므로
|
||||
* 메모리도 절약된다(저장 대상은 카운트뿐). 프론트 computeLineDiff 와 동일 전략이라
|
||||
* added/removed 카운트가 일치한다.
|
||||
*
|
||||
* @param array<string> $a 이전 라인
|
||||
* @param array<string> $b 새 라인
|
||||
* @return array{0: int, 1: int} [추가 라인 수, 삭제 라인 수]
|
||||
*/
|
||||
private function diffLineCounts(array $a, array $b): array
|
||||
{
|
||||
$a = array_values($a);
|
||||
$b = array_values($b);
|
||||
$n = count($a);
|
||||
$m = count($b);
|
||||
|
||||
// 공통 prefix
|
||||
$prefix = 0;
|
||||
$maxPrefix = min($n, $m);
|
||||
while ($prefix < $maxPrefix && $a[$prefix] === $b[$prefix]) {
|
||||
$prefix++;
|
||||
}
|
||||
|
||||
// 공통 suffix
|
||||
$suffix = 0;
|
||||
$maxSuffix = min($n, $m) - $prefix;
|
||||
while ($suffix < $maxSuffix && $a[$n - 1 - $suffix] === $b[$m - 1 - $suffix]) {
|
||||
$suffix++;
|
||||
}
|
||||
|
||||
$midA = array_slice($a, $prefix, $n - $suffix - $prefix);
|
||||
$midB = array_slice($b, $prefix, $m - $suffix - $prefix);
|
||||
|
||||
$na = count($midA);
|
||||
$nb = count($midB);
|
||||
|
||||
// 안전 가드 — 변경 영역이 과대하면 LCS 를 생략하고 라인 집합 차집합으로 근사한다.
|
||||
// 프론트 lineDiff.ts 의 DIFF_MAX_LINES(4000) 와 동일 임계. 인접 버전 비교는 변경
|
||||
// 영역이 작아 이 경로를 타지 않으며, 비정상적으로 큰 변경에서만 O(n·m) DP 를 회피한다.
|
||||
if ($na > self::DIFF_MAX_LINES || $nb > self::DIFF_MAX_LINES) {
|
||||
return $this->approximateLineCounts($midA, $midB);
|
||||
}
|
||||
|
||||
// LCS DP
|
||||
$dp = array_fill(0, $na + 1, array_fill(0, $nb + 1, 0));
|
||||
for ($i = $na - 1; $i >= 0; $i--) {
|
||||
for ($j = $nb - 1; $j >= 0; $j--) {
|
||||
$dp[$i][$j] = $midA[$i] === $midB[$j]
|
||||
? $dp[$i + 1][$j + 1] + 1
|
||||
: max($dp[$i + 1][$j], $dp[$i][$j + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
// backtrack — 삭제/추가 라인 수만 카운트
|
||||
$added = 0;
|
||||
$removed = 0;
|
||||
$i = 0;
|
||||
$j = 0;
|
||||
while ($i < $na && $j < $nb) {
|
||||
if ($midA[$i] === $midB[$j]) {
|
||||
$i++;
|
||||
$j++;
|
||||
} elseif ($dp[$i + 1][$j] >= $dp[$i][$j + 1]) {
|
||||
$removed++;
|
||||
$i++;
|
||||
} else {
|
||||
$added++;
|
||||
$j++;
|
||||
}
|
||||
}
|
||||
$removed += $na - $i;
|
||||
$added += $nb - $j;
|
||||
|
||||
return [$added, $removed];
|
||||
}
|
||||
|
||||
/**
|
||||
* 변경 영역이 과대할 때의 라인 diff 카운트 근사 — multiset 차집합
|
||||
*
|
||||
* LCS 없이 라인 빈도수 차이로 추가/삭제 라인 수를 근사한다. 순서를 고려하지 않으므로
|
||||
* LCS 보다 부정확할 수 있으나(이동을 추가+삭제로 셈), 비정상적으로 큰 변경에서만
|
||||
* 발동하므로 실용상 충분하다. 정확 일치 라인은 변경에서 제외된다.
|
||||
*
|
||||
* @param array<string> $a 이전 라인
|
||||
* @param array<string> $b 새 라인
|
||||
* @return array{0: int, 1: int} [추가 라인 수, 삭제 라인 수]
|
||||
*/
|
||||
private function approximateLineCounts(array $a, array $b): array
|
||||
{
|
||||
$oldFreq = array_count_values($a);
|
||||
$newFreq = array_count_values($b);
|
||||
|
||||
$removed = 0;
|
||||
foreach ($oldFreq as $line => $cnt) {
|
||||
$removed += max(0, $cnt - ($newFreq[$line] ?? 0));
|
||||
}
|
||||
|
||||
$added = 0;
|
||||
foreach ($newFreq as $line => $cnt) {
|
||||
$added += max(0, $cnt - ($oldFreq[$line] ?? 0));
|
||||
}
|
||||
|
||||
return [$added, $removed];
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,14 @@ namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\IdentityPolicyRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Models\IdentityPolicy;
|
||||
use App\Models\Module;
|
||||
use App\Models\Plugin;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* identity_policies Repository 구현체.
|
||||
@@ -29,6 +35,21 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
|
||||
return IdentityPolicy::query()->where('key', $key)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* key + source_type 조합으로 정책 존재 여부를 확인합니다.
|
||||
*
|
||||
* @param string $key 정책 키
|
||||
* @param string $sourceType 'core' | 'module' | 'plugin' | 'admin'
|
||||
* @return bool 해당 조합의 정책 존재 여부
|
||||
*/
|
||||
public function existsByKeyAndSourceType(string $key, string $sourceType): bool
|
||||
{
|
||||
return IdentityPolicy::query()
|
||||
->where('key', $key)
|
||||
->where('source_type', $sourceType)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 정책을 조회합니다.
|
||||
*
|
||||
@@ -49,11 +70,22 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
|
||||
*/
|
||||
public function resolveByScopeTarget(string $scope, string $target): Collection
|
||||
{
|
||||
return IdentityPolicy::query()
|
||||
$query = IdentityPolicy::query()
|
||||
->where('scope', $scope)
|
||||
->where('target', $target)
|
||||
->where('enabled', true)
|
||||
->where('enabled', true);
|
||||
|
||||
// 비활성 모듈/플러그인이 선언한 정책은 enforce 대상에서 제외
|
||||
$this->applyActiveExtensionScope($query);
|
||||
|
||||
// priority 동률 시 결정적 순서 보장 — id 2차 정렬키가 없으면 MySQL 이 동점 행을
|
||||
// 보장되지 않는 순서로 반환해, 같은 scope+target 에 동률 정책이 둘 이상일 때 어느 정책이
|
||||
// enforce 되는지(어떤 purpose 로 challenge 되는지)가 비결정적이 된다. 운영자는 우선순위
|
||||
// 입력칸으로 순서를 정할 수 있으나, 같은 값을 넣어 동률이 된 경우에도 항상 동일한 정책이
|
||||
// 적용되도록 id 오름차순(먼저 생성된 정책 우선)을 2차 키로 고정한다.
|
||||
return $query
|
||||
->orderByDesc('priority')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
@@ -167,12 +199,36 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
|
||||
return (int) $query->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 키 목록에 없는 stale 정책 모델을 조회합니다.
|
||||
*
|
||||
* 호출 측이 per-model delete()(deleted 이벤트 발화 — 라우트 스코프 캐시 flush)와
|
||||
* 로깅을 수행할 수 있도록 모델 인스턴스를 반환한다.
|
||||
*
|
||||
* @param string $sourceType 소스 타입
|
||||
* @param string $sourceIdentifier 소스 식별자
|
||||
* @param array $currentKeys 유지할 키 목록
|
||||
* @return Collection<int, IdentityPolicy> stale 정책 목록
|
||||
*/
|
||||
public function findStale(string $sourceType, string $sourceIdentifier, array $currentKeys): Collection
|
||||
{
|
||||
$query = IdentityPolicy::query()
|
||||
->where('source_type', $sourceType)
|
||||
->where('source_identifier', $sourceIdentifier);
|
||||
|
||||
if (! empty($currentKeys)) {
|
||||
$query->whereNotIn('key', $currentKeys);
|
||||
}
|
||||
|
||||
return $query->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 필터 기반 정책 페이지네이션 결과를 반환합니다.
|
||||
*
|
||||
* @param array $filters 검색 필터
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 페이지네이터
|
||||
* @return LengthAwarePaginator 페이지네이터
|
||||
*/
|
||||
public function search(array $filters, int $perPage = 20)
|
||||
{
|
||||
@@ -221,10 +277,19 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
|
||||
return $this->cache->remember(
|
||||
IdentityPolicy::ROUTE_SCOPE_CACHE_KEY,
|
||||
function (): array {
|
||||
$policies = IdentityPolicy::query()
|
||||
$query = IdentityPolicy::query()
|
||||
->where('scope', 'route')
|
||||
->where('enabled', true)
|
||||
->where('enabled', true);
|
||||
|
||||
// 비활성 모듈/플러그인이 선언한 정책은 enforce 대상에서 제외
|
||||
$this->applyActiveExtensionScope($query);
|
||||
|
||||
// resolveByScopeTarget 과 동일한 결정적 정렬 — priority 동률 시 id 오름차순.
|
||||
// 미들웨어가 이 인덱스 순서대로 enforce 하므로, 2차 키가 없으면 동률 정책의
|
||||
// 적용 순서가 캐시 재빌드/실행계획에 따라 달라진다.
|
||||
$policies = $query
|
||||
->orderByDesc('priority')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
$index = [];
|
||||
@@ -250,7 +315,6 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
|
||||
* brace expansion — 'api.admin.{modules,plugins}.uninstall' → ['api.admin.modules.uninstall', 'api.admin.plugins.uninstall'].
|
||||
* 단일 그룹만 지원 (중첩/다중 그룹은 정책 키를 분리해서 정의하는 편이 명확).
|
||||
*
|
||||
* @param string $target
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function expandTargetBraces(string $target): array
|
||||
@@ -276,7 +340,7 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
|
||||
public function listHookTargets(): array
|
||||
{
|
||||
try {
|
||||
if (! \Illuminate\Support\Facades\Schema::hasTable('identity_policies')) {
|
||||
if (! Schema::hasTable('identity_policies')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -291,4 +355,67 @@ class IdentityPolicyRepository implements IdentityPolicyRepositoryInterface
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비활성 모듈/플러그인이 선언한 정책을 enforce 대상에서 제외하는 쿼리 scope 를 적용합니다.
|
||||
*
|
||||
* 정책의 source_type/source_identifier 귀속 정보를 기준으로:
|
||||
* - core / admin 정책: 항상 포함 (확장 비활성 개념 없음)
|
||||
* - module 정책: source_identifier 가 활성 모듈일 때만 포함
|
||||
* - plugin 정책: source_identifier 가 활성 플러그인일 때만 포함
|
||||
*
|
||||
* `enabled` 컬럼(운영자 토글)은 그대로 보존하며, 확장이 재활성화되면 정책도 자동으로
|
||||
* 다시 enforce 된다. modules/plugins 테이블 부재(부팅/마이그레이션 전) 시에는
|
||||
* 필터를 적용하지 않아 기존 동작을 보존한다.
|
||||
*
|
||||
* @param Builder $query 대상 쿼리 빌더
|
||||
* @return Builder 활성 확장 필터가 적용된 쿼리 빌더
|
||||
*/
|
||||
protected function applyActiveExtensionScope(Builder $query): Builder
|
||||
{
|
||||
$activeModules = $this->activeExtensionIdentifiers(Module::class);
|
||||
$activePlugins = $this->activeExtensionIdentifiers(Plugin::class);
|
||||
|
||||
// 테이블 부재 등으로 활성 목록 자체를 조회하지 못한 경우(null) 필터 미적용 — 기존 동작 보존
|
||||
if ($activeModules === null && $activePlugins === null) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
return $query->where(function (Builder $q) use ($activeModules, $activePlugins): void {
|
||||
$q->whereIn('source_type', ['core', 'admin'])
|
||||
->orWhere(function (Builder $sub) use ($activeModules): void {
|
||||
$sub->where('source_type', 'module')
|
||||
->whereIn('source_identifier', $activeModules ?? []);
|
||||
})
|
||||
->orWhere(function (Builder $sub) use ($activePlugins): void {
|
||||
$sub->where('source_type', 'plugin')
|
||||
->whereIn('source_identifier', $activePlugins ?? []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 상태(ExtensionStatus::Active)인 확장 식별자 목록을 반환합니다.
|
||||
*
|
||||
* @param class-string<Module|Plugin> $modelClass modules 또는 plugins 모델 클래스
|
||||
* @return list<string>|null 활성 식별자 목록, 테이블 부재/조회 실패 시 null
|
||||
*/
|
||||
protected function activeExtensionIdentifiers(string $modelClass): ?array
|
||||
{
|
||||
try {
|
||||
$table = (new $modelClass)->getTable();
|
||||
if (! Schema::hasTable($table)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $modelClass::query()
|
||||
->where('status', ExtensionStatus::Active->value)
|
||||
->pluck('identifier')
|
||||
->filter(fn ($id) => is_string($id) && $id !== '')
|
||||
->values()
|
||||
->all();
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\LayoutExtensionRepositoryInterface;
|
||||
use App\Enums\LayoutExtensionType;
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Models\LayoutExtension;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -16,8 +15,8 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 특정 확장점에 등록된 확장 목록 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getByExtensionPoint(int $templateId, string $extensionPointName): Collection
|
||||
@@ -34,8 +33,8 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 특정 레이아웃을 타겟으로 하는 오버레이 목록 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getOverlaysByLayout(int $templateId, string $layoutName): Collection
|
||||
@@ -52,8 +51,8 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 확장 등록
|
||||
*
|
||||
* @param array $data 확장 데이터
|
||||
* @return LayoutExtension
|
||||
* @param array $data 확장 데이터
|
||||
* @return LayoutExtension 생성된 확장 모델
|
||||
*/
|
||||
public function create(array $data): LayoutExtension
|
||||
{
|
||||
@@ -66,9 +65,9 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
* 동일한 조건의 확장이 존재하면 업데이트하고, 없으면 생성합니다.
|
||||
* soft delete된 레코드도 복원하여 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 값
|
||||
* @return LayoutExtension
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 값
|
||||
* @return LayoutExtension 생성 또는 업데이트된 확장 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): LayoutExtension
|
||||
{
|
||||
@@ -94,8 +93,8 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 출처별 확장 삭제 (soft delete)
|
||||
*
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function softDeleteBySource(LayoutSourceType $sourceType, string $identifier): int
|
||||
@@ -108,8 +107,8 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 출처별 확장 복원
|
||||
*
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @return int 복원된 레코드 수
|
||||
*/
|
||||
public function restoreBySource(LayoutSourceType $sourceType, string $identifier): int
|
||||
@@ -123,8 +122,8 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 출처별 확장 영구 삭제
|
||||
*
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function forceDeleteBySource(LayoutSourceType $sourceType, string $identifier): int
|
||||
@@ -138,10 +137,10 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 템플릿 오버라이드 확인 (Extension Point용)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @param string $moduleIdentifier 모듈/플러그인 식별자
|
||||
* @return LayoutExtension|null
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @param string $moduleIdentifier 모듈/플러그인 식별자
|
||||
* @return LayoutExtension|null 템플릿 오버라이드 또는 null
|
||||
*/
|
||||
public function findTemplateOverrideForExtensionPoint(
|
||||
int $templateId,
|
||||
@@ -161,10 +160,10 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 템플릿 오버라이드 확인 (Overlay용)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param string $moduleIdentifier 모듈/플러그인 식별자
|
||||
* @return LayoutExtension|null
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param string $moduleIdentifier 모듈/플러그인 식별자
|
||||
* @return LayoutExtension|null 템플릿 오버라이드 또는 null
|
||||
*/
|
||||
public function findTemplateOverrideForOverlay(
|
||||
int $templateId,
|
||||
@@ -184,8 +183,8 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
/**
|
||||
* 오버라이드를 고려한 Extension Point 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getResolvedExtensionPoints(int $templateId, string $extensionPointName): Collection
|
||||
@@ -199,31 +198,15 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
->ordered()
|
||||
->get();
|
||||
|
||||
// 2. 템플릿 오버라이드가 있는 모듈 식별자 추출
|
||||
$overriddenModules = $allExtensions
|
||||
->where('source_type', LayoutSourceType::Template)
|
||||
->pluck('override_target')
|
||||
->filter()
|
||||
->unique()
|
||||
->toArray();
|
||||
|
||||
// 3. 오버라이드된 모듈/플러그인 확장은 제외하고 반환
|
||||
return $allExtensions->filter(function ($extension) use ($overriddenModules) {
|
||||
// 템플릿 오버라이드는 항상 포함
|
||||
if ($extension->source_type === LayoutSourceType::Template) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 오버라이드된 모듈/플러그인 확장은 제외
|
||||
return ! in_array($extension->source_identifier, $overriddenModules, true);
|
||||
})->values();
|
||||
// 2. 템플릿 오버라이드에 가려진 모듈/플러그인 확장 제거
|
||||
return $this->resolveOverrides($allExtensions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 오버라이드를 고려한 Overlay 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getResolvedOverlays(int $templateId, string $layoutName): Collection
|
||||
@@ -237,30 +220,54 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
->ordered()
|
||||
->get();
|
||||
|
||||
// 2. 템플릿 오버라이드가 있는 모듈 식별자 추출
|
||||
$overriddenModules = $allOverlays
|
||||
// 2. 템플릿 오버라이드에 가려진 모듈/플러그인 확장 제거
|
||||
return $this->resolveOverrides($allOverlays);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 오버라이드 해석을 적용해 가려진 확장을 제거합니다.
|
||||
*
|
||||
* 동일한 (extension_type, target_name) 범위 안에서, 템플릿이 특정
|
||||
* 모듈/플러그인을 오버라이드하면 그 모듈/플러그인의 원본 확장은
|
||||
* 화면에 적용되지 않으므로 결과에서 제외합니다. 템플릿 오버라이드 행은
|
||||
* 항상 유지됩니다.
|
||||
*
|
||||
* 렌더링 경로(getResolvedExtensionPoints/getResolvedOverlays)와
|
||||
* 편집 화면 트리(getByTemplateId)가 동일한 가시성 기준을 공유하도록
|
||||
* 이 메서드를 단일 출처(SSoT)로 사용합니다.
|
||||
*
|
||||
* 호출 측은 동일한 (extension_type, target_name) 범위의 확장만
|
||||
* 전달해야 합니다. 혼합 컬렉션은 target_name 별로 그룹핑한 뒤
|
||||
* 그룹마다 호출하십시오.
|
||||
*
|
||||
* @param Collection<int, LayoutExtension> $extensions 동일 범위 확장 컬렉션
|
||||
* @return Collection<int, LayoutExtension> 오버라이드에 가려진 행을 제외한 컬렉션
|
||||
*/
|
||||
public function resolveOverrides(Collection $extensions): Collection
|
||||
{
|
||||
// 템플릿 오버라이드가 가리키는 모듈/플러그인 식별자 추출
|
||||
$overriddenSources = $extensions
|
||||
->where('source_type', LayoutSourceType::Template)
|
||||
->pluck('override_target')
|
||||
->filter()
|
||||
->unique()
|
||||
->toArray();
|
||||
|
||||
// 3. 오버라이드된 모듈/플러그인 확장은 제외하고 반환
|
||||
return $allOverlays->filter(function ($overlay) use ($overriddenModules) {
|
||||
return $extensions->filter(function ($extension) use ($overriddenSources) {
|
||||
// 템플릿 오버라이드는 항상 포함
|
||||
if ($overlay->source_type === LayoutSourceType::Template) {
|
||||
if ($extension->source_type === LayoutSourceType::Template) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 오버라이드된 모듈/플러그인 확장은 제외
|
||||
return ! in_array($overlay->source_identifier, $overriddenModules, true);
|
||||
return ! in_array($extension->source_identifier, $overriddenSources, true);
|
||||
})->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 확장 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getByTemplateId(int $templateId): Collection
|
||||
@@ -272,10 +279,116 @@ class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 확장을 오버라이드 해석을 적용해 조회합니다.
|
||||
*
|
||||
* getByTemplateId 가 모든 행을 반환하는 것과 달리, 템플릿 오버라이드에
|
||||
* 가려져 화면에 적용되지 않는 모듈/플러그인 확장을 제외합니다.
|
||||
* 레이아웃 편집 화면 좌측 트리가 "실제 화면에 반영되는 확장"만 보여주도록
|
||||
* 렌더링 경로와 동일한 가시성 기준(resolveOverrides)을 적용합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection<int, LayoutExtension> 오버라이드에 가려진 행을 제외한 컬렉션
|
||||
*/
|
||||
public function getResolvedByTemplateId(int $templateId): Collection
|
||||
{
|
||||
$all = $this->getByTemplateId($templateId);
|
||||
|
||||
// (extension_type, target_name) 별로 그룹핑한 뒤 그룹마다 오버라이드 해석
|
||||
return $all
|
||||
->groupBy(fn ($extension) => $extension->extension_type->value.'|'.$extension->target_name)
|
||||
->flatMap(fn (Collection $group) => $this->resolveOverrides($group))
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 단일 확장 조회
|
||||
*
|
||||
* @param int $extensionId 확장 ID
|
||||
* @return LayoutExtension|null 확장 모델 또는 null
|
||||
*/
|
||||
public function findById(int $extensionId): ?LayoutExtension
|
||||
{
|
||||
return LayoutExtension::find($extensionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 출처(모듈/플러그인)의 모든 확장 조회
|
||||
*
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getBySource(LayoutSourceType $sourceType, string $identifier): Collection
|
||||
{
|
||||
return LayoutExtension::query()
|
||||
->bySource($sourceType, $identifier)
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 조회 조건에 일치하는 확장을 조회합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @return LayoutExtension|null 일치하는 확장 또는 null
|
||||
*/
|
||||
public function findByAttributes(array $attributes): ?LayoutExtension
|
||||
{
|
||||
return LayoutExtension::query()->where($attributes)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 조회 조건에 일치하는 모든 LIVE 확장을 템플릿 구분 없이 조회합니다.
|
||||
*
|
||||
* cross-template 판정에 사용 — 동일 확장(source/type/target)이 어느 템플릿들에
|
||||
* 등록돼 있는지 전수 확인하기 위함. template_id 는 조건에 넣지 않는다.
|
||||
*
|
||||
* @param array $attributes 조회 조건 (template_id 제외)
|
||||
* @return \Illuminate\Database\Eloquent\Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getAllByAttributesAcrossTemplates(array $attributes): \Illuminate\Database\Eloquent\Collection
|
||||
{
|
||||
return LayoutExtension::query()->where($attributes)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 업데이트
|
||||
*
|
||||
* @param int $extensionId 확장 ID
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return LayoutExtension 업데이트된 확장 모델
|
||||
*/
|
||||
public function update(int $extensionId, array $data): LayoutExtension
|
||||
{
|
||||
$extension = LayoutExtension::findOrFail($extensionId);
|
||||
$extension->update($data);
|
||||
|
||||
return $extension->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 content + lock_version 동시 갱신 (낙관적 잠금)
|
||||
*
|
||||
* Service 가 호출 직전에 expected_lock_version 검증을 마친 상태로,
|
||||
* 본 메서드는 update 데이터에 lock_version 증가를 함께 반영한다.
|
||||
*
|
||||
* @param int $extensionId 확장 ID
|
||||
* @param array $data 업데이트 데이터 (content, priority 등)
|
||||
* @param int $newLockVersion 새 lock_version 값 (currentVersion + 1)
|
||||
* @return LayoutExtension 업데이트된 확장 모델
|
||||
*/
|
||||
public function updateWithLock(int $extensionId, array $data, int $newLockVersion): LayoutExtension
|
||||
{
|
||||
$extension = LayoutExtension::findOrFail($extensionId);
|
||||
$extension->update([...$data, 'lock_version' => $newLockVersion]);
|
||||
|
||||
return $extension->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 확장 삭제
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByTemplateId(int $templateId): int
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\LayoutExtensionVersionRepositoryInterface;
|
||||
use App\Models\LayoutExtension;
|
||||
use App\Models\TemplateLayoutExtensionVersion;
|
||||
use App\Repositories\Concerns\CalculatesJsonContentDiff;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class LayoutExtensionVersionRepository implements LayoutExtensionVersionRepositoryInterface
|
||||
{
|
||||
use CalculatesJsonContentDiff;
|
||||
|
||||
public function __construct(
|
||||
private TemplateLayoutExtensionVersion $model
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 버전 저장 (자동 증가)
|
||||
*
|
||||
* 버전 1건은 저장 시점의 content 스냅샷(`$content`)을 담고, changes_summary 는 직전
|
||||
* 버전(`$previousContent`) 대비 변경(추가/삭제/변경/문자수)을 기록한다. (레이아웃 본체와
|
||||
* 동일 정책 — 종전 2건 저장 + 자기 비교로 최신 버전 changes_summary 가 0 이던 결함 수정.)
|
||||
*
|
||||
* @param int $extensionId 레이아웃 확장 ID
|
||||
* @param array $content 저장할 content 스냅샷
|
||||
* @param array|null $previousContent 직전 버전 content (변경 요약 기준). null 이면 변경 요약 0
|
||||
* @return TemplateLayoutExtensionVersion 생성된 버전
|
||||
*/
|
||||
public function saveVersion(int $extensionId, array $content, ?array $previousContent = null): TemplateLayoutExtensionVersion
|
||||
{
|
||||
$nextVersion = $this->getNextVersion($extensionId);
|
||||
|
||||
// changes_summary 계산 — 직전 버전 대비 이 스냅샷의 변경. 직전이 없으면(최초) 빈 요약.
|
||||
$changesSummary = $previousContent !== null
|
||||
? $this->calculateChanges($previousContent, $content)
|
||||
: ['added' => 0, 'removed' => 0, 'char_diff' => 0];
|
||||
|
||||
return $this->model->create([
|
||||
'extension_id' => $extensionId,
|
||||
'version' => $nextVersion,
|
||||
'content' => $content,
|
||||
'changes_summary' => $changesSummary,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 확장의 모든 버전 조회 (최신순)
|
||||
*
|
||||
* @param int $extensionId 레이아웃 확장 ID
|
||||
* @return Collection 버전 컬렉션
|
||||
*/
|
||||
public function getVersions(int $extensionId): Collection
|
||||
{
|
||||
// creator eager load — 버전 목록에 저장자 이름(created_by_name) 노출용 (N+1 회피,
|
||||
// 레이아웃 본체 getVersionsByLayoutId 와 동일 정책).
|
||||
return $this->model
|
||||
->with('creator:id,name')
|
||||
->where('extension_id', $extensionId)
|
||||
->orderBy('version', 'desc')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 ID 목록의 현재(최신) 버전 번호 맵 조회
|
||||
*
|
||||
* 레이아웃 편집기 라우트 트리의 확장 노드 버전 배지용 —
|
||||
* 버전 이력이 있는 확장만 포함된다(미저장 확장 = 원본 → 맵 제외 → 배지 미표시).
|
||||
*
|
||||
* @param array<int> $extensionIds 확장 ID 목록
|
||||
* @return array<int, int> 확장 ID → 최신 버전 번호
|
||||
*/
|
||||
public function getCurrentVersionsByExtensionIds(array $extensionIds): array
|
||||
{
|
||||
if ($extensionIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->model->newQuery()
|
||||
->whereIn('extension_id', $extensionIds)
|
||||
->groupBy('extension_id')
|
||||
->selectRaw('extension_id, MAX(version) as current_version')
|
||||
->pluck('current_version', 'extension_id')
|
||||
->map(fn ($version) => (int) $version)
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 버전 조회
|
||||
*
|
||||
* @param int $versionId 버전 ID
|
||||
* @return TemplateLayoutExtensionVersion|null 찾은 버전 모델 또는 null
|
||||
*/
|
||||
public function getVersion(int $versionId): ?TemplateLayoutExtensionVersion
|
||||
{
|
||||
return $this->model->find($versionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다음 버전 번호 계산
|
||||
*
|
||||
* @param int $extensionId 레이아웃 확장 ID
|
||||
* @return int 다음 버전 번호
|
||||
*/
|
||||
public function getNextVersion(int $extensionId): int
|
||||
{
|
||||
$maxVersion = $this->model
|
||||
->where('extension_id', $extensionId)
|
||||
->max('version');
|
||||
|
||||
return $maxVersion ? $maxVersion + 1 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 복원
|
||||
*
|
||||
* @param int $extensionId 레이아웃 확장 ID
|
||||
* @param int $versionId 복원할 버전 ID
|
||||
* @return TemplateLayoutExtensionVersion 복원 후 생성된 새 버전
|
||||
*
|
||||
* @throws ModelNotFoundException 버전을 찾을 수 없는 경우
|
||||
*/
|
||||
public function restoreVersion(int $extensionId, int $versionId): TemplateLayoutExtensionVersion
|
||||
{
|
||||
return DB::transaction(function () use ($extensionId, $versionId) {
|
||||
// 1. 복원할 버전 조회
|
||||
$versionToRestore = $this->model
|
||||
->where('id', $versionId)
|
||||
->where('extension_id', $extensionId)
|
||||
->firstOrFail();
|
||||
|
||||
// 2. 확장 모델 조회 및 복원 직전 content 보관 (변경 요약 기준)
|
||||
$extension = LayoutExtension::findOrFail($extensionId);
|
||||
$currentContent = $extension->content;
|
||||
|
||||
// 3. 확장을 복원할 content로 업데이트
|
||||
$extension->update([
|
||||
'content' => $versionToRestore->content,
|
||||
]);
|
||||
|
||||
// 4. 복원 결과를 새 버전으로 저장 — content 는 복원된 내용, changes_summary 는 복원
|
||||
// 직전(currentContent) 대비 변경(레이아웃 본체와 동일 — 복원으로 줄면 삭제, 늘면 추가).
|
||||
return $this->saveVersion($extensionId, $versionToRestore->content, $currentContent);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getByTemplateId(int $templateId): Collection
|
||||
{
|
||||
@@ -22,6 +25,10 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
|
||||
/**
|
||||
* 특정 레이아웃 조회 (템플릿 ID와 이름으로)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findByName(int $templateId, string $name): ?TemplateLayout
|
||||
{
|
||||
@@ -32,6 +39,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
|
||||
/**
|
||||
* ID로 레이아웃 조회
|
||||
*
|
||||
* @param int $id 레이아웃 ID
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?TemplateLayout
|
||||
{
|
||||
@@ -40,6 +50,10 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
|
||||
/**
|
||||
* 레이아웃이 존재하는지 확인
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return bool 존재 여부
|
||||
*/
|
||||
public function exists(int $templateId, string $name): bool
|
||||
{
|
||||
@@ -48,8 +62,145 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 레이아웃 중 지정한 확장점(extension_point)을 정의한 것이 있는지 확인
|
||||
*
|
||||
* 레이아웃 content JSON 트리를 재귀 순회하여 `type: extension_point` 노드의
|
||||
* `name` 이 일치하는지 검사합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @return bool 정의 존재 여부
|
||||
*/
|
||||
public function hasExtensionPoint(int $templateId, string $extensionPointName): bool
|
||||
{
|
||||
// 1차 필터: content 에 extension_point 명이 포함된 레이아웃만 조회 (성능 최적화)
|
||||
$layouts = TemplateLayout::where('template_id', $templateId)
|
||||
->where('content', 'like', '%'.$extensionPointName.'%')
|
||||
->get(['content']);
|
||||
|
||||
foreach ($layouts as $layout) {
|
||||
if ($this->containsExtensionPoint($layout->content, $extensionPointName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정 extension_point 를 포함하는 레이아웃 이름 목록을 반환합니다.
|
||||
*
|
||||
* 확장 편집 모드에서 extension_point 확장의 대표 호스트 레이아웃 선택(picker)에 쓴다.
|
||||
* 여러 레이아웃에 같은 확장점이 있으면 모두 반환하며, 클라이언트가 1개면 즉시 진입,
|
||||
* 복수면 선택 모달을 띄운다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @return array<int, string> 호스트 레이아웃 이름 목록 (정렬됨)
|
||||
*/
|
||||
public function findLayoutNamesWithExtensionPoint(int $templateId, string $extensionPointName): array
|
||||
{
|
||||
$layouts = TemplateLayout::where('template_id', $templateId)
|
||||
->where('content', 'like', '%'.$extensionPointName.'%')
|
||||
->get(['name', 'content']);
|
||||
|
||||
$names = [];
|
||||
foreach ($layouts as $layout) {
|
||||
if ($this->containsExtensionPoint($layout->content, $extensionPointName)) {
|
||||
$names[] = $layout->name;
|
||||
}
|
||||
}
|
||||
|
||||
sort($names);
|
||||
|
||||
return $names;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 content 트리에 지정 노드 id 가 존재하는지 확인합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param string $nodeId 찾을 노드 id
|
||||
* @return bool 노드 id 존재 여부
|
||||
*/
|
||||
public function layoutContainsNodeId(int $templateId, string $layoutName, string $nodeId): bool
|
||||
{
|
||||
$layout = $this->findByNameWithOverride($templateId, $layoutName)
|
||||
?? $this->findByName($templateId, $layoutName);
|
||||
if ($layout === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$content = is_array($layout->content)
|
||||
? $layout->content
|
||||
: json_decode((string) $layout->content, true);
|
||||
|
||||
return is_array($content) && $this->containsNodeId($content, $nodeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* content 트리를 재귀 순회하여 노드 id(`id` 또는 `props.id`)가 일치하는 노드를 검색합니다.
|
||||
*
|
||||
* @param mixed $node 탐색 노드 (배열 또는 스칼라)
|
||||
* @param string $nodeId 찾을 노드 id
|
||||
* @return bool 발견 여부
|
||||
*/
|
||||
private function containsNodeId(mixed $node, string $nodeId): bool
|
||||
{
|
||||
if (! is_array($node)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$id = $node['id'] ?? ($node['props']['id'] ?? null);
|
||||
if ($id === $nodeId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ($node as $value) {
|
||||
if (is_array($value) && $this->containsNodeId($value, $nodeId)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 content 트리를 재귀 순회하여 extension_point 노드를 검색합니다.
|
||||
*
|
||||
* @param mixed $node 탐색 노드 (배열 또는 스칼라)
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @return bool 발견 여부
|
||||
*/
|
||||
private function containsExtensionPoint(mixed $node, string $extensionPointName): bool
|
||||
{
|
||||
if (! is_array($node)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// extension_point 노드 검출
|
||||
if (($node['type'] ?? null) === 'extension_point' && ($node['name'] ?? null) === $extensionPointName) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 모든 하위 노드 재귀 탐색 (components / children / slots 등 구조 무관)
|
||||
foreach ($node as $value) {
|
||||
if (is_array($value) && $this->containsExtensionPoint($value, $extensionPointName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* extends를 가진 자식 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extendsName 부모 레이아웃 이름
|
||||
* @return Collection 자식 레이아웃 컬렉션
|
||||
*/
|
||||
public function getChildrenByExtends(int $templateId, string $extendsName): Collection
|
||||
{
|
||||
@@ -82,22 +233,57 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
return $layout->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 content + lock_version 동시 갱신 (낙관적 잠금)
|
||||
*
|
||||
* Service 가 호출 직전에 expected_lock_version 검증을 마친 상태로,
|
||||
* 본 메서드는 content 교체와 lock_version 증가를 한 번의 UPDATE 로 수행한다.
|
||||
*
|
||||
* @param int $id 레이아웃 ID
|
||||
* @param array $content 전체 레이아웃 JSON content
|
||||
* @param int $newLockVersion 새 lock_version 값 (currentVersion + 1)
|
||||
* @return TemplateLayout 업데이트된 레이아웃 모델
|
||||
*/
|
||||
public function updateContent(int $id, array $content, int $newLockVersion): TemplateLayout
|
||||
{
|
||||
$layout = TemplateLayout::findOrFail($id);
|
||||
|
||||
$layout->content = $content;
|
||||
$layout->extends = $content['extends'] ?? null;
|
||||
$layout->lock_version = $newLockVersion;
|
||||
|
||||
$layout->save();
|
||||
|
||||
return $layout->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 레이아웃의 모든 버전 조회
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @return Collection 버전 컬렉션
|
||||
*/
|
||||
public function getVersionsByLayoutId(int $layoutId): Collection
|
||||
{
|
||||
return TemplateLayoutVersion::where('layout_id', $layoutId)
|
||||
// creator eager load — 버전 목록에 저장자 이름(created_by_name) 노출용 (N+1 회피).
|
||||
return TemplateLayoutVersion::with('creator:id,name')
|
||||
->where('layout_id', $layoutId)
|
||||
->latest()
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 버전 조회
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @param int $version 버전 번호
|
||||
* @return TemplateLayoutVersion|null 찾은 버전 모델 또는 null
|
||||
*/
|
||||
public function findVersionByNumber(int $layoutId, int $version): ?TemplateLayoutVersion
|
||||
{
|
||||
return TemplateLayoutVersion::where('layout_id', $layoutId)
|
||||
// creator eager load — 단건 버전 조회(showVersion)도 저장자 이름 일관 노출.
|
||||
return TemplateLayoutVersion::with('creator:id,name')
|
||||
->where('layout_id', $layoutId)
|
||||
->where('version', $version)
|
||||
->first();
|
||||
}
|
||||
@@ -105,8 +291,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
/**
|
||||
* 템플릿 오버라이드 레이아웃 찾기
|
||||
*
|
||||
* 템플릿에서 제공하는 오버라이드 레이아웃을 검색합니다.
|
||||
* source_type = 'template'이고 source_identifier가 있는 레이아웃
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findTemplateOverride(int $templateId, string $layoutName): ?TemplateLayout
|
||||
{
|
||||
@@ -120,8 +307,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
/**
|
||||
* 모듈 기본 레이아웃 찾기
|
||||
*
|
||||
* 모듈에서 제공하는 기본 레이아웃을 검색합니다.
|
||||
* source_type = 'module'인 레이아웃
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findModuleLayout(int $templateId, string $layoutName): ?TemplateLayout
|
||||
{
|
||||
@@ -134,7 +322,8 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃 이름 조회
|
||||
*
|
||||
* @return \Illuminate\Support\Collection<int, string>
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return \Illuminate\Support\Collection<int, string> 레이아웃 이름 컬렉션
|
||||
*/
|
||||
public function getLayoutNamesByTemplateId(int $templateId): \Illuminate\Support\Collection
|
||||
{
|
||||
@@ -145,6 +334,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
|
||||
/**
|
||||
* 특정 모듈의 모든 레이아웃 조회
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getLayoutsByModule(string $moduleIdentifier): Collection
|
||||
{
|
||||
@@ -155,6 +347,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
|
||||
/**
|
||||
* 특정 템플릿에서 오버라이드된 모든 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection 오버라이드 레이아웃 컬렉션
|
||||
*/
|
||||
public function getOverriddenLayouts(int $templateId): Collection
|
||||
{
|
||||
@@ -166,6 +361,10 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
|
||||
/**
|
||||
* 특정 모듈의 레이아웃 중 템플릿에서 오버라이드된 것들 조회
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection 오버라이드 레이아웃 컬렉션
|
||||
*/
|
||||
public function getModuleLayoutOverrides(string $moduleIdentifier, int $templateId): Collection
|
||||
{
|
||||
@@ -186,10 +385,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
/**
|
||||
* 우선순위에 따라 레이아웃 조회 (오버라이드 우선)
|
||||
*
|
||||
* 우선순위:
|
||||
* 1. 템플릿 오버라이드 (source_type = 'template', source_identifier 있음)
|
||||
* 2. 모듈 기본 레이아웃 (source_type = 'module')
|
||||
* 3. 일반 템플릿 레이아웃 (source_type = 'template', source_identifier 없음)
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findByNameWithOverride(int $templateId, string $name): ?TemplateLayout
|
||||
{
|
||||
@@ -214,6 +412,7 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $moduleIdentifier 특정 모듈만 조회 (선택)
|
||||
* @return Collection 모듈 레이아웃 컬렉션
|
||||
*/
|
||||
public function findModuleLayouts(int $templateId, ?string $moduleIdentifier = null): Collection
|
||||
{
|
||||
@@ -234,6 +433,7 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
* @param string|null $sourceType 소스 타입 필터 ('template', 'module', 'plugin')
|
||||
* @param string|null $sourceIdentifier 소스 식별자 필터 (null이면 source_identifier가 null인 레코드만 조회)
|
||||
* @param bool $nullIdentifierOnly true이면 source_identifier가 null인 레코드만 조회 (sourceIdentifier 파라미터가 null일 때만 적용)
|
||||
* @return Collection 필터링된 레이아웃 컬렉션
|
||||
*/
|
||||
public function getByTemplateIdWithFilter(
|
||||
int $templateId,
|
||||
@@ -260,6 +460,9 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
|
||||
/**
|
||||
* 특정 플러그인의 모든 레이아웃 조회
|
||||
*
|
||||
* @param string $pluginIdentifier 플러그인 식별자
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getLayoutsByPlugin(string $pluginIdentifier): Collection
|
||||
{
|
||||
@@ -273,6 +476,7 @@ class LayoutRepository implements LayoutRepositoryInterface
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $pluginIdentifier 특정 플러그인만 조회 (선택)
|
||||
* @return Collection 플러그인 레이아웃 컬렉션
|
||||
*/
|
||||
public function findPluginLayouts(int $templateId, ?string $pluginIdentifier = null): Collection
|
||||
{
|
||||
|
||||
@@ -5,12 +5,15 @@ namespace App\Repositories;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\TemplateLayoutVersion;
|
||||
use App\Repositories\Concerns\CalculatesJsonContentDiff;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class LayoutVersionRepository implements LayoutVersionRepositoryInterface
|
||||
{
|
||||
use CalculatesJsonContentDiff;
|
||||
|
||||
public function __construct(
|
||||
private TemplateLayoutVersion $model
|
||||
) {}
|
||||
@@ -18,34 +21,37 @@ class LayoutVersionRepository implements LayoutVersionRepositoryInterface
|
||||
/**
|
||||
* 버전 저장 (자동 증가)
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @param array $oldContent 이전 콘텐츠
|
||||
* @param array|null $newContent 새 콘텐츠 (null이면 현재 레이아웃에서 가져옴)
|
||||
* 버전 1건은 저장 시점의 content 스냅샷(`$content`)을 담고, changes_summary 는
|
||||
* 직전 버전(`$previousContent`) 대비 그 스냅샷이 무엇이 바뀌었는지(추가/삭제/변경/문자수)를
|
||||
* 기록한다. 따라서 목록의 각 버전은 "이 버전이 직전 대비 어떻게 바뀌었나"를 정확히 표현한다.
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @param array $content 저장할 content 스냅샷 (이 버전이 담는 내용)
|
||||
* @param array|null $previousContent 직전 버전 content (변경 요약 기준). null 이면 변경 요약 0
|
||||
* @return TemplateLayoutVersion 생성된 버전
|
||||
*/
|
||||
public function saveVersion(int $layoutId, array $oldContent, ?array $newContent = null): TemplateLayoutVersion
|
||||
public function saveVersion(int $layoutId, array $content, ?array $previousContent = null): TemplateLayoutVersion
|
||||
{
|
||||
$nextVersion = $this->getNextVersion($layoutId);
|
||||
|
||||
// newContent가 제공되지 않으면 현재 레이아웃 content를 사용
|
||||
if ($newContent === null) {
|
||||
$layout = TemplateLayout::findOrFail($layoutId);
|
||||
$newContent = $layout->content;
|
||||
}
|
||||
|
||||
// changes_summary 계산
|
||||
$changesSummary = $this->calculateChanges($oldContent, $newContent);
|
||||
// changes_summary 계산 — 직전 버전 대비 이 스냅샷의 변경. 직전이 없으면(최초) 빈 요약.
|
||||
$changesSummary = $previousContent !== null
|
||||
? $this->calculateChanges($previousContent, $content)
|
||||
: ['added' => 0, 'removed' => 0, 'char_diff' => 0];
|
||||
|
||||
return $this->model->create([
|
||||
'layout_id' => $layoutId,
|
||||
'version' => $nextVersion,
|
||||
'content' => $oldContent,
|
||||
'content' => $content,
|
||||
'changes_summary' => $changesSummary,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 레이아웃의 모든 버전 조회 (최신순)
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @return Collection 버전 컬렉션
|
||||
*/
|
||||
public function getVersions(int $layoutId): Collection
|
||||
{
|
||||
@@ -57,6 +63,9 @@ class LayoutVersionRepository implements LayoutVersionRepositoryInterface
|
||||
|
||||
/**
|
||||
* 특정 버전 조회
|
||||
*
|
||||
* @param int $versionId 버전 ID
|
||||
* @return TemplateLayoutVersion|null 찾은 버전 모델 또는 null
|
||||
*/
|
||||
public function getVersion(int $versionId): ?TemplateLayoutVersion
|
||||
{
|
||||
@@ -65,6 +74,9 @@ class LayoutVersionRepository implements LayoutVersionRepositoryInterface
|
||||
|
||||
/**
|
||||
* 다음 버전 번호 계산
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @return int 다음 버전 번호
|
||||
*/
|
||||
public function getNextVersion(int $layoutId): int
|
||||
{
|
||||
@@ -75,96 +87,13 @@ class LayoutVersionRepository implements LayoutVersionRepositoryInterface
|
||||
return $maxVersion ? $maxVersion + 1 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON content 변경사항 계산
|
||||
*/
|
||||
public function calculateChanges(array $oldContent, array $newContent): array
|
||||
{
|
||||
$added = [];
|
||||
$removed = [];
|
||||
$modified = [];
|
||||
|
||||
// 재귀적으로 비교
|
||||
$this->diffRecursive($oldContent, $newContent, '', $added, $removed, $modified);
|
||||
|
||||
// 문자 수 변화 계산
|
||||
$oldChars = strlen(json_encode($oldContent, JSON_UNESCAPED_UNICODE));
|
||||
$newChars = strlen(json_encode($newContent, JSON_UNESCAPED_UNICODE));
|
||||
$charDiff = $newChars - $oldChars;
|
||||
|
||||
return [
|
||||
'added' => $added,
|
||||
'removed' => $removed,
|
||||
'modified' => $modified,
|
||||
'char_diff' => $charDiff,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 재귀적 JSON diff 알고리즘
|
||||
*/
|
||||
private function diffRecursive(
|
||||
array $old,
|
||||
array $new,
|
||||
string $prefix,
|
||||
array &$added,
|
||||
array &$removed,
|
||||
array &$modified
|
||||
): void {
|
||||
// 삭제된 키 찾기
|
||||
foreach ($old as $key => $value) {
|
||||
$path = $prefix ? "{$prefix}.{$key}" : $key;
|
||||
|
||||
if (!array_key_exists($key, $new)) {
|
||||
$removed[] = $path;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 값 비교
|
||||
$oldValue = $old[$key];
|
||||
$newValue = $new[$key];
|
||||
|
||||
// 둘 다 배열이면 재귀 호출
|
||||
if (is_array($oldValue) && is_array($newValue)) {
|
||||
$this->diffRecursive($oldValue, $newValue, $path, $added, $removed, $modified);
|
||||
} elseif ($oldValue !== $newValue) {
|
||||
// 값이 변경됨
|
||||
$modified[] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
// 추가된 키 찾기
|
||||
foreach ($new as $key => $value) {
|
||||
if (!array_key_exists($key, $old)) {
|
||||
$path = $prefix ? "{$prefix}.{$key}" : $key;
|
||||
$added[] = $path;
|
||||
|
||||
// 추가된 항목의 하위 구조도 added로 포함
|
||||
if (is_array($value)) {
|
||||
$this->collectAddedPaths($value, $path, $added);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가된 경로의 모든 하위 경로 수집
|
||||
*/
|
||||
private function collectAddedPaths(array $data, string $prefix, array &$added): void
|
||||
{
|
||||
foreach ($data as $key => $value) {
|
||||
$path = "{$prefix}.{$key}";
|
||||
$added[] = $path;
|
||||
|
||||
if (is_array($value)) {
|
||||
$this->collectAddedPaths($value, $path, $added);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 복원
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @param int $versionId 복원할 버전 ID
|
||||
* @return TemplateLayoutVersion 복원 후 생성된 새 버전 모델
|
||||
*
|
||||
* @throws ModelNotFoundException 버전을 찾을 수 없는 경우
|
||||
*/
|
||||
public function restoreVersion(int $layoutId, int $versionId): TemplateLayoutVersion
|
||||
@@ -176,7 +105,7 @@ class LayoutVersionRepository implements LayoutVersionRepositoryInterface
|
||||
->where('layout_id', $layoutId)
|
||||
->firstOrFail();
|
||||
|
||||
// 2. 레이아웃 모델 조회 및 현재 content 저장
|
||||
// 2. 레이아웃 모델 조회 및 복원 직전 content 보관 (변경 요약 기준)
|
||||
$layout = TemplateLayout::findOrFail($layoutId);
|
||||
$currentContent = $layout->content;
|
||||
|
||||
@@ -185,8 +114,82 @@ class LayoutVersionRepository implements LayoutVersionRepositoryInterface
|
||||
'content' => $versionToRestore->content,
|
||||
]);
|
||||
|
||||
// 4. 복원 전 content를 새 버전으로 저장 (이력 보존)
|
||||
return $this->saveVersion($layoutId, $currentContent, $versionToRestore->content);
|
||||
// 4. 복원 결과를 새 버전으로 저장 — content 는 복원된 내용(versionToRestore),
|
||||
// changes_summary 는 복원 직전(currentContent) 대비 변경이다. 따라서 복원으로
|
||||
// 내용이 줄면 "삭제", 늘면 "추가"로 정확히 기록된다(종전엔 content 로 복원 직전
|
||||
// 상태를 저장하고 방향도 거꾸로라, 복원인데 "추가"로 표기되던 결함 수정).
|
||||
return $this->saveVersion($layoutId, $versionToRestore->content, $currentContent);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿의 레이아웃별 현재(최신) 버전 번호 맵 조회
|
||||
*
|
||||
* 레이아웃 편집기 라우트 트리의 버전 배지용 — 버전 이력이 있는
|
||||
* 레이아웃만 포함된다(미저장 레이아웃 = 원본 → 맵 제외 → 배지 미표시).
|
||||
*
|
||||
* @param int $templateId 대상 템플릿 ID
|
||||
* @return array<string, int> 레이아웃 이름 → 최신 버전 번호
|
||||
*/
|
||||
public function getCurrentVersionsByTemplateId(int $templateId): array
|
||||
{
|
||||
// 테이블 프리픽스 환경에서도 안전하도록 join/테이블 한정자 없이 2단계 조회 —
|
||||
// (1) 템플릿의 레이아웃 id→name 맵, (2) layout_id 별 MAX(version).
|
||||
$layoutNames = TemplateLayout::query()
|
||||
->where('template_id', $templateId)
|
||||
->pluck('name', 'id');
|
||||
|
||||
if ($layoutNames->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$maxVersions = $this->model->newQuery()
|
||||
->whereIn('layout_id', $layoutNames->keys())
|
||||
->groupBy('layout_id')
|
||||
->selectRaw('layout_id, MAX(version) as current_version')
|
||||
->pluck('current_version', 'layout_id');
|
||||
|
||||
$result = [];
|
||||
foreach ($maxVersions as $layoutId => $version) {
|
||||
$name = $layoutNames[$layoutId] ?? null;
|
||||
if ($name !== null) {
|
||||
$result[$name] = (int) $version;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 버전의 changes_summary 를 현재 알고리즘으로 재계산하여 갱신합니다.
|
||||
*
|
||||
* @return int 갱신된 버전 수
|
||||
*/
|
||||
public function recalculateAllChangeSummaries(): int
|
||||
{
|
||||
$updated = 0;
|
||||
|
||||
// 레이아웃별로 버전을 오름차순 정렬해 인접 쌍으로 재계산.
|
||||
$layoutIds = $this->model->query()->distinct()->pluck('layout_id');
|
||||
|
||||
foreach ($layoutIds as $layoutId) {
|
||||
$versions = $this->model
|
||||
->where('layout_id', $layoutId)
|
||||
->orderBy('version', 'asc')
|
||||
->get();
|
||||
|
||||
$previousContent = null;
|
||||
foreach ($versions as $version) {
|
||||
$summary = $previousContent !== null
|
||||
? $this->calculateChanges($previousContent, $version->content ?? [])
|
||||
: ['added' => 0, 'removed' => 0, 'char_diff' => 0];
|
||||
|
||||
$version->update(['changes_summary' => $summary]);
|
||||
$previousContent = $version->content ?? [];
|
||||
$updated++;
|
||||
}
|
||||
}
|
||||
|
||||
return $updated;
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,31 @@ use App\Enums\NotificationLogStatus;
|
||||
use App\Models\NotificationLog;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 최근 발송된 알림 로그를 발송 시각 최신순으로 조회합니다 (대시보드 최근 알림).
|
||||
*
|
||||
* @param int $limit 조회 건수
|
||||
* @return Collection<int, NotificationLog> 최근 알림 로그 컬렉션
|
||||
*/
|
||||
public function getRecent(int $limit): Collection
|
||||
{
|
||||
return NotificationLog::with(['recipientUser'])
|
||||
->orderByDesc('sent_at')
|
||||
->orderByDesc('id')
|
||||
->limit($limit)
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 알림 로그 조회.
|
||||
*
|
||||
* @param int $id 알림 로그 ID
|
||||
* @return NotificationLog|null 알림 로그 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?NotificationLog
|
||||
{
|
||||
@@ -21,6 +40,9 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
|
||||
/**
|
||||
* 알림 로그 생성.
|
||||
*
|
||||
* @param array<string, mixed> $data 생성 데이터
|
||||
* @return NotificationLog 생성된 알림 로그
|
||||
*/
|
||||
public function create(array $data): NotificationLog
|
||||
{
|
||||
@@ -29,6 +51,9 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
|
||||
/**
|
||||
* 알림 로그 삭제.
|
||||
*
|
||||
* @param NotificationLog $log 삭제 대상 알림 로그
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(NotificationLog $log): bool
|
||||
{
|
||||
@@ -37,6 +62,9 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
|
||||
/**
|
||||
* 다건 삭제.
|
||||
*
|
||||
* @param array<int, int> $ids 삭제할 알림 로그 ID 목록
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function bulkDelete(array $ids): int
|
||||
{
|
||||
@@ -45,6 +73,11 @@ class NotificationLogRepository implements NotificationLogRepositoryInterface
|
||||
|
||||
/**
|
||||
* 페이지네이션 목록 조회.
|
||||
*
|
||||
* @param array<string, mixed> $filters 필터 조건
|
||||
* @param int $perPage 페이지당 건수
|
||||
* @param User|null $scopeUser 스코프 적용 대상 사용자 (null이면 스코프 미적용)
|
||||
* @return LengthAwarePaginator 페이지네이션 결과
|
||||
*/
|
||||
public function getPaginated(array $filters = [], int $perPage = 20, ?User $scopeUser = null): LengthAwarePaginator
|
||||
{
|
||||
|
||||
@@ -56,6 +56,21 @@ class RoleRepository implements RoleRepositoryInterface
|
||||
return Role::where('identifier', $identifier)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 식별자로 역할에 소속된 사용자들을 조회합니다.
|
||||
*
|
||||
* 역할이 없거나 소속 사용자가 없으면 빈 컬렉션을 반환합니다.
|
||||
*
|
||||
* @param string $identifier 역할 식별자
|
||||
* @return Collection 역할 소속 사용자 컬렉션
|
||||
*/
|
||||
public function getUsersByIdentifier(string $identifier): Collection
|
||||
{
|
||||
$role = Role::where('identifier', $identifier)->first();
|
||||
|
||||
return $role ? $role->users()->get() : new Collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* 새로운 역할을 생성합니다.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\TemplateCustomTranslationRepositoryInterface;
|
||||
use App\Models\TemplateCustomTranslation;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class TemplateCustomTranslationRepository implements TemplateCustomTranslationRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 특정 템플릿의 커스텀 다국어 키 목록 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $layoutName 레이아웃 이름 필터 (null 이면 전체)
|
||||
* @param string|null $status 상태 필터 (null 이면 전체)
|
||||
* @return Collection<int, TemplateCustomTranslation> 커스텀 키 컬렉션
|
||||
*/
|
||||
public function getByTemplateId(int $templateId, ?string $layoutName = null, ?string $status = null): Collection
|
||||
{
|
||||
return TemplateCustomTranslation::query()
|
||||
->where('template_id', $templateId)
|
||||
->when($layoutName !== null, fn ($query) => $query->where('layout_name', $layoutName))
|
||||
->when($status !== null, fn ($query) => $query->where('status', $status))
|
||||
->orderBy('translation_key')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 활성 커스텀 다국어 키 조회 (런타임 병합용)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection<int, TemplateCustomTranslation> 활성 커스텀 키 컬렉션
|
||||
*/
|
||||
public function getActiveByTemplateId(int $templateId): Collection
|
||||
{
|
||||
return TemplateCustomTranslation::query()
|
||||
->where('template_id', $templateId)
|
||||
->active()
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿 + 레이아웃의 커스텀 키 조회 (좀비 감지용)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름 (원본)
|
||||
* @param string|null $status 상태 필터 (null 이면 전체)
|
||||
* @return Collection<int, TemplateCustomTranslation> 커스텀 키 컬렉션
|
||||
*/
|
||||
public function getByTemplateIdAndLayout(int $templateId, string $layoutName, ?string $status = null): Collection
|
||||
{
|
||||
return TemplateCustomTranslation::query()
|
||||
->where('template_id', $templateId)
|
||||
->where('layout_name', $layoutName)
|
||||
->when($status !== null, fn ($query) => $query->where('status', $status))
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 ID 목록의 상태를 일괄 변경합니다 (active ↔ orphaned 전이)
|
||||
*
|
||||
* @param array<int, int> $ids 대상 커스텀 키 ID 목록
|
||||
* @param string $status 새 상태 (active|orphaned)
|
||||
* @return int 변경된 행 수
|
||||
*/
|
||||
public function updateStatus(array $ids, string $status): int
|
||||
{
|
||||
if ($ids === []) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return TemplateCustomTranslation::query()
|
||||
->whereIn('id', $ids)
|
||||
->update(['status' => $status]);
|
||||
}
|
||||
|
||||
/**
|
||||
* ID로 커스텀 다국어 키 조회
|
||||
*
|
||||
* @param int $id 커스텀 키 ID
|
||||
* @return TemplateCustomTranslation|null 찾은 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?TemplateCustomTranslation
|
||||
{
|
||||
return TemplateCustomTranslation::find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 + 키로 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $translationKey 다국어 키
|
||||
* @return TemplateCustomTranslation|null 찾은 모델 또는 null
|
||||
*/
|
||||
public function findByKey(int $templateId, string $translationKey): ?TemplateCustomTranslation
|
||||
{
|
||||
return TemplateCustomTranslation::query()
|
||||
->where('template_id', $templateId)
|
||||
->where('translation_key', $translationKey)
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿 + 레이아웃의 최대 seq 조회
|
||||
*
|
||||
* `custom.{layoutKey}.{seq}` 형식 키에서 seq 의 현재 최대값을 반환합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutKey 키 네임스페이스 (레이아웃명 정규화)
|
||||
* @return int 현재 최대 seq (없으면 0)
|
||||
*/
|
||||
public function getMaxSeq(int $templateId, string $layoutKey): int
|
||||
{
|
||||
$prefix = "custom.{$layoutKey}.";
|
||||
|
||||
$keys = TemplateCustomTranslation::query()
|
||||
->where('template_id', $templateId)
|
||||
->where('translation_key', 'like', $prefix.'%')
|
||||
->pluck('translation_key');
|
||||
|
||||
$maxSeq = 0;
|
||||
foreach ($keys as $key) {
|
||||
$suffix = substr($key, strlen($prefix));
|
||||
if (ctype_digit($suffix)) {
|
||||
$maxSeq = max($maxSeq, (int) $suffix);
|
||||
}
|
||||
}
|
||||
|
||||
return $maxSeq;
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 다국어 키 생성
|
||||
*
|
||||
* @param array<string, mixed> $data 생성 데이터
|
||||
* @return TemplateCustomTranslation 생성된 모델
|
||||
*/
|
||||
public function create(array $data): TemplateCustomTranslation
|
||||
{
|
||||
return TemplateCustomTranslation::create($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 다국어 키 값 수정 (lock_version 갱신 포함)
|
||||
*
|
||||
* @param int $id 커스텀 키 ID
|
||||
* @param array<string, mixed> $data 수정 데이터
|
||||
* @param int $newLockVersion 새 잠금 버전
|
||||
* @return TemplateCustomTranslation 수정된 모델
|
||||
*/
|
||||
public function update(int $id, array $data, int $newLockVersion): TemplateCustomTranslation
|
||||
{
|
||||
$model = TemplateCustomTranslation::findOrFail($id);
|
||||
|
||||
$model->fill($data);
|
||||
$model->lock_version = $newLockVersion;
|
||||
$model->save();
|
||||
|
||||
return $model->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 다국어 키 삭제
|
||||
*
|
||||
* @param int $id 커스텀 키 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(int $id): bool
|
||||
{
|
||||
$model = TemplateCustomTranslation::find($id);
|
||||
|
||||
if ($model === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) $model->delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repositories;
|
||||
|
||||
use App\Contracts\Repositories\TemplateLayoutAttachmentRepositoryInterface;
|
||||
use App\Models\TemplateLayoutAttachment;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
/**
|
||||
* 템플릿 레이아웃 첨부 파일 Repository 구현체
|
||||
*/
|
||||
class TemplateLayoutAttachmentRepository implements TemplateLayoutAttachmentRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* ID로 첨부 파일 조회
|
||||
*
|
||||
* @param int $id 첨부 파일 ID
|
||||
* @return TemplateLayoutAttachment|null 첨부 파일 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?TemplateLayoutAttachment
|
||||
{
|
||||
return TemplateLayoutAttachment::find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿(+선택적 레이아웃)별 첨부 파일 목록 조회 (최신순)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $layoutName 레이아웃 이름 (null 이면 템플릿 전체)
|
||||
* @return Collection<int, TemplateLayoutAttachment>
|
||||
*/
|
||||
public function listForTemplate(int $templateId, ?string $layoutName = null): Collection
|
||||
{
|
||||
return TemplateLayoutAttachment::query()
|
||||
->where('template_id', $templateId)
|
||||
->when($layoutName !== null, fn ($query) => $query->where('layout_name', $layoutName))
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부 파일 생성
|
||||
*
|
||||
* @param array<string, mixed> $data 생성 데이터
|
||||
* @return TemplateLayoutAttachment 생성된 첨부 파일
|
||||
*/
|
||||
public function create(array $data): TemplateLayoutAttachment
|
||||
{
|
||||
return TemplateLayoutAttachment::create($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부 파일 삭제 (DB 행만 — 스토리지 파일 삭제는 Service 책임)
|
||||
*
|
||||
* @param TemplateLayoutAttachment $attachment 삭제할 첨부 파일
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(TemplateLayoutAttachment $attachment): bool
|
||||
{
|
||||
return (bool) $attachment->delete();
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use App\Repositories\Concerns\HasMultipleSearchFilters;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class UserRepository implements UserRepositoryInterface
|
||||
{
|
||||
@@ -232,6 +233,46 @@ class UserRepository implements UserRepositoryInterface
|
||||
return User::whereIn('uuid', $uuids)->get()->keyBy('uuid');
|
||||
}
|
||||
|
||||
/**
|
||||
* UUID 목록으로 사용자들을 조회합니다.
|
||||
*
|
||||
* @param array<int, string> $uuids 사용자 UUID 목록
|
||||
* @return Collection<int, User> 조회된 사용자 컬렉션
|
||||
*/
|
||||
public function findManyByUuids(array $uuids): Collection
|
||||
{
|
||||
return User::whereIn('uuid', $uuids)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 슈퍼관리자 1명을 조회합니다.
|
||||
*
|
||||
* 역할 기반 수신자 해석에서 대상 역할에 사용자가 없을 때 폴백 수신자로 사용합니다.
|
||||
*
|
||||
* @return User|null 슈퍼관리자 또는 없으면 null
|
||||
*/
|
||||
public function findSuperAdmin(): ?User
|
||||
{
|
||||
return User::superAdmins()->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 권한 identifier 를 가진 역할에 소속된 모든 사용자를 조회합니다.
|
||||
*
|
||||
* "권한을 가진 자" 기준이므로 권한이 회수되면 자동으로 결과에서 제외됩니다.
|
||||
*
|
||||
* @param string $permissionIdentifier 권한 identifier
|
||||
* @return Collection<int, User> 권한 보유 사용자 컬렉션
|
||||
*/
|
||||
public function findManyByPermissionIdentifier(string $permissionIdentifier): Collection
|
||||
{
|
||||
return User::query()
|
||||
->whereHas('roles.permissions', function ($query) use ($permissionIdentifier) {
|
||||
$query->where('permissions.identifier', $permissionIdentifier);
|
||||
})
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 연속 로그인 실패 카운터를 1 증가시킵니다.
|
||||
*
|
||||
@@ -255,9 +296,9 @@ class UserRepository implements UserRepositoryInterface
|
||||
*
|
||||
* @param User $user 잠글 사용자
|
||||
* @param int $minutes 잠금 유지 시간(분)
|
||||
* @return \Illuminate\Support\Carbon 잠금 해제 시각
|
||||
* @return Carbon 잠금 해제 시각
|
||||
*/
|
||||
public function lockAccount(User $user, int $minutes): \Illuminate\Support\Carbon
|
||||
public function lockAccount(User $user, int $minutes): Carbon
|
||||
{
|
||||
$lockedUntil = now()->addMinutes(max(1, $minutes));
|
||||
|
||||
@@ -275,7 +316,6 @@ class UserRepository implements UserRepositoryInterface
|
||||
* 멱등 — 모든 컬럼이 이미 초기 상태면 UPDATE 를 발행하지 않습니다.
|
||||
*
|
||||
* @param User $user 대상 사용자
|
||||
* @return void
|
||||
*/
|
||||
public function resetLoginAttempts(User $user): void
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user