v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

+240
View File
@@ -0,0 +1,240 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\ActivityLogRepositoryInterface;
use App\Helpers\PermissionHelper;
use App\Helpers\TimezoneHelper;
use App\Models\ActivityLog;
use App\Repositories\Concerns\HasMultipleSearchFilters;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
/**
* 활동 로그 Repository
*/
class ActivityLogRepository implements ActivityLogRepositoryInterface
{
use HasMultipleSearchFilters;
/**
* 특정 모델의 활동 로그를 페이지네이션하여 조회합니다.
*
* @param Model $model 대상 모델
* @param array $filters 필터 조건
* @return LengthAwarePaginator 페이지네이션된 로그 목록
*/
public function getPaginatedForModel(Model $model, array $filters = []): LengthAwarePaginator
{
$sortOrder = $filters['sort_order'] ?? 'desc';
$query = ActivityLog::forModel($model)->orderBy('created_at', $sortOrder);
if (isset($filters['action'])) {
$query->action($filters['action']);
}
if (isset($filters['user_id'])) {
$query->byUser($filters['user_id']);
}
return $query->paginate($filters['per_page'] ?? 15);
}
/**
* 활동 로그 목록을 페이지네이션하여 조회합니다.
*
* @param array $filters 필터 조건
* @return LengthAwarePaginator 페이지네이션된 로그 목록
*/
public function getPaginated(array $filters = []): LengthAwarePaginator
{
$query = ActivityLog::query()->with('user:id,uuid,name,email');
// 스코프 기반 권한 필터링 (self: 본인 로그만, role: 소유역할 로그, null: 전체)
PermissionHelper::applyPermissionScope($query, 'core.activities.read');
if (isset($filters['log_type'])) {
if (is_array($filters['log_type'])) {
$query->whereIn('log_type', $filters['log_type']);
} else {
$query->where('log_type', $filters['log_type']);
}
}
if (isset($filters['action'])) {
$query->action($filters['action']);
}
if (isset($filters['user_id'])) {
$query->byUser($filters['user_id']);
}
if (isset($filters['loggable_type'])) {
$query->where('loggable_type', $filters['loggable_type']);
}
if (isset($filters['created_by'])) {
$query->whereHas('user', function ($q) use ($filters) {
$q->where('uuid', $filters['created_by']);
});
}
if (isset($filters['search'])) {
$searchType = $filters['search_type'] ?? 'all';
$this->applyBilingualSearch($query, $filters['search'], $searchType);
}
if (isset($filters['date_from'])) {
$query->where('created_at', '>=', TimezoneHelper::fromSiteDateTime($filters['date_from']));
}
if (isset($filters['date_to'])) {
$query->where('created_at', '<=', TimezoneHelper::fromSiteDateTime($filters['date_to']));
}
$sortBy = $filters['sort_by'] ?? 'created_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
return $query->paginate($filters['per_page'] ?? 15);
}
/**
* 양방향(한글/영어) 검색을 적용합니다.
*
* action/description 필드는 영어 키를 저장하므로,
* 검색어가 번역된 라벨과 일치하는 원본 키도 함께 검색합니다.
*
* @param \Illuminate\Database\Eloquent\Builder $query 쿼리 빌더
* @param string $search 검색어
* @param string $searchType 검색 유형 (all, action, description, ip_address)
* @return void
*/
private function applyBilingualSearch($query, string $search, string $searchType): void
{
$query->where(function ($q) use ($search, $searchType) {
$searchLower = mb_strtolower($search);
if ($searchType === 'action' || $searchType === 'all') {
// 영어 원문 검색
$q->orWhere('action', 'LIKE', "%{$search}%");
// 번역된 라벨로 원본 action 값 역추적
$matchingActions = $this->findActionsByTranslatedLabel($searchLower);
if (! empty($matchingActions)) {
$q->orWhereIn('action', $matchingActions);
}
}
if ($searchType === 'description' || $searchType === 'all') {
// 영어 원문 검색
$q->orWhere('description_key', 'LIKE', "%{$search}%");
// 번역된 설명으로 원본 description_key 역추적
$matchingKeys = $this->findDescriptionKeysByTranslatedText($searchLower);
if (! empty($matchingKeys)) {
$q->orWhereIn('description_key', $matchingKeys);
}
}
if ($searchType === 'ip_address' || $searchType === 'all') {
$q->orWhere('ip_address', 'LIKE', "%{$search}%");
}
});
}
/**
* 번역된 액션 라벨로 원본 action 값을 역추적합니다.
*
* @param string $searchLower 소문자 검색어
* @return array<string> 일치하는 action 값 목록
*/
private function findActionsByTranslatedLabel(string $searchLower): array
{
$distinctActions = ActivityLog::distinct()->pluck('action')->toArray();
$matching = [];
foreach ($distinctActions as $action) {
// 전체 키 번역 (activity_log.action.user.create)
$fullKey = "activity_log.action.{$action}";
$translated = __($fullKey);
if ($translated !== $fullKey && str_contains(mb_strtolower($translated), $searchLower)) {
$matching[] = $action;
continue;
}
// 마지막 세그먼트 번역 (activity_log.action.create)
$lastSegment = last(explode('.', $action));
$segmentKey = "activity_log.action.{$lastSegment}";
$translated = __($segmentKey);
if ($translated !== $segmentKey && str_contains(mb_strtolower($translated), $searchLower)) {
$matching[] = $action;
}
}
return $matching;
}
/**
* 번역된 설명 텍스트로 원본 description_key를 역추적합니다.
*
* @param string $searchLower 소문자 검색어
* @return array<string> 일치하는 description_key 목록
*/
private function findDescriptionKeysByTranslatedText(string $searchLower): array
{
$distinctKeys = ActivityLog::distinct()->pluck('description_key')->filter()->toArray();
$matching = [];
foreach ($distinctKeys as $key) {
$translated = __($key);
if ($translated !== $key && str_contains(mb_strtolower($translated), $searchLower)) {
$matching[] = $key;
}
}
return $matching;
}
/**
* 활동 로그를 삭제합니다.
*
* @param int $id 삭제할 활동 로그 ID
* @return bool 삭제 성공 여부
*/
public function delete(int $id): bool
{
return ActivityLog::where('id', $id)->delete() > 0;
}
/**
* 여러 활동 로그를 일괄 삭제합니다.
*
* @param array<int> $ids 삭제할 활동 로그 ID 목록
* @return int 삭제된 건수
*/
public function deleteMany(array $ids): int
{
return ActivityLog::whereIn('id', $ids)->delete();
}
/**
* 최근 활동 로그를 스코프 권한 적용하여 조회합니다.
*
* @param string $permission 권한 식별자
* @param int $limit 조회할 활동 수
* @return Collection 활동 로그 컬렉션
*/
public function getRecent(string $permission, int $limit = 5): Collection
{
$query = ActivityLog::query()->with('user:id,uuid,name,email');
// 스코프 기반 권한 필터링 (self: 본인 활동만, role: 소유역할 활동, null: 전체)
PermissionHelper::applyPermissionScope($query, $permission);
return $query->latest()
->limit($limit)
->get();
}
}
+285
View File
@@ -0,0 +1,285 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\AttachmentRepositoryInterface;
use App\Models\Attachment;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
/**
* 첨부파일 Repository 구현체
*/
class AttachmentRepository implements AttachmentRepositoryInterface
{
/**
* ID로 첨부파일 조회
*
* @param int $id 첨부파일 ID
* @return Attachment|null 첨부파일 또는 null
*/
public function findById(int $id): ?Attachment
{
return Attachment::find($id);
}
/**
* 여러 ID로 첨부파일 조회 (order 정렬)
*
* @param array<int> $ids 첨부파일 ID 배열
* @return Collection<int, Attachment>
*/
public function findByIds(array $ids): Collection
{
if (empty($ids)) {
return collect();
}
return Attachment::whereIn('id', $ids)
->ordered()
->get();
}
/**
* 해시로 첨부파일 조회
*
* @param string $hash 첨부파일 해시
* @return Attachment|null 첨부파일 또는 null
*/
public function findByHash(string $hash): ?Attachment
{
return Attachment::where('hash', $hash)->first();
}
/**
* 첨부 대상별 첨부파일 조회
*
* @param string $type attachmentable_type
* @param int $id attachmentable_id
* @param string|null $collection 컬렉션 필터 (null이면 전체)
* @return Collection<int, Attachment>
*/
public function getByAttachmentable(string $type, int $id, ?string $collection = null): Collection
{
$query = Attachment::where('attachmentable_type', $type)
->where('attachmentable_id', $id)
->ordered();
if ($collection !== null) {
$query->collection($collection);
}
return $query->get();
}
/**
* 첨부파일 생성
*
* @param array<string, mixed> $data 생성 데이터
* @return Attachment 생성된 첨부파일
*/
public function create(array $data): Attachment
{
return Attachment::create($data);
}
/**
* 첨부파일 업데이트
*
* @param int $id 첨부파일 ID
* @param array<string, mixed> $data 업데이트 데이터
* @return Attachment 업데이트된 첨부파일
*/
public function update(int $id, array $data): Attachment
{
$attachment = Attachment::findOrFail($id);
$attachment->update($data);
return $attachment->fresh();
}
/**
* 첨부파일 삭제 (soft delete)
*
* @param int $id 첨부파일 ID
* @return bool 삭제 성공 여부
*/
public function delete(int $id): bool
{
$attachment = Attachment::find($id);
if (! $attachment) {
return false;
}
return $attachment->delete();
}
/**
* 첨부파일 영구 삭제
*
* @param int $id 첨부파일 ID
* @return bool 삭제 성공 여부
*/
public function forceDelete(int $id): bool
{
$attachment = Attachment::withTrashed()->find($id);
if (! $attachment) {
return false;
}
return $attachment->forceDelete();
}
/**
* 순서 변경
*
* @param array<int, array{id: int, order: int}> $orderData 순서 데이터
*/
public function reorder(array $orderData): void
{
DB::transaction(function () use ($orderData) {
foreach ($orderData as $item) {
Attachment::where('id', $item['id'])
->update(['order' => $item['order']]);
}
});
}
/**
* 특정 소스 식별자의 첨부파일 목록 조회
*
* @param string $identifier 소스 식별자
* @return Collection 첨부파일 컬렉션
*/
public function getBySourceIdentifier(string $identifier): Collection
{
return Attachment::where('source_identifier', $identifier)->get();
}
/**
* 특정 소스 식별자의 첨부파일 일괄 삭제
*
* @param string $identifier 소스 식별자
* @return int 삭제된 개수
*/
public function deleteBySourceIdentifier(string $identifier): int
{
return Attachment::where('source_identifier', $identifier)->delete();
}
/**
* 컬렉션 내 최대 order 값 조회
*
* @param string $type attachmentable_type
* @param int $id attachmentable_id
* @param string $collection 컬렉션명
* @return int 최대 order 값
*/
public function getMaxOrder(string $type, int $id, string $collection): int
{
return Attachment::where('attachmentable_type', $type)
->where('attachmentable_id', $id)
->where('collection', $collection)
->max('order') ?? 0;
}
/**
* 컬렉션명으로만 최대 order 값 조회 (attachmentable 없는 경우)
*
* @param string $collection 컬렉션명
* @return int 최대 order 값
*/
public function getMaxOrderByCollection(string $collection): int
{
return Attachment::where('collection', $collection)
->whereNull('attachmentable_type')
->whereNull('attachmentable_id')
->max('order') ?? 0;
}
/**
* 컬렉션명으로 첨부파일 조회 (attachmentable 없는 경우)
*
* @param string $collection 컬렉션명
* @return Collection<int, Attachment>
*/
public function getByCollection(string $collection): Collection
{
return Attachment::where('collection', $collection)
->whereNull('attachmentable_type')
->whereNull('attachmentable_id')
->ordered()
->get();
}
/**
* 미연결 첨부파일을 특정 엔티티에 연결합니다.
* 기존 연결된 파일들의 order 뒤에 순차적으로 배치됩니다.
*
* @param string $collection 컬렉션명
* @param string $attachmentableType 연결할 모델 클래스명
* @param int $attachmentableId 연결할 모델 ID
* @return int 연결된 첨부파일 수
*/
public function linkUnattachedFiles(string $collection, string $attachmentableType, int $attachmentableId): int
{
// 기존 연결된 파일들의 최대 order 조회
$maxOrder = $this->getMaxOrder($attachmentableType, $attachmentableId, $collection);
// 미연결 파일들을 order 순으로 조회
$unattachedFiles = Attachment::where('collection', $collection)
->whereNull('attachmentable_type')
->whereNull('attachmentable_id')
->orderBy('order')
->orderBy('id')
->get();
if ($unattachedFiles->isEmpty()) {
return 0;
}
// 각 파일에 대해 연결 및 order 재설정
$count = 0;
foreach ($unattachedFiles as $file) {
$maxOrder++;
$file->update([
'attachmentable_type' => $attachmentableType,
'attachmentable_id' => $attachmentableId,
'order' => $maxOrder,
]);
$count++;
}
return $count;
}
/**
* 특정 엔티티의 첨부파일 순서를 재정렬합니다.
* 삭제 등으로 중간에 빈 순서가 생긴 경우 1부터 연속된 순서로 재정렬합니다.
*
* @param string $attachmentableType 첨부 대상 타입
* @param int $attachmentableId 첨부 대상 ID
* @param string $collection 컬렉션명
*/
public function reorderAfterDelete(string $attachmentableType, int $attachmentableId, string $collection): void
{
$attachments = Attachment::where('attachmentable_type', $attachmentableType)
->where('attachmentable_id', $attachmentableId)
->where('collection', $collection)
->orderBy('order')
->orderBy('id')
->get();
DB::transaction(function () use ($attachments) {
$order = 1;
foreach ($attachments as $attachment) {
if ($attachment->order !== $order) {
$attachment->update(['order' => $order]);
}
$order++;
}
});
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Repositories\Concerns;
use Illuminate\Database\Eloquent\Builder;
/**
* 다중 검색 필터 기능을 제공하는 Trait
*
* Repository에서 다중 검색 조건을 처리할 때 사용합니다.
* 지원 연산자: like(기본), eq, starts_with, ends_with
*/
trait HasMultipleSearchFilters
{
/**
* 다중 검색 조건을 쿼리에 적용합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param array $searchFilters 검색 조건 배열 [['field' => 'name', 'value' => '홍길동', 'operator' => 'like'], ...]
* @param array $allowedFields 허용된 검색 필드 목록
*/
protected function applyMultipleSearchFilters(Builder $query, array $searchFilters, array $allowedFields): void
{
if (empty($searchFilters)) {
return;
}
$query->where(function ($q) use ($searchFilters, $allowedFields) {
foreach ($searchFilters as $filter) {
$this->applySearchFilter($q, $filter, $allowedFields);
}
});
}
/**
* 개별 검색 필터를 쿼리에 적용합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param array $filter 검색 필터 ['field' => string, 'value' => string, 'operator' => string]
* @param array $allowedFields 허용된 검색 필드 목록
*/
protected function applySearchFilter(Builder $query, array $filter, array $allowedFields): void
{
$field = $filter['field'] ?? null;
$value = $filter['value'] ?? null;
$operator = $filter['operator'] ?? 'like';
// 필드와 값이 유효한지 확인
if (! $field || ! $value) {
return;
}
// 'all' 필드인 경우: 모든 허용 필드를 OR 조건으로 검색
if ($field === 'all') {
$this->applyOrSearchAcrossFields($query, $value, $allowedFields);
return;
}
// 특정 필드 검색: 허용된 필드인지 확인
if (! in_array($field, $allowedFields)) {
return;
}
// 연산자에 따른 검색 조건 적용 (AND 조건으로 연결)
match ($operator) {
'eq' => $query->where($field, '=', $value),
'starts_with' => $query->where($field, 'like', "{$value}%"),
'ends_with' => $query->where($field, 'like', "%{$value}"),
default => $query->where($field, 'like', "%{$value}%"),
};
}
/**
* 단일 검색어로 여러 필드를 OR 조건으로 검색합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param string $searchTerm 검색어
* @param array $searchFields 검색할 필드 목록
*/
protected function applyOrSearchAcrossFields(Builder $query, string $searchTerm, array $searchFields): void
{
if (empty($searchTerm) || empty($searchFields)) {
return;
}
$query->where(function ($q) use ($searchTerm, $searchFields) {
foreach ($searchFields as $index => $field) {
if ($index === 0) {
$q->where($field, 'like', "%{$searchTerm}%");
} else {
$q->orWhere($field, 'like', "%{$searchTerm}%");
}
}
});
}
}
+500
View File
@@ -0,0 +1,500 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\ConfigRepositoryInterface;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
/**
* JSON 파일 기반 설정 저장소
*
* 설정을 카테고리별 JSON 파일로 관리합니다.
*/
class JsonConfigRepository implements ConfigRepositoryInterface
{
/**
* Storage disk 이름
*/
private const STORAGE_DISK = 'settings';
/**
* 백업 파일 저장 디렉토리 (disk 기준)
*/
private const BACKUP_DIR = 'backups';
/**
* 기본 설정 파일 경로
*/
private const DEFAULTS_FILE = 'settings/defaults.json';
/**
* 기본 설정 캐시
*
* @var array<string, mixed>|null
*/
private ?array $defaultsCache = null;
/**
* 메모리 캐시
*
* @var array<string, array<string, mixed>>|null
*/
private ?array $cache = null;
/**
* 모든 카테고리의 설정을 조회합니다.
*
* @return array<string, array<string, mixed>>
*/
public function all(): array
{
if ($this->cache !== null) {
return $this->cache;
}
$settings = [];
foreach ($this->getCategories() as $category) {
$settings[$category] = $this->getCategory($category);
}
$this->cache = $settings;
return $settings;
}
/**
* 특정 카테고리의 설정을 조회합니다.
*
* @return array<string, mixed>
*/
public function getCategory(string $category): array
{
if (! $this->categoryExists($category)) {
return $this->getDefaultsForCategory($category);
}
$path = $this->getCategoryPath($category);
if (! Storage::disk(self::STORAGE_DISK)->exists($path)) {
return $this->getDefaultsForCategory($category);
}
try {
$content = Storage::disk(self::STORAGE_DISK)->get($path);
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Log::warning("설정 파일 JSON 파싱 실패: {$category}", [
'error' => json_last_error_msg(),
]);
return $this->getDefaultsForCategory($category);
}
// _meta 키 제거하고 반환
unset($data['_meta']);
// 기본값과 병합 (새 설정 키 자동 추가)
$defaults = $this->getDefaultsForCategory($category);
return array_merge($defaults, $data);
} catch (\Exception $e) {
Log::error("설정 파일 읽기 실패: {$category}", [
'error' => $e->getMessage(),
]);
return $this->getDefaultsForCategory($category);
}
}
/**
* 도트 노테이션으로 특정 설정값을 조회합니다.
*
* @param string $key 예: 'mail.host', 'general.site_name'
*/
public function get(string $key, mixed $default = null): mixed
{
$parts = explode('.', $key, 2);
if (count($parts) === 1) {
// 카테고리만 지정된 경우
return $this->getCategory($key);
}
[$category, $settingKey] = $parts;
$categoryData = $this->getCategory($category);
return Arr::get($categoryData, $settingKey, $default);
}
/**
* 도트 노테이션으로 특정 설정값을 저장합니다.
*/
public function set(string $key, mixed $value): bool
{
$parts = explode('.', $key, 2);
if (count($parts) !== 2) {
return false;
}
[$category, $settingKey] = $parts;
$categoryData = $this->getCategory($category);
Arr::set($categoryData, $settingKey, $value);
return $this->saveCategory($category, $categoryData);
}
/**
* 여러 설정을 일괄 저장합니다.
*
* @param array<string, mixed> $settings
*/
public function setMany(array $settings): bool
{
$grouped = $this->groupByCategory($settings);
foreach ($grouped as $category => $categorySettings) {
$existing = $this->getCategory($category);
$merged = array_merge($existing, $categorySettings);
if (! $this->saveCategory($category, $merged)) {
return false;
}
}
return true;
}
/**
* 특정 카테고리의 설정을 저장합니다.
*
* @param array<string, mixed> $settings
*/
public function saveCategory(string $category, array $settings): bool
{
if (! $this->categoryExists($category)) {
return false;
}
$this->ensureDirectoryExists();
// 메타 정보 추가
$data = [
'_meta' => [
'version' => '1.0.0',
'updated_at' => now()->toIso8601String(),
],
...$settings,
];
$path = $this->getCategoryPath($category);
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
try {
// 파일 잠금으로 동시 쓰기 방지
$fullPath = Storage::disk(self::STORAGE_DISK)->path($path);
$handle = fopen($fullPath, 'c');
if ($handle === false) {
return false;
}
if (flock($handle, LOCK_EX)) {
ftruncate($handle, 0);
fwrite($handle, $json);
fflush($handle);
flock($handle, LOCK_UN);
}
fclose($handle);
// 캐시 무효화
$this->cache = null;
return true;
} catch (\Exception $e) {
Log::error("설정 파일 저장 실패: {$category}", [
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* 설정 키 존재 여부를 확인합니다.
*/
public function has(string $key): bool
{
return $this->get($key) !== null;
}
/**
* 특정 설정을 삭제합니다.
*/
public function delete(string $key): bool
{
$parts = explode('.', $key, 2);
if (count($parts) !== 2) {
return false;
}
[$category, $settingKey] = $parts;
$categoryData = $this->getCategory($category);
Arr::forget($categoryData, $settingKey);
return $this->saveCategory($category, $categoryData);
}
/**
* 사용 가능한 카테고리 목록을 반환합니다.
*
* config/settings/defaults.json의 _meta.categories에서 조회합니다.
*
* @return array<string>
*/
public function getCategories(): array
{
if ($this->defaultsCache === null) {
$this->loadDefaultsFile();
}
return $this->defaultsCache['_meta']['categories'] ?? [];
}
/**
* 카테고리 존재 여부를 확인합니다.
*/
public function categoryExists(string $category): bool
{
return in_array($category, $this->getCategories(), true);
}
/**
* 설정 파일을 초기화합니다.
*
* @param array<string, array<string, mixed>> $settings
*/
public function initialize(array $settings = []): bool
{
$this->ensureDirectoryExists();
$defaults = $this->getDefaults();
$merged = array_replace_recursive($defaults, $settings);
foreach ($merged as $category => $categorySettings) {
if (! $this->saveCategory($category, $categorySettings)) {
return false;
}
}
return true;
}
/**
* 설정을 백업합니다.
*
* @return string 백업 파일 경로
*/
public function backup(): string
{
$this->ensureBackupDirectoryExists();
$timestamp = now()->format('Y-m-d_His');
$backupName = "backup_{$timestamp}.zip";
$backupPath = self::BACKUP_DIR.'/'.$backupName;
$zip = new \ZipArchive;
$fullBackupPath = Storage::disk(self::STORAGE_DISK)->path($backupPath);
if ($zip->open($fullBackupPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
throw new \RuntimeException(__('exceptions.settings.backup_creation_failed'));
}
foreach ($this->getCategories() as $category) {
$categoryPath = $this->getCategoryPath($category);
$fullCategoryPath = Storage::disk(self::STORAGE_DISK)->path($categoryPath);
if (file_exists($fullCategoryPath)) {
$zip->addFile($fullCategoryPath, "{$category}.json");
}
}
$zip->close();
return $backupPath;
}
/**
* 백업에서 설정을 복원합니다.
*/
public function restore(string $backupPath): bool
{
$fullBackupPath = Storage::disk(self::STORAGE_DISK)->path($backupPath);
if (! file_exists($fullBackupPath)) {
return false;
}
$zip = new \ZipArchive;
if ($zip->open($fullBackupPath) !== true) {
return false;
}
$this->ensureDirectoryExists();
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$category = pathinfo($filename, PATHINFO_FILENAME);
if ($this->categoryExists($category)) {
$content = $zip->getFromIndex($i);
$categoryPath = $this->getCategoryPath($category);
Storage::disk(self::STORAGE_DISK)->put($categoryPath, $content);
}
}
$zip->close();
$this->cache = null;
return true;
}
/**
* 기본 설정값을 반환합니다.
*
* config/settings/defaults.json 파일에서 기본값을 로드합니다.
*
* @return array<string, array<string, mixed>>
*/
public function getDefaults(): array
{
if ($this->defaultsCache !== null) {
return $this->defaultsCache['defaults'] ?? [];
}
$this->loadDefaultsFile();
return $this->defaultsCache['defaults'] ?? [];
}
/**
* 프론트엔드 스키마를 반환합니다.
*
* @return array<string, array<string, mixed>>
*/
public function getFrontendSchema(): array
{
if ($this->defaultsCache === null) {
$this->loadDefaultsFile();
}
return $this->defaultsCache['frontend_schema'] ?? [];
}
/**
* 기본 설정 파일을 로드합니다.
*/
private function loadDefaultsFile(): void
{
$path = config_path(self::DEFAULTS_FILE);
if (! file_exists($path)) {
Log::error('설정 기본값 파일을 찾을 수 없습니다. settings:install 명령을 실행하세요.', ['path' => $path]);
$this->defaultsCache = ['_meta' => ['categories' => []], 'defaults' => [], 'frontend_schema' => []];
return;
}
try {
$content = file_get_contents($path);
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Log::error('설정 기본값 파일 JSON 파싱 실패', [
'error' => json_last_error_msg(),
]);
$this->defaultsCache = ['_meta' => ['categories' => []], 'defaults' => [], 'frontend_schema' => []];
return;
}
$this->defaultsCache = $data;
} catch (\Exception $e) {
Log::error('설정 기본값 파일 로드 실패', ['error' => $e->getMessage()]);
$this->defaultsCache = ['_meta' => ['categories' => []], 'defaults' => [], 'frontend_schema' => []];
}
}
/**
* 특정 카테고리의 기본값을 반환합니다.
*
* @return array<string, mixed>
*/
private function getDefaultsForCategory(string $category): array
{
$defaults = $this->getDefaults();
return $defaults[$category] ?? [];
}
/**
* 카테고리 파일 경로를 반환합니다.
*/
private function getCategoryPath(string $category): string
{
return "{$category}.json";
}
/**
* 설정 디렉토리가 존재하는지 확인하고 없으면 생성합니다.
*/
private function ensureDirectoryExists(): void
{
$disk = Storage::disk(self::STORAGE_DISK);
if (! $disk->exists('.')) {
$disk->makeDirectory('.');
}
}
/**
* 백업 디렉토리가 존재하는지 확인하고 없으면 생성합니다.
*/
private function ensureBackupDirectoryExists(): void
{
$disk = Storage::disk(self::STORAGE_DISK);
if (! $disk->exists(self::BACKUP_DIR)) {
$disk->makeDirectory(self::BACKUP_DIR);
}
}
/**
* 설정을 카테고리별로 그룹화합니다.
*
* @param array<string, mixed> $settings
* @return array<string, array<string, mixed>>
*/
private function groupByCategory(array $settings): array
{
$grouped = [];
foreach ($settings as $key => $value) {
$parts = explode('.', $key, 2);
if (count($parts) === 2) {
[$category, $settingKey] = $parts;
$grouped[$category][$settingKey] = $value;
}
}
return $grouped;
}
}
@@ -0,0 +1,288 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\LayoutExtensionRepositoryInterface;
use App\Enums\LayoutExtensionType;
use App\Enums\LayoutSourceType;
use App\Models\LayoutExtension;
use Illuminate\Support\Collection;
/**
* 레이아웃 확장 리포지토리 구현
*/
class LayoutExtensionRepository implements LayoutExtensionRepositoryInterface
{
/**
* 특정 확장점에 등록된 확장 목록 조회
*
* @param int $templateId 템플릿 ID
* @param string $extensionPointName 확장점 이름
* @return Collection<int, LayoutExtension>
*/
public function getByExtensionPoint(int $templateId, string $extensionPointName): Collection
{
return LayoutExtension::query()
->where('template_id', $templateId)
->extensionPoints()
->where('target_name', $extensionPointName)
->active()
->ordered()
->get();
}
/**
* 특정 레이아웃을 타겟으로 하는 오버레이 목록 조회
*
* @param int $templateId 템플릿 ID
* @param string $layoutName 레이아웃 이름
* @return Collection<int, LayoutExtension>
*/
public function getOverlaysByLayout(int $templateId, string $layoutName): Collection
{
return LayoutExtension::query()
->where('template_id', $templateId)
->overlays()
->where('target_name', $layoutName)
->active()
->ordered()
->get();
}
/**
* 확장 등록
*
* @param array $data 확장 데이터
* @return LayoutExtension
*/
public function create(array $data): LayoutExtension
{
return LayoutExtension::create($data);
}
/**
* 확장 등록 또는 업데이트 (upsert)
*
* 동일한 조건의 확장이 존재하면 업데이트하고, 없으면 생성합니다.
* soft delete된 레코드도 복원하여 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 값
* @return LayoutExtension
*/
public function updateOrCreate(array $attributes, array $values): LayoutExtension
{
// soft delete된 레코드도 포함하여 조회
$existing = LayoutExtension::withTrashed()
->where($attributes)
->first();
if ($existing) {
// 기존 레코드가 있으면 복원 후 업데이트
if ($existing->trashed()) {
$existing->restore();
}
$existing->update($values);
return $existing->fresh();
}
// 없으면 새로 생성
return LayoutExtension::create(array_merge($attributes, $values));
}
/**
* 출처별 확장 삭제 (soft delete)
*
* @param LayoutSourceType $sourceType 출처 타입
* @param string $identifier 출처 식별자
* @return int 삭제된 레코드 수
*/
public function softDeleteBySource(LayoutSourceType $sourceType, string $identifier): int
{
return LayoutExtension::query()
->bySource($sourceType, $identifier)
->delete();
}
/**
* 출처별 확장 복원
*
* @param LayoutSourceType $sourceType 출처 타입
* @param string $identifier 출처 식별자
* @return int 복원된 레코드 수
*/
public function restoreBySource(LayoutSourceType $sourceType, string $identifier): int
{
return LayoutExtension::query()
->withTrashed()
->bySource($sourceType, $identifier)
->restore();
}
/**
* 출처별 확장 영구 삭제
*
* @param LayoutSourceType $sourceType 출처 타입
* @param string $identifier 출처 식별자
* @return int 삭제된 레코드 수
*/
public function forceDeleteBySource(LayoutSourceType $sourceType, string $identifier): int
{
return LayoutExtension::query()
->withTrashed()
->bySource($sourceType, $identifier)
->forceDelete();
}
/**
* 템플릿 오버라이드 확인 (Extension Point용)
*
* @param int $templateId 템플릿 ID
* @param string $extensionPointName 확장점 이름
* @param string $moduleIdentifier 모듈/플러그인 식별자
* @return LayoutExtension|null
*/
public function findTemplateOverrideForExtensionPoint(
int $templateId,
string $extensionPointName,
string $moduleIdentifier
): ?LayoutExtension {
return LayoutExtension::query()
->where('template_id', $templateId)
->extensionPoints()
->where('target_name', $extensionPointName)
->templateOverrides()
->overridingTarget($moduleIdentifier)
->active()
->first();
}
/**
* 템플릿 오버라이드 확인 (Overlay용)
*
* @param int $templateId 템플릿 ID
* @param string $layoutName 레이아웃 이름
* @param string $moduleIdentifier 모듈/플러그인 식별자
* @return LayoutExtension|null
*/
public function findTemplateOverrideForOverlay(
int $templateId,
string $layoutName,
string $moduleIdentifier
): ?LayoutExtension {
return LayoutExtension::query()
->where('template_id', $templateId)
->overlays()
->where('target_name', $layoutName)
->templateOverrides()
->overridingTarget($moduleIdentifier)
->active()
->first();
}
/**
* 오버라이드를 고려한 Extension Point 조회
*
* @param int $templateId 템플릿 ID
* @param string $extensionPointName 확장점 이름
* @return Collection<int, LayoutExtension>
*/
public function getResolvedExtensionPoints(int $templateId, string $extensionPointName): Collection
{
// 1. 모든 확장 조회 (모듈/플러그인/템플릿 오버라이드 포함)
$allExtensions = LayoutExtension::query()
->where('template_id', $templateId)
->extensionPoints()
->where('target_name', $extensionPointName)
->active()
->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();
}
/**
* 오버라이드를 고려한 Overlay 조회
*
* @param int $templateId 템플릿 ID
* @param string $layoutName 레이아웃 이름
* @return Collection<int, LayoutExtension>
*/
public function getResolvedOverlays(int $templateId, string $layoutName): Collection
{
// 1. 모든 오버레이 조회
$allOverlays = LayoutExtension::query()
->where('template_id', $templateId)
->overlays()
->where('target_name', $layoutName)
->active()
->ordered()
->get();
// 2. 템플릿 오버라이드가 있는 모듈 식별자 추출
$overriddenModules = $allOverlays
->where('source_type', LayoutSourceType::Template)
->pluck('override_target')
->filter()
->unique()
->toArray();
// 3. 오버라이드된 모듈/플러그인 확장은 제외하고 반환
return $allOverlays->filter(function ($overlay) use ($overriddenModules) {
// 템플릿 오버라이드는 항상 포함
if ($overlay->source_type === LayoutSourceType::Template) {
return true;
}
// 오버라이드된 모듈/플러그인 확장은 제외
return ! in_array($overlay->source_identifier, $overriddenModules, true);
})->values();
}
/**
* 특정 템플릿의 모든 확장 조회
*
* @param int $templateId 템플릿 ID
* @return Collection<int, LayoutExtension>
*/
public function getByTemplateId(int $templateId): Collection
{
return LayoutExtension::query()
->where('template_id', $templateId)
->active()
->ordered()
->get();
}
/**
* 특정 템플릿의 모든 확장 삭제
*
* @param int $templateId 템플릿 ID
* @return int 삭제된 레코드 수
*/
public function deleteByTemplateId(int $templateId): int
{
return LayoutExtension::query()
->withTrashed()
->where('template_id', $templateId)
->forceDelete();
}
}
@@ -0,0 +1,73 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\LayoutPreviewRepositoryInterface;
use App\Models\TemplateLayoutPreview;
/**
* 레이아웃 미리보기 리포지토리 구현체
*/
class LayoutPreviewRepository implements LayoutPreviewRepositoryInterface
{
/**
* 미리보기를 생성합니다.
*
* @param array $data 생성 데이터
* @return TemplateLayoutPreview 생성된 미리보기 모델
*/
public function create(array $data): TemplateLayoutPreview
{
return TemplateLayoutPreview::create($data);
}
/**
* 토큰으로 미리보기를 조회합니다.
*
* @param string $token 미리보기 토큰
* @return TemplateLayoutPreview|null 찾은 미리보기 모델 또는 null
*/
public function findByToken(string $token): ?TemplateLayoutPreview
{
return TemplateLayoutPreview::where('token', $token)
->notExpired()
->first();
}
/**
* 토큰으로 미리보기를 삭제합니다.
*
* @param string $token 미리보기 토큰
* @return bool 삭제 성공 여부
*/
public function deleteByToken(string $token): bool
{
return TemplateLayoutPreview::where('token', $token)->delete() > 0;
}
/**
* 만료된 미리보기를 일괄 삭제합니다.
*
* @return int 삭제된 행 수
*/
public function deleteExpired(): int
{
return TemplateLayoutPreview::where('expires_at', '<=', now())->delete();
}
/**
* 특정 관리자의 특정 레이아웃 미리보기를 삭제합니다.
*
* @param int $templateId 템플릿 ID
* @param string $layoutName 레이아웃 이름
* @param int $adminId 관리자 ID
* @return int 삭제된 행 수
*/
public function deleteByLayoutAndAdmin(int $templateId, string $layoutName, int $adminId): int
{
return TemplateLayoutPreview::where('template_id', $templateId)
->where('layout_name', $layoutName)
->where('admin_id', $adminId)
->delete();
}
}
+462
View File
@@ -0,0 +1,462 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\LayoutRepositoryInterface;
use App\Enums\LayoutSourceType;
use App\Models\TemplateLayout;
use App\Models\TemplateLayoutVersion;
use Illuminate\Database\Eloquent\Collection;
class LayoutRepository implements LayoutRepositoryInterface
{
/**
* 특정 템플릿의 모든 레이아웃 조회
*/
public function getByTemplateId(int $templateId): Collection
{
return TemplateLayout::where('template_id', $templateId)
->orderBy('name')
->get();
}
/**
* 특정 레이아웃 조회 (템플릿 ID와 이름으로)
*/
public function findByName(int $templateId, string $name): ?TemplateLayout
{
return TemplateLayout::where('template_id', $templateId)
->where('name', $name)
->first();
}
/**
* ID로 레이아웃 조회
*/
public function findById(int $id): ?TemplateLayout
{
return TemplateLayout::find($id);
}
/**
* 레이아웃이 존재하는지 확인
*/
public function exists(int $templateId, string $name): bool
{
return TemplateLayout::where('template_id', $templateId)
->where('name', $name)
->exists();
}
/**
* extends를 가진 자식 레이아웃 조회
*/
public function getChildrenByExtends(int $templateId, string $extendsName): Collection
{
return TemplateLayout::where('template_id', $templateId)
->where('extends', $extendsName)
->get();
}
/**
* 레이아웃 업데이트
*
* 전체 content를 교체합니다. FormRequest에서 구조 검증이 완료된 데이터를 받습니다.
*
* @param int $id 레이아웃 ID
* @param array $data 업데이트할 content 데이터 (전체 레이아웃 JSON)
* @return TemplateLayout 업데이트된 레이아웃 모델
*/
public function update(int $id, array $data): TemplateLayout
{
$layout = TemplateLayout::findOrFail($id);
// 전체 content 교체 (FormRequest에서 검증 완료)
$layout->content = $data;
// extends 필드 동기화 (캐시 무효화 및 자식 레이아웃 탐색용)
$layout->extends = $data['extends'] ?? null;
$layout->save();
return $layout->fresh();
}
/**
* 특정 레이아웃의 모든 버전 조회
*/
public function getVersionsByLayoutId(int $layoutId): Collection
{
return TemplateLayoutVersion::where('layout_id', $layoutId)
->latest()
->get();
}
/**
* 특정 버전 조회
*/
public function findVersionByNumber(int $layoutId, int $version): ?TemplateLayoutVersion
{
return TemplateLayoutVersion::where('layout_id', $layoutId)
->where('version', $version)
->first();
}
/**
* 템플릿 오버라이드 레이아웃 찾기
*
* 템플릿에서 제공하는 오버라이드 레이아웃을 검색합니다.
* source_type = 'template'이고 source_identifier가 있는 레이아웃
*/
public function findTemplateOverride(int $templateId, string $layoutName): ?TemplateLayout
{
return TemplateLayout::where('template_id', $templateId)
->where('name', $layoutName)
->fromTemplates()
->whereNotNull('source_identifier')
->first();
}
/**
* 모듈 기본 레이아웃 찾기
*
* 모듈에서 제공하는 기본 레이아웃을 검색합니다.
* source_type = 'module'인 레이아웃
*/
public function findModuleLayout(int $templateId, string $layoutName): ?TemplateLayout
{
return TemplateLayout::where('template_id', $templateId)
->where('name', $layoutName)
->fromModules()
->first();
}
/**
* 특정 템플릿의 모든 레이아웃 이름 조회
*
* @return \Illuminate\Support\Collection<int, string>
*/
public function getLayoutNamesByTemplateId(int $templateId): \Illuminate\Support\Collection
{
return TemplateLayout::where('template_id', $templateId)
->pluck('name')
->unique();
}
/**
* 특정 모듈의 모든 레이아웃 조회
*/
public function getLayoutsByModule(string $moduleIdentifier): Collection
{
return TemplateLayout::fromModules()
->bySourceIdentifier($moduleIdentifier)
->get(['template_id', 'name']);
}
/**
* 특정 템플릿에서 오버라이드된 모든 레이아웃 조회
*/
public function getOverriddenLayouts(int $templateId): Collection
{
return TemplateLayout::where('template_id', $templateId)
->fromTemplates()
->whereNotNull('source_identifier')
->get();
}
/**
* 특정 모듈의 레이아웃 중 템플릿에서 오버라이드된 것들 조회
*/
public function getModuleLayoutOverrides(string $moduleIdentifier, int $templateId): Collection
{
// 모듈의 레이아웃 이름 목록 조회
$moduleLayoutNames = TemplateLayout::fromModules()
->bySourceIdentifier($moduleIdentifier)
->where('template_id', $templateId)
->pluck('name');
// 해당 이름들에 대한 오버라이드 조회
return TemplateLayout::where('template_id', $templateId)
->fromTemplates()
->whereNotNull('source_identifier')
->whereIn('name', $moduleLayoutNames)
->get();
}
/**
* 우선순위에 따라 레이아웃 조회 (오버라이드 우선)
*
* 우선순위:
* 1. 템플릿 오버라이드 (source_type = 'template', source_identifier 있음)
* 2. 모듈 기본 레이아웃 (source_type = 'module')
* 3. 일반 템플릿 레이아웃 (source_type = 'template', source_identifier 없음)
*/
public function findByNameWithOverride(int $templateId, string $name): ?TemplateLayout
{
// 1. 템플릿 오버라이드 확인 (최우선)
$override = $this->findTemplateOverride($templateId, $name);
if ($override) {
return $override;
}
// 2. 모듈 기본 레이아웃 확인
$moduleLayout = $this->findModuleLayout($templateId, $name);
if ($moduleLayout) {
return $moduleLayout;
}
// 3. 일반 템플릿 레이아웃 (폴백)
return $this->findByName($templateId, $name);
}
/**
* 특정 템플릿의 모든 모듈 레이아웃 조회
*
* @param int $templateId 템플릿 ID
* @param string|null $moduleIdentifier 특정 모듈만 조회 (선택)
*/
public function findModuleLayouts(int $templateId, ?string $moduleIdentifier = null): Collection
{
$query = TemplateLayout::where('template_id', $templateId)
->fromModules();
if ($moduleIdentifier !== null) {
$query->bySourceIdentifier($moduleIdentifier);
}
return $query->orderBy('name')->get();
}
/**
* 특정 템플릿의 모든 레이아웃 조회 (source_type 필터 옵션 포함)
*
* @param int $templateId 템플릿 ID
* @param string|null $sourceType 소스 타입 필터 ('template', 'module', 'plugin')
* @param string|null $sourceIdentifier 소스 식별자 필터 (null이면 source_identifier가 null인 레코드만 조회)
* @param bool $nullIdentifierOnly true이면 source_identifier가 null인 레코드만 조회 (sourceIdentifier 파라미터가 null일 때만 적용)
*/
public function getByTemplateIdWithFilter(
int $templateId,
?string $sourceType = null,
?string $sourceIdentifier = null,
bool $nullIdentifierOnly = true
): Collection {
$query = TemplateLayout::where('template_id', $templateId);
if ($sourceType !== null) {
$query->where('source_type', $sourceType);
}
if ($sourceIdentifier !== null) {
$query->bySourceIdentifier($sourceIdentifier);
} elseif ($nullIdentifierOnly) {
// sourceIdentifier가 null이고 nullIdentifierOnly가 true이면
// source_identifier가 null인 레코드만 조회
$query->whereNull('source_identifier');
}
return $query->orderBy('name')->get();
}
/**
* 특정 플러그인의 모든 레이아웃 조회
*/
public function getLayoutsByPlugin(string $pluginIdentifier): Collection
{
return TemplateLayout::fromPlugins()
->bySourceIdentifier($pluginIdentifier)
->get(['template_id', 'name']);
}
/**
* 특정 템플릿의 모든 플러그인 레이아웃 조회
*
* @param int $templateId 템플릿 ID
* @param string|null $pluginIdentifier 특정 플러그인만 조회 (선택)
*/
public function findPluginLayouts(int $templateId, ?string $pluginIdentifier = null): Collection
{
$query = TemplateLayout::where('template_id', $templateId)
->fromPlugins();
if ($pluginIdentifier !== null) {
$query->bySourceIdentifier($pluginIdentifier);
}
return $query->orderBy('name')->get();
}
/**
* 레이아웃을 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return TemplateLayout 생성 또는 업데이트된 레이아웃 모델
*/
public function updateOrCreate(array $attributes, array $values): TemplateLayout
{
return TemplateLayout::updateOrCreate($attributes, $values);
}
/**
* 특정 모듈의 soft delete된 레이아웃을 조회합니다.
*
* @param string $moduleIdentifier 모듈 식별자
* @return Collection soft delete된 레이아웃 컬렉션
*/
public function getTrashedByModule(string $moduleIdentifier): Collection
{
return TemplateLayout::onlyTrashed()
->where('source_type', LayoutSourceType::Module)
->where('source_identifier', $moduleIdentifier)
->get();
}
/**
* 특정 모듈의 레이아웃을 soft delete합니다.
*
* @param string $moduleIdentifier 모듈 식별자
* @return int soft delete된 레코드 수
*/
public function softDeleteByModule(string $moduleIdentifier): int
{
$layouts = TemplateLayout::where('source_type', LayoutSourceType::Module)
->where('source_identifier', $moduleIdentifier)
->get();
$deletedCount = 0;
foreach ($layouts as $layout) {
$layout->delete();
$deletedCount++;
}
return $deletedCount;
}
/**
* 특정 모듈의 레이아웃을 영구 삭제합니다 (soft delete 포함).
*
* @param string $moduleIdentifier 모듈 식별자
* @return int 삭제된 레코드 수
*/
public function forceDeleteByModule(string $moduleIdentifier): int
{
return TemplateLayout::withTrashed()
->where('source_type', LayoutSourceType::Module)
->where('source_identifier', $moduleIdentifier)
->forceDelete();
}
/**
* 특정 모듈의 레이아웃 개수를 반환합니다 (soft delete 포함).
*
* @param string $moduleIdentifier 모듈 식별자
* @return int 레이아웃 개수
*/
public function countByModule(string $moduleIdentifier): int
{
return TemplateLayout::withTrashed()
->where('source_type', LayoutSourceType::Module)
->where('source_identifier', $moduleIdentifier)
->count();
}
/**
* 특정 모듈의 soft delete된 레이아웃을 복원합니다.
*
* @param string $moduleIdentifier 모듈 식별자
* @return int 복원된 레코드 수
*/
public function restoreByModule(string $moduleIdentifier): int
{
$layouts = $this->getTrashedByModule($moduleIdentifier);
$restoredCount = 0;
foreach ($layouts as $layout) {
$layout->restore();
$restoredCount++;
}
return $restoredCount;
}
/**
* 특정 모듈의 레이아웃들을 조회합니다 (soft delete 제외).
*
* @param string $moduleIdentifier 모듈 식별자
* @return Collection 레이아웃 컬렉션
*/
public function getByModuleIdentifier(string $moduleIdentifier): Collection
{
return TemplateLayout::where('source_type', LayoutSourceType::Module)
->where('source_identifier', $moduleIdentifier)
->get();
}
/**
* 특정 확장(모듈 또는 플러그인)의 레이아웃들을 소스 타입과 함께 조회합니다.
*
* @param string $sourceIdentifier 확장 식별자
* @param LayoutSourceType $sourceType 소스 타입 (Module 또는 Plugin)
* @return Collection 레이아웃 컬렉션
*/
public function getBySourceIdentifier(string $sourceIdentifier, LayoutSourceType $sourceType): Collection
{
return TemplateLayout::where('source_type', $sourceType)
->where('source_identifier', $sourceIdentifier)
->get();
}
/**
* 특정 템플릿의 모든 레이아웃을 삭제합니다.
* soft deleted된 레코드를 포함하여 영구 삭제합니다.
*
* @param int $templateId 템플릿 ID
* @return int 삭제된 레코드 수
*/
public function deleteByTemplateId(int $templateId): int
{
return TemplateLayout::withTrashed()
->where('template_id', $templateId)
->forceDelete();
}
/**
* 특정 템플릿의 레이아웃 개수를 조회합니다.
*
* @param int $templateId 템플릿 ID
* @return int 레이아웃 개수
*/
public function countByTemplateId(int $templateId): int
{
return TemplateLayout::where('template_id', $templateId)->count();
}
/**
* 특정 템플릿의 오버라이드 레이아웃들을 조회합니다.
*
* @param int $templateId 템플릿 ID
* @return Collection 오버라이드 레이아웃 컬렉션
*/
public function getOverridesByTemplateId(int $templateId): Collection
{
return TemplateLayout::where('template_id', $templateId)
->where('source_type', LayoutSourceType::Template)
->whereNotNull('source_identifier')
->get();
}
/**
* 특정 소스 식별자의 레이아웃을 모두 삭제합니다.
* soft deleted된 레코드를 포함하여 영구 삭제합니다.
*
* @param string $sourceIdentifier 소스 식별자 (모듈/템플릿 식별자)
* @return int 삭제된 레코드 수
*/
public function deleteBySourceIdentifier(string $sourceIdentifier): int
{
return TemplateLayout::withTrashed()
->where('source_identifier', $sourceIdentifier)
->forceDelete();
}
}
@@ -0,0 +1,192 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
use App\Models\TemplateLayout;
use App\Models\TemplateLayoutVersion;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
class LayoutVersionRepository implements LayoutVersionRepositoryInterface
{
public function __construct(
private TemplateLayoutVersion $model
) {}
/**
* 버전 저장 (자동 증가)
*
* @param int $layoutId 레이아웃 ID
* @param array $oldContent 이전 콘텐츠
* @param array|null $newContent 새 콘텐츠 (null이면 현재 레이아웃에서 가져옴)
* @return TemplateLayoutVersion 생성된 버전
*/
public function saveVersion(int $layoutId, array $oldContent, ?array $newContent = 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);
return $this->model->create([
'layout_id' => $layoutId,
'version' => $nextVersion,
'content' => $oldContent,
'changes_summary' => $changesSummary,
]);
}
/**
* 특정 레이아웃의 모든 버전 조회 (최신순)
*/
public function getVersions(int $layoutId): Collection
{
return $this->model
->where('layout_id', $layoutId)
->orderBy('version', 'desc')
->get();
}
/**
* 특정 버전 조회
*/
public function getVersion(int $versionId): ?TemplateLayoutVersion
{
return $this->model->find($versionId);
}
/**
* 다음 버전 번호 계산
*/
public function getNextVersion(int $layoutId): int
{
$maxVersion = $this->model
->where('layout_id', $layoutId)
->max('version');
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);
}
}
}
/**
* 버전 복원
*
* @throws ModelNotFoundException 버전을 찾을 수 없는 경우
*/
public function restoreVersion(int $layoutId, int $versionId): TemplateLayoutVersion
{
return DB::transaction(function () use ($layoutId, $versionId) {
// 1. 복원할 버전 조회
$versionToRestore = $this->model
->where('id', $versionId)
->where('layout_id', $layoutId)
->firstOrFail();
// 2. 레이아웃 모델 조회 및 현재 content 저장
$layout = TemplateLayout::findOrFail($layoutId);
$currentContent = $layout->content;
// 3. 레이아웃을 복원할 content로 업데이트
$layout->update([
'content' => $versionToRestore->content,
]);
// 4. 복원 전 content를 새 버전으로 저장 (이력 보존)
return $this->saveVersion($layoutId, $currentContent, $versionToRestore->content);
});
}
}
+124
View File
@@ -0,0 +1,124 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\MailSendLogRepositoryInterface;
use App\Enums\MailSendStatus;
use App\Models\MailSendLog;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
/**
* 메일 발송 이력 리포지토리 구현체
*/
class MailSendLogRepository implements MailSendLogRepositoryInterface
{
/**
* 발송 이력을 생성합니다.
*
* @param array $data 생성 데이터
* @return MailSendLog 생성된 발송 이력 모델
*/
public function create(array $data): MailSendLog
{
return MailSendLog::create($data);
}
/**
* 발송 이력 목록을 페이지네이션하여 조회합니다.
*
* @param array $filters 필터 조건
* @param int $perPage 페이지 당 항목 수
* @return LengthAwarePaginator 페이지네이션 결과
*/
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator
{
$sortBy = $filters['sort_by'] ?? 'sent_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query = MailSendLog::query()->orderBy($sortBy, $sortOrder);
if (! empty($filters['extension_type'])) {
$types = is_array($filters['extension_type']) ? $filters['extension_type'] : [$filters['extension_type']];
$query->whereIn('extension_type', $types);
}
if (! empty($filters['extension_identifier'])) {
$identifiers = is_array($filters['extension_identifier']) ? $filters['extension_identifier'] : [$filters['extension_identifier']];
$query->whereIn('extension_identifier', $identifiers);
}
if (! empty($filters['template_type'])) {
$query->where('template_type', $filters['template_type']);
}
if (! empty($filters['status'])) {
$statuses = is_array($filters['status']) ? $filters['status'] : [$filters['status']];
$query->whereIn('status', $statuses);
}
if (! empty($filters['search'])) {
$search = $filters['search'];
$searchType = $filters['search_type'] ?? 'all';
$query->where(function ($q) use ($search, $searchType) {
if ($searchType === 'recipient_email') {
$q->where('recipient_email', 'like', "%{$search}%");
} elseif ($searchType === 'recipient_name') {
$q->where('recipient_name', 'like', "%{$search}%");
} elseif ($searchType === 'subject') {
$q->where('subject', 'like', "%{$search}%");
} else {
$q->where('recipient_email', 'like', "%{$search}%")
->orWhere('recipient_name', 'like', "%{$search}%")
->orWhere('subject', 'like', "%{$search}%");
}
});
}
if (! empty($filters['date_from'])) {
$query->where('sent_at', '>=', Carbon::parse($filters['date_from'])->startOfDay());
}
if (! empty($filters['date_to'])) {
$query->where('sent_at', '<=', Carbon::parse($filters['date_to'])->endOfDay());
}
return $query->paginate($perPage);
}
/**
* 발송 통계를 조회합니다.
*
* @return array{total: int, sent: int, failed: int, today: int} 통계 정보
*/
public function getStatistics(): array
{
return [
'total' => MailSendLog::count(),
'sent' => MailSendLog::where('status', MailSendStatus::Sent->value)->count(),
'failed' => MailSendLog::where('status', MailSendStatus::Failed->value)->count(),
'today' => MailSendLog::whereDate('sent_at', Carbon::today())->count(),
];
}
/**
* 발송 이력을 삭제합니다.
*
* @param int $id 삭제할 발송 이력 ID
* @return bool 삭제 성공 여부
*/
public function delete(int $id): bool
{
return MailSendLog::where('id', $id)->delete() > 0;
}
/**
* 여러 발송 이력을 일괄 삭제합니다.
*
* @param array<int> $ids 삭제할 발송 이력 ID 목록
* @return int 삭제된 건수
*/
public function deleteMany(array $ids): int
{
return MailSendLog::whereIn('id', $ids)->delete();
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\MailTemplateRepositoryInterface;
use App\Models\MailTemplate;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
/**
* 메일 템플릿 리포지토리 구현체
*
* 메일 템플릿의 조회, 수정 등 데이터 접근 로직을 처리합니다.
*/
class MailTemplateRepository implements MailTemplateRepositoryInterface
{
/**
* ID로 메일 템플릿을 찾습니다.
*
* @param int $id 메일 템플릿 ID
* @return MailTemplate|null 찾은 모델 또는 null
*/
public function findById(int $id): ?MailTemplate
{
return MailTemplate::find($id);
}
/**
* 유형으로 메일 템플릿을 찾습니다.
*
* @param string $type 템플릿 유형
* @return MailTemplate|null 찾은 모델 또는 null
*/
public function findByType(string $type): ?MailTemplate
{
return MailTemplate::where('type', $type)->first();
}
/**
* 활성 상태인 특정 유형 템플릿을 찾습니다.
*
* @param string $type 템플릿 유형
* @return MailTemplate|null 활성 템플릿 또는 null
*/
public function getActiveByType(string $type): ?MailTemplate
{
return MailTemplate::active()->byType($type)->first();
}
/**
* 모든 메일 템플릿 목록을 반환합니다.
*
* @return Collection 메일 템플릿 컬렉션
*/
public function getAllTemplates(): Collection
{
return MailTemplate::orderBy('id')->get();
}
/**
* 메일 템플릿을 수정합니다.
*
* @param MailTemplate $template 수정 대상
* @param array $data 수정 데이터
* @return bool 수정 성공 여부
*/
public function update(MailTemplate $template, array $data): bool
{
return $template->update($data);
}
/**
* 메일 템플릿 목록을 페이지네이션하여 조회합니다.
*
* @param array $filters 필터 조건
* @param int $perPage 페이지 당 항목 수
* @return LengthAwarePaginator 페이지네이션 결과
*/
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator
{
$sortBy = $filters['sort_by'] ?? 'id';
$sortOrder = $filters['sort_order'] ?? 'asc';
$query = MailTemplate::query()->orderBy($sortBy, $sortOrder);
if (! empty($filters['search'])) {
$search = $filters['search'];
$searchType = $filters['search_type'] ?? 'all';
$query->where(function ($q) use ($search, $searchType) {
$locales = config('app.supported_locales', ['ko', 'en']);
if ($searchType === 'subject' || $searchType === 'all') {
foreach ($locales as $locale) {
$q->orWhere("subject->{$locale}", 'like', "%{$search}%");
}
}
if ($searchType === 'body' || $searchType === 'all') {
foreach ($locales as $locale) {
$q->orWhere("body->{$locale}", 'like', "%{$search}%");
}
}
});
}
return $query->paginate($perPage);
}
}
+470
View File
@@ -0,0 +1,470 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\MenuRepositoryInterface;
use App\Helpers\PermissionHelper;
use App\Enums\ExtensionOwnerType;
use App\Models\Menu;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
class MenuRepository implements MenuRepositoryInterface
{
/**
* 모든 메뉴를 조회합니다.
*
* @return Collection 메뉴 컬렉션 (관계 데이터 포함)
*/
public function getAll(): Collection
{
return Menu::with(['creator', 'parent', 'children'])
->orderBy('order')
->get();
}
/**
* 최상위 메뉴들을 조회합니다.
*
* @return Collection 최상위 메뉴 컬렉션 (활성화된 것만)
*/
public function getTopLevelMenus(): Collection
{
return Menu::topLevel()
->active()
->with(['creator', 'activeChildren'])
->get();
}
public function getTopLevelMenusForManagement(array $activeModuleIdentifiers = [], array $activePluginIdentifiers = [], ?User $user = null): Collection
{
$extensionFilter = function ($query) use ($activeModuleIdentifiers, $activePluginIdentifiers) {
// 코어 메뉴 또는 사용자 생성 메뉴
$query->whereNull('extension_type')
->orWhere('extension_type', ExtensionOwnerType::Core)
// 활성화된 모듈의 메뉴
->orWhere(function ($q) use ($activeModuleIdentifiers) {
$q->where('extension_type', ExtensionOwnerType::Module)
->whereIn('extension_identifier', $activeModuleIdentifiers);
})
// 활성화된 플러그인의 메뉴
->orWhere(function ($q) use ($activePluginIdentifiers) {
$q->where('extension_type', ExtensionOwnerType::Plugin)
->whereIn('extension_identifier', $activePluginIdentifiers);
});
};
$query = Menu::whereNull('parent_id')
->where($extensionFilter);
// 권한 스코프 필터링
PermissionHelper::applyPermissionScope($query, 'core.menus.read');
// 사용자 역할 기반 접근 제어
if ($user) {
$query->accessibleBy($user);
}
return $query->with(['creator', 'roles', 'children' => function ($query) use ($extensionFilter, $user) {
$query->where($extensionFilter);
if ($user) {
$query->accessibleBy($user);
}
$query->with('roles')
->orderBy('order');
}])
->orderBy('order')
->get();
}
/**
* 활성화된 메뉴들만 조회합니다.
*
* @return Collection 활성화된 메뉴 컬렉션
*/
public function getActiveMenus(): Collection
{
return Menu::active()
->with(['creator', 'parent', 'activeChildren'])
->orderBy('order')
->get();
}
/**
* ID로 메뉴를 찾습니다.
*
* @param int $id 메뉴 ID
* @return Menu|null 찾은 메뉴 모델 또는 null
*/
public function findById(int $id): ?Menu
{
return Menu::with(['creator', 'parent', 'children'])->find($id);
}
/**
* 슬러그로 메뉴를 찾습니다.
*
* @param string $slug 메뉴 슬러그
* @return Menu|null 찾은 메뉴 모델 또는 null
*/
public function findBySlug(string $slug): ?Menu
{
return Menu::where('slug', $slug)->first();
}
/**
* 새로운 메뉴를 생성합니다.
*
* @param array $data 메뉴 생성 데이터
* @return Menu 생성된 메뉴 모델
*/
public function create(array $data): Menu
{
return Menu::create($data);
}
/**
* 기존 메뉴를 업데이트합니다.
*
* @param Menu $menu 업데이트할 메뉴 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Menu $menu, array $data): bool
{
return $menu->update($data);
}
/**
* 메뉴를 삭제합니다.
*
* @param Menu $menu 삭제할 메뉴 모델
* @return bool 삭제 성공 여부
*/
public function delete(Menu $menu): bool
{
return $menu->delete();
}
/**
* 메뉴의 순서를 업데이트합니다.
*
* @param array $menuOrders 메뉴 ID와 순서 매핑 배열
* @return bool 업데이트 성공 여부
*/
public function updateOrder(array $menuOrders): bool
{
try {
foreach ($menuOrders as $order => $menuId) {
Menu::where('id', $menuId)->update(['order' => $order + 1]);
}
return true;
} catch (\Exception $e) {
return false;
}
}
/**
* 계층 구조를 고려한 메뉴 순서를 업데이트합니다.
*
* @param array $orderData 계층 구조 순서 데이터
* @return bool 업데이트 성공 여부
*/
public function updateOrderWithHierarchy(array $orderData): bool
{
try {
DB::beginTransaction();
// ① depth 이동 처리 (parent_id 변경)
if (isset($orderData['moved_items'])) {
foreach ($orderData['moved_items'] as $movedItem) {
Menu::where('id', $movedItem['id'])
->update(['parent_id' => $movedItem['new_parent_id']]);
}
}
// ② 부모 메뉴 순서 업데이트
if (isset($orderData['parent_menus'])) {
foreach ($orderData['parent_menus'] as $parentMenu) {
Menu::where('id', $parentMenu['id'])
->update(['order' => $parentMenu['order']]);
}
}
// ③ 자식 메뉴 순서 업데이트
if (isset($orderData['child_menus'])) {
foreach ($orderData['child_menus'] as $parentId => $children) {
foreach ($children as $childMenu) {
Menu::where('id', $childMenu['id'])
->where('parent_id', $parentId)
->update(['order' => $childMenu['order']]);
}
}
}
DB::commit();
return true;
} catch (\Exception $e) {
DB::rollBack();
return false;
}
}
/**
* 특정 확장에 속한 메뉴들을 조회합니다.
*
* @param ExtensionOwnerType $type 확장 타입
* @param string $identifier 확장 식별자
* @return Collection 확장에 속한 메뉴 컬렉션
*/
public function getMenusByExtension(ExtensionOwnerType $type, string $identifier): Collection
{
return Menu::where('extension_type', $type)
->where('extension_identifier', $identifier)
->with(['creator', 'parent', 'children'])
->orderBy('order')
->get();
}
/**
* 부모 메뉴의 자식 메뉴들을 조회합니다.
*
* @param int $parentId 부모 메뉴 ID
* @return Collection 자식 메뉴 컬렉션
*/
public function getChildrenByParent(int $parentId): Collection
{
return Menu::where('parent_id', $parentId)
->with(['creator', 'children'])
->orderBy('order')
->get();
}
/**
* 네비게이션용 활성화된 메뉴들을 자식 메뉴와 함께 조회합니다.
*
* @return Collection 활성화된 메뉴 컬렉션 (자식 메뉴 포함)
*/
public function getActiveMenusWithChildren(): Collection
{
$activeExtensionFilter = function ($query) {
// 코어 메뉴 또는 사용자 생성 메뉴
$query->whereNull('extension_type')
->orWhere('extension_type', ExtensionOwnerType::Core)
// 활성화된 모듈의 메뉴
->orWhere(function ($q) {
$q->where('extension_type', ExtensionOwnerType::Module)
->whereExists(function ($subQuery) {
$subQuery->select(DB::raw(1))
->from('modules')
->whereColumn('modules.identifier', 'menus.extension_identifier')
->where('modules.status', 'active');
});
})
// 활성화된 플러그인의 메뉴
->orWhere(function ($q) {
$q->where('extension_type', ExtensionOwnerType::Plugin)
->whereExists(function ($subQuery) {
$subQuery->select(DB::raw(1))
->from('plugins')
->whereColumn('plugins.identifier', 'menus.extension_identifier')
->where('plugins.status', 'active');
});
});
};
return Menu::active()
->where($activeExtensionFilter)
->with(['activeChildren' => function ($query) use ($activeExtensionFilter) {
$query->where($activeExtensionFilter)
->orderBy('order');
}])
->whereNull('parent_id') // 최상위 메뉴만
->orderBy('order')
->get();
}
/**
* 사용자가 접근 가능한 네비게이션용 메뉴들을 조회합니다.
*
* @param User $user 접근 권한을 확인할 사용자
* @return Collection 사용자가 접근 가능한 메뉴 컬렉션
*/
public function getAccessibleNavigationMenus(User $user): Collection
{
return Menu::active()
->accessibleBy($user)
->with(['activeChildren' => function ($query) use ($user) {
$query->accessibleBy($user)->orderBy('order');
}])
->whereNull('parent_id') // 최상위 메뉴만
->orderBy('order')
->get();
}
/**
* slug와 확장 정보로 메뉴를 찾습니다.
*
* @param string $slug 메뉴 슬러그
* @param ExtensionOwnerType $extensionType 확장 타입
* @param string $extensionIdentifier 확장 식별자
* @return Menu|null 찾은 메뉴 모델 또는 null
*/
public function findBySlugAndExtension(string $slug, ExtensionOwnerType $extensionType, string $extensionIdentifier): ?Menu
{
return Menu::where('slug', $slug)
->where('extension_type', $extensionType)
->where('extension_identifier', $extensionIdentifier)
->first();
}
/**
* 메뉴를 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return Menu 생성 또는 업데이트된 메뉴 모델
*/
public function updateOrCreate(array $attributes, array $values): Menu
{
return Menu::updateOrCreate($attributes, $values);
}
/**
* 특정 확장의 모든 메뉴를 삭제합니다.
*
* @param ExtensionOwnerType $type 확장 타입
* @param string $identifier 확장 식별자
* @return int 삭제된 레코드 수
*/
public function deleteByExtension(ExtensionOwnerType $type, string $identifier): int
{
return Menu::where('extension_type', $type)
->where('extension_identifier', $identifier)
->delete();
}
/**
* 같은 부모 내에서 최대 순서 값을 조회합니다.
*
* @param int|null $parentId 부모 메뉴 ID (null이면 최상위)
* @return int 최대 순서 값 (없으면 0)
*/
public function getMaxOrder(?int $parentId = null): int
{
return (int) Menu::where('parent_id', $parentId)->max('order');
}
public function getFilteredTopLevelMenus(array $filters, array $activeModuleIdentifiers = [], array $activePluginIdentifiers = [], ?User $user = null): Collection
{
$extensionFilter = function ($query) use ($activeModuleIdentifiers, $activePluginIdentifiers) {
$query->whereNull('extension_type')
->orWhere('extension_type', ExtensionOwnerType::Core)
->orWhere(function ($q) use ($activeModuleIdentifiers) {
$q->where('extension_type', ExtensionOwnerType::Module)
->whereIn('extension_identifier', $activeModuleIdentifiers);
})
->orWhere(function ($q) use ($activePluginIdentifiers) {
$q->where('extension_type', ExtensionOwnerType::Plugin)
->whereIn('extension_identifier', $activePluginIdentifiers);
});
};
$query = Menu::whereNull('parent_id')
->where($extensionFilter);
// 권한 스코프 필터링
PermissionHelper::applyPermissionScope($query, 'core.menus.read');
// 사용자 역할 기반 접근 제어
if ($user) {
$query->accessibleBy($user);
}
// 활성화 상태 필터
if (isset($filters['is_active'])) {
$query->where('is_active', $filters['is_active']);
}
// 다중 검색 조건 적용
if (! empty($filters['filters'])) {
$searchableFields = ['name', 'slug', 'url'];
foreach ($filters['filters'] as $filter) {
$field = $filter['field'] ?? null;
$value = $filter['value'] ?? null;
$operator = $filter['operator'] ?? 'like';
if (! $field || ! $value) {
continue;
}
// 'all' 필드인 경우 모든 검색 가능 필드에서 검색
if ($field === 'all') {
$query->where(function ($q) use ($searchableFields, $value, $operator) {
foreach ($searchableFields as $searchField) {
$q->orWhere(function ($subQ) use ($searchField, $value, $operator) {
$this->applyFilterOperator($subQ, $searchField, $value, $operator);
});
}
});
} elseif (in_array($field, $searchableFields)) {
$this->applyFilterOperator($query, $field, $value, $operator);
}
}
}
// 정렬
$sortBy = $filters['sort_by'] ?? 'order';
$sortOrder = $filters['sort_order'] ?? 'asc';
$query->orderBy($sortBy, $sortOrder);
// 자식 메뉴도 동일한 조건 적용하여 로드
return $query->with(['creator', 'roles', 'children' => function ($childQuery) use ($extensionFilter, $filters, $user) {
$childQuery->where($extensionFilter);
// 자식 메뉴에도 사용자 역할 기반 접근 제어 적용
if ($user) {
$childQuery->accessibleBy($user);
}
// 자식 메뉴에도 활성화 상태 필터 적용
if (isset($filters['is_active'])) {
$childQuery->where('is_active', $filters['is_active']);
}
$childQuery->with('roles')->orderBy('order');
}])->get();
}
/**
* 필터 연산자를 쿼리에 적용합니다.
*
* @param \Illuminate\Database\Eloquent\Builder $query 쿼리 빌더
* @param string $field 필드명
* @param string $value 검색 값
* @param string $operator 연산자 (like, eq, starts_with, ends_with)
*/
private function applyFilterOperator($query, string $field, string $value, string $operator): void
{
switch ($operator) {
case 'eq':
$query->where($field, $value);
break;
case 'starts_with':
$query->where($field, 'like', $value.'%');
break;
case 'ends_with':
$query->where($field, 'like', '%'.$value);
break;
case 'like':
default:
$query->where($field, 'like', '%'.$value.'%');
break;
}
}
}
+329
View File
@@ -0,0 +1,329 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\ModuleRepositoryInterface;
use App\Enums\ExtensionStatus;
use App\Models\Module;
use Illuminate\Database\Eloquent\Collection;
class ModuleRepository implements ModuleRepositoryInterface
{
/**
* 모든 모듈을 조회합니다.
*
* @return Collection 모듈 컬렉션
*/
public function getAll(): Collection
{
return Module::all();
}
/**
* 모든 모듈을 identifier로 키잉하여 조회합니다.
*
* @return Collection identifier를 키로 하는 모듈 컬렉션
*/
public function getAllKeyedByIdentifier(): Collection
{
return Module::all()->keyBy('identifier');
}
/**
* 설치된 모든 모듈의 identifier 목록을 조회합니다.
*
* @return array 설치된 모듈 identifier 배열
*/
public function getInstalledIdentifiers(): array
{
return Module::pluck('identifier')->toArray();
}
/**
* 이름으로 모듈을 찾습니다.
*
* @param string $name 찾을 모듈 이름
* @return Module|null 찾은 모듈 모델 또는 null
*/
public function findByName(string $name): ?Module
{
return Module::where('name', $name)->first();
}
/**
* 활성화된 모듈들을 조회합니다.
*
* @return Collection 활성화된 모듈 컬렉션
*/
public function getActive(): Collection
{
return Module::where('is_active', true)->get();
}
/**
* 새로운 모듈을 생성합니다.
*
* @param array $data 모듈 생성 데이터
* @return Module 생성된 모듈 모델
*/
public function create(array $data): Module
{
return Module::create($data);
}
/**
* 모듈을 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return Module 생성 또는 업데이트된 모듈 모델
*/
public function updateOrCreate(array $attributes, array $values): Module
{
return Module::updateOrCreate($attributes, $values);
}
/**
* 기존 모듈을 업데이트합니다.
*
* @param Module $module 업데이트할 모듈 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Module $module, array $data): bool
{
return $module->update($data);
}
/**
* 식별자로 모듈 상태를 업데이트합니다.
*
* @param string $identifier 모듈 식별자
* @param array $data 업데이트할 데이터
* @return int 업데이트된 레코드 수
*/
public function updateByIdentifier(string $identifier, array $data): int
{
return Module::where('identifier', $identifier)->update($data);
}
/**
* 모듈을 삭제합니다.
*
* @param Module $module 삭제할 모듈 모델
* @return bool 삭제 성공 여부
*/
public function delete(Module $module): bool
{
return $module->delete();
}
/**
* 식별자로 모듈을 삭제합니다.
*
* @param string $identifier 모듈 식별자
* @return int 삭제된 레코드 수
*/
public function deleteByIdentifier(string $identifier): int
{
return Module::where('identifier', $identifier)->delete();
}
/**
* 모듈을 활성화합니다.
*
* @param Module $module 활성화할 모듈 모델
* @return bool 활성화 성공 여부
*/
public function activate(Module $module): bool
{
return $module->update(['is_active' => true]);
}
/**
* 모듈을 비활성화합니다.
*
* @param Module $module 비활성화할 모듈 모델
* @return bool 비활성화 성공 여부
*/
public function deactivate(Module $module): bool
{
return $module->update(['is_active' => false]);
}
/**
* 모듈의 설치 상태를 업데이트합니다.
*
* @param Module $module 대상 모듈 모델
* @param bool $installed 설치 상태 (기본값: true)
* @return bool 업데이트 성공 여부
*/
public function setInstalled(Module $module, bool $installed = true): bool
{
return $module->update(['is_installed' => $installed]);
}
/**
* 설치된 모듈들을 조회합니다.
*
* @return Collection 설치된 모듈 컬렉션
*/
public function getInstalled(): Collection
{
return Module::where('is_installed', true)->get();
}
/**
* 마켓플레이스용 모듈들을 조회합니다.
*
* @return Collection 공개된 모듈 컬렉션
*/
public function getForMarketplace(): Collection
{
return Module::where('is_published', true)->get();
}
/**
* 의존성 정보가 포함된 모든 모듈을 조회합니다.
*
* @return Collection 의존성 정보를 포함한 모듈 컬렉션
*/
public function getAllWithDependencies(): Collection
{
return Module::with(['dependencies', 'dependents'])->get();
}
/**
* 슬러그로 모듈을 찾습니다.
*
* @param string $slug 모듈 슬러그
* @return Module|null 찾은 모듈 모델 또는 null
*/
public function findBySlug(string $slug): ?Module
{
return Module::where('slug', $slug)->first();
}
/**
* 식별자로 모듈을 찾습니다.
*
* @param string $identifier 모듈 식별자
* @return Module|null 찾은 모듈 모델 또는 null
*/
public function findByIdentifier(string $identifier): ?Module
{
return Module::where('identifier', $identifier)->first();
}
/**
* 활성화된 모듈들의 ID 목록을 반환합니다.
*
* @return array 활성화된 모듈 ID 배열
*/
public function getActiveModuleIds(): array
{
return Module::where('status', ExtensionStatus::Active)
->pluck('id')
->toArray();
}
/**
* 활성화된 모듈들의 identifier 목록을 반환합니다.
*
* @return array 활성화된 모듈 identifier 배열
*/
public function getActiveModuleIdentifiers(): array
{
return Module::where('status', ExtensionStatus::Active)
->pluck('identifier')
->toArray();
}
/**
* 식별자로 활성화된 모듈을 찾습니다.
*
* @param string $identifier 모듈 식별자
* @return Module|null 찾은 모듈 모델 또는 null
*/
public function findActiveByIdentifier(string $identifier): ?Module
{
return Module::where('identifier', $identifier)
->where('status', ExtensionStatus::Active->value)
->first();
}
/**
* 특정 모듈에 의존하는 활성 모듈을 조회합니다.
*
* ModuleManager를 통해 각 모듈의 getDependencies()를 확인하여
* 해당 모듈에 의존하는 모듈만 필터링합니다.
*
* @param string $moduleIdentifier 의존 대상 모듈 식별자
* @return Collection 해당 모듈에 의존하는 활성 모듈 컬렉션
*/
public function findActiveByModuleDependency(string $moduleIdentifier): Collection
{
// 활성화된 모든 모듈 조회
$activeModules = Module::where('status', ExtensionStatus::Active->value)->get();
if ($activeModules->isEmpty()) {
return new Collection();
}
// ModuleManager를 통해 각 모듈의 의존성 확인
$moduleManager = app(\App\Contracts\Extension\ModuleManagerInterface::class);
return $activeModules->filter(function (Module $module) use ($moduleManager, $moduleIdentifier) {
$moduleInstance = $moduleManager->getModule($module->identifier);
if (! $moduleInstance) {
return false;
}
$dependencies = $moduleInstance->getDependencies();
// 해당 모듈이 의존성에 포함되어 있는지 확인
return in_array($moduleIdentifier, $dependencies);
})->values();
}
/**
* 특정 플러그인에 의존하는 활성 모듈을 조회합니다.
*
* ModuleManager를 통해 각 모듈의 getPluginDependencies()를 확인하여
* 해당 플러그인에 의존하는 모듈만 필터링합니다.
*
* @param string $pluginIdentifier 의존 대상 플러그인 식별자
* @return Collection 해당 플러그인에 의존하는 활성 모듈 컬렉션
*/
public function findActiveByPluginDependency(string $pluginIdentifier): Collection
{
// 활성화된 모든 모듈 조회
$activeModules = Module::where('status', ExtensionStatus::Active->value)->get();
if ($activeModules->isEmpty()) {
return new Collection();
}
// ModuleManager를 통해 각 모듈의 플러그인 의존성 확인
$moduleManager = app(\App\Contracts\Extension\ModuleManagerInterface::class);
return $activeModules->filter(function (Module $module) use ($moduleManager, $pluginIdentifier) {
$moduleInstance = $moduleManager->getModule($module->identifier);
if (! $moduleInstance) {
return false;
}
// getPluginDependencies 메서드가 있는지 확인
if (! method_exists($moduleInstance, 'getPluginDependencies')) {
return false;
}
$pluginDependencies = $moduleInstance->getPluginDependencies();
// 해당 플러그인이 의존성에 포함되어 있는지 확인
return in_array($pluginIdentifier, $pluginDependencies);
})->values();
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\PasswordResetTokenRepositoryInterface;
use App\Models\PasswordResetToken;
/**
* 비밀번호 재설정 토큰 Repository
*/
class PasswordResetTokenRepository implements PasswordResetTokenRepositoryInterface
{
/**
* 이메일로 비밀번호 재설정 토큰을 조회합니다.
*
* @param string $email 사용자 이메일
* @return PasswordResetToken|null 토큰 레코드 또는 null
*/
public function findByEmail(string $email): ?PasswordResetToken
{
return PasswordResetToken::where('email', $email)->first();
}
/**
* 비밀번호 재설정 토큰을 생성하거나 업데이트합니다.
*
* @param string $email 사용자 이메일
* @param array $data 토큰 데이터
* @return PasswordResetToken 생성 또는 업데이트된 토큰
*/
public function updateOrCreateByEmail(string $email, array $data): PasswordResetToken
{
return PasswordResetToken::updateOrCreate(
['email' => $email],
$data
);
}
/**
* 비밀번호 재설정 토큰을 삭제합니다.
*
* @param PasswordResetToken $token 삭제할 토큰
* @return bool 삭제 성공 여부
*/
public function delete(PasswordResetToken $token): bool
{
return $token->delete();
}
}
+161
View File
@@ -0,0 +1,161 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\PermissionRepositoryInterface;
use App\Enums\ExtensionOwnerType;
use App\Models\Permission;
use Illuminate\Database\Eloquent\Collection;
class PermissionRepository implements PermissionRepositoryInterface
{
/**
* 모든 권한을 조회합니다.
*
* @return Collection 권한 컬렉션
*/
public function getAll(): Collection
{
return Permission::orderBy('id')->get();
}
/**
* ID로 권한을 찾습니다.
*
* @param int $id 권한 ID
* @return Permission|null 찾은 권한 모델 또는 null
*/
public function findById(int $id): ?Permission
{
return Permission::find($id);
}
/**
* 식별자로 권한을 찾습니다.
*
* @param string $identifier 권한 식별자
* @return Permission|null 찾은 권한 모델 또는 null
*/
public function findByIdentifier(string $identifier): ?Permission
{
return Permission::where('identifier', $identifier)->first();
}
/**
* 새로운 권한을 생성합니다.
*
* @param array $data 권한 생성 데이터
* @return Permission 생성된 권한 모델
*/
public function create(array $data): Permission
{
return Permission::create($data);
}
/**
* 권한을 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return Permission 생성 또는 업데이트된 권한 모델
*/
public function updateOrCreate(array $attributes, array $values): Permission
{
return Permission::updateOrCreate($attributes, $values);
}
/**
* 기존 권한을 업데이트합니다.
*
* @param Permission $permission 업데이트할 권한 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Permission $permission, array $data): bool
{
return $permission->update($data);
}
/**
* 권한을 삭제합니다.
*
* @param Permission $permission 삭제할 권한 모델
* @return bool 삭제 성공 여부
*/
public function delete(Permission $permission): bool
{
return $permission->delete();
}
/**
* 특정 확장의 모든 권한을 조회합니다.
*
* @param ExtensionOwnerType $type 확장 타입
* @param string|null $identifier 확장 식별자
* @return Collection 확장에 속한 권한 컬렉션
*/
public function getByExtension(ExtensionOwnerType $type, ?string $identifier = null): Collection
{
$query = Permission::where('extension_type', $type);
if ($identifier !== null) {
$query->where('extension_identifier', $identifier);
}
return $query->get();
}
/**
* 특정 확장의 모든 권한을 삭제합니다.
*
* @param ExtensionOwnerType $type 확장 타입
* @param string|null $identifier 확장 식별자
* @return int 삭제된 레코드 수
*/
public function deleteByExtension(ExtensionOwnerType $type, ?string $identifier = null): int
{
$query = Permission::where('extension_type', $type);
if ($identifier !== null) {
$query->where('extension_identifier', $identifier);
}
return $query->delete();
}
/**
* 코어 권한들을 조회합니다.
*
* @return Collection 코어 권한 컬렉션
*/
public function getCorePermissions(): Collection
{
return Permission::where('extension_type', ExtensionOwnerType::Core)->get();
}
/**
* 최상위 권한(루트)을 모든 자식과 함께 조회합니다.
*
* @return Collection 루트 권한 컬렉션 (allChildren 관계 포함)
*/
public function getRootsWithChildren(): Collection
{
return Permission::roots()
->with('allChildren')
->orderBy('order')
->get();
}
/**
* 할당 가능한 권한 ID 목록을 반환합니다. (리프 노드만)
*
* @return array 할당 가능한 권한 ID 배열
*/
public function getAssignableIds(): array
{
return Permission::whereDoesntHave('children')
->whereNotNull('parent_id')
->pluck('id')
->toArray();
}
}
+278
View File
@@ -0,0 +1,278 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\PluginRepositoryInterface;
use App\Enums\ExtensionStatus;
use App\Models\Plugin;
use Illuminate\Database\Eloquent\Collection;
class PluginRepository implements PluginRepositoryInterface
{
/**
* 모든 플러그인을 조회합니다.
*
* @return Collection 플러그인 컬렉션
*/
public function getAll(): Collection
{
return Plugin::all();
}
/**
* 이름으로 플러그인을 찾습니다.
*
* @param string $name 찾을 플러그인 이름
* @return Plugin|null 찾은 플러그인 모델 또는 null
*/
public function findByName(string $name): ?Plugin
{
return Plugin::where('name', $name)->first();
}
/**
* 활성화된 플러그인들을 조회합니다.
*
* @return Collection 활성화된 플러그인 컬렉션
*/
public function getActive(): Collection
{
return Plugin::where('status', ExtensionStatus::Active->value)->get();
}
/**
* 새로운 플러그인을 생성합니다.
*
* @param array $data 플러그인 생성 데이터
* @return Plugin 생성된 플러그인 모델
*/
public function create(array $data): Plugin
{
return Plugin::create($data);
}
/**
* 기존 플러그인을 업데이트합니다.
*
* @param Plugin $plugin 업데이트할 플러그인 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Plugin $plugin, array $data): bool
{
return $plugin->update($data);
}
/**
* 플러그인을 삭제합니다.
*
* @param Plugin $plugin 삭제할 플러그인 모델
* @return bool 삭제 성공 여부
*/
public function delete(Plugin $plugin): bool
{
return $plugin->delete();
}
/**
* 플러그인을 활성화합니다.
*
* @param Plugin $plugin 활성화할 플러그인 모델
* @return bool 활성화 성공 여부
*/
public function activate(Plugin $plugin): bool
{
return $plugin->update(['status' => ExtensionStatus::Active->value]);
}
/**
* 플러그인을 비활성화합니다.
*
* @param Plugin $plugin 비활성화할 플러그인 모델
* @return bool 비활성화 성공 여부
*/
public function deactivate(Plugin $plugin): bool
{
return $plugin->update(['status' => ExtensionStatus::Inactive->value]);
}
/**
* 플러그인의 설치 상태를 업데이트합니다.
*
* @param Plugin $plugin 대상 플러그인 모델
* @param bool $installed 설치 상태 (기본값: true)
* @return bool 업데이트 성공 여부
*/
public function setInstalled(Plugin $plugin, bool $installed = true): bool
{
$status = $installed ? ExtensionStatus::Inactive->value : ExtensionStatus::Installing->value;
return $plugin->update(['status' => $status]);
}
/**
* 식별자로 플러그인을 찾습니다.
*
* @param string $identifier 플러그인 식별자
* @return Plugin|null 찾은 플러그인 모델 또는 null
*/
public function findByIdentifier(string $identifier): ?Plugin
{
return Plugin::where('identifier', $identifier)->first();
}
/**
* 식별자로 활성화된 플러그인을 찾습니다.
*
* @param string $identifier 플러그인 식별자
* @return Plugin|null 찾은 플러그인 모델 또는 null
*/
public function findActiveByIdentifier(string $identifier): ?Plugin
{
return Plugin::where('identifier', $identifier)
->where('status', ExtensionStatus::Active->value)
->first();
}
/**
* 활성화된 플러그인들의 identifier 목록을 반환합니다.
*
* @return array 활성화된 플러그인 identifier 배열
*/
public function getActivePluginIdentifiers(): array
{
return Plugin::where('status', ExtensionStatus::Active->value)
->pluck('identifier')
->toArray();
}
/**
* 플러그인을 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return Plugin 생성 또는 업데이트된 플러그인 모델
*/
public function updateOrCreate(array $attributes, array $values): Plugin
{
return Plugin::updateOrCreate($attributes, $values);
}
/**
* 식별자로 플러그인 상태를 업데이트합니다.
*
* @param string $identifier 플러그인 식별자
* @param array $data 업데이트할 데이터
* @return int 업데이트된 레코드 수
*/
public function updateByIdentifier(string $identifier, array $data): int
{
return Plugin::where('identifier', $identifier)->update($data);
}
/**
* 식별자로 플러그인을 삭제합니다.
*
* @param string $identifier 플러그인 식별자
* @return int 삭제된 레코드 수
*/
public function deleteByIdentifier(string $identifier): int
{
return Plugin::where('identifier', $identifier)->delete();
}
/**
* 모든 플러그인을 identifier로 키잉하여 조회합니다.
*
* @return Collection identifier를 키로 하는 플러그인 컬렉션
*/
public function getAllKeyedByIdentifier(): Collection
{
return Plugin::all()->keyBy('identifier');
}
/**
* 설치된 모든 플러그인의 identifier 목록을 조회합니다.
*
* @return array 설치된 플러그인 identifier 배열
*/
public function getInstalledIdentifiers(): array
{
return Plugin::pluck('identifier')->toArray();
}
/**
* 특정 모듈에 의존하는 활성 플러그인을 조회합니다.
*
* PluginManager를 통해 각 플러그인의 getDependencies()를 확인하여
* 해당 모듈에 의존하는 플러그인만 필터링합니다.
*
* @param string $moduleIdentifier 의존 대상 모듈 식별자
* @return Collection 해당 모듈에 의존하는 활성 플러그인 컬렉션
*/
public function findActiveByModuleDependency(string $moduleIdentifier): Collection
{
// 활성화된 모든 플러그인 조회
$activePlugins = Plugin::where('status', ExtensionStatus::Active->value)->get();
if ($activePlugins->isEmpty()) {
return new Collection();
}
// PluginManager를 통해 각 플러그인의 모듈 의존성 확인
$pluginManager = app(\App\Contracts\Extension\PluginManagerInterface::class);
return $activePlugins->filter(function (Plugin $plugin) use ($pluginManager, $moduleIdentifier) {
$pluginInstance = $pluginManager->getPlugin($plugin->identifier);
if (! $pluginInstance) {
return false;
}
// getModuleDependencies 메서드가 있는지 확인
if (! method_exists($pluginInstance, 'getModuleDependencies')) {
return false;
}
$moduleDependencies = $pluginInstance->getModuleDependencies();
// 해당 모듈이 의존성에 포함되어 있는지 확인
return in_array($moduleIdentifier, $moduleDependencies);
})->values();
}
/**
* 특정 플러그인에 의존하는 활성 플러그인을 조회합니다.
*
* PluginManager를 통해 각 플러그인의 getDependencies()를 확인하여
* 해당 플러그인에 의존하는 플러그인만 필터링합니다.
*
* @param string $pluginIdentifier 의존 대상 플러그인 식별자
* @return Collection 해당 플러그인에 의존하는 활성 플러그인 컬렉션
*/
public function findActiveByPluginDependency(string $pluginIdentifier): Collection
{
// 활성화된 모든 플러그인 조회
$activePlugins = Plugin::where('status', ExtensionStatus::Active->value)->get();
if ($activePlugins->isEmpty()) {
return new Collection();
}
// PluginManager를 통해 각 플러그인의 플러그인 의존성 확인
$pluginManager = app(\App\Contracts\Extension\PluginManagerInterface::class);
return $activePlugins->filter(function (Plugin $plugin) use ($pluginManager, $pluginIdentifier) {
$pluginInstance = $pluginManager->getPlugin($plugin->identifier);
if (! $pluginInstance) {
return false;
}
$dependencies = $pluginInstance->getDependencies();
// 해당 플러그인이 의존성에 포함되어 있는지 확인
return in_array($pluginIdentifier, $dependencies);
})->values();
}
}
+205
View File
@@ -0,0 +1,205 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\RoleRepositoryInterface;
use App\Enums\ExtensionOwnerType;
use App\Models\Role;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
class RoleRepository implements RoleRepositoryInterface
{
/**
* 모든 역할을 조회합니다.
*
* @return Collection 역할 컬렉션
*/
public function getAll(): Collection
{
return Role::with(['permissions'])
->orderBy('id')
->get();
}
/**
* 활성화된 역할들만 조회합니다.
*
* @return Collection 활성화된 역할 컬렉션
*/
public function getActiveRoles(): Collection
{
return Role::where('is_active', true)
->orderBy('id')
->get();
}
/**
* ID로 역할을 찾습니다.
*
* @param int $id 역할 ID
* @return Role|null 찾은 역할 모델 또는 null
*/
public function findById(int $id): ?Role
{
return Role::with(['permissions'])->find($id);
}
/**
* 식별자로 역할을 찾습니다.
*
* @param string $identifier 역할 식별자
* @return Role|null 찾은 역할 모델 또는 null
*/
public function findByIdentifier(string $identifier): ?Role
{
return Role::where('identifier', $identifier)->first();
}
/**
* 새로운 역할을 생성합니다.
*
* @param array $data 역할 생성 데이터
* @return Role 생성된 역할 모델
*/
public function create(array $data): Role
{
return Role::create($data);
}
/**
* 역할을 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return Role 생성 또는 업데이트된 역할 모델
*/
public function updateOrCreate(array $attributes, array $values): Role
{
return Role::updateOrCreate($attributes, $values);
}
/**
* 기존 역할을 업데이트합니다.
*
* @param Role $role 업데이트할 역할 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Role $role, array $data): bool
{
return $role->update($data);
}
/**
* 역할을 삭제합니다.
*
* @param Role $role 삭제할 역할 모델
* @return bool 삭제 성공 여부
*/
public function delete(Role $role): bool
{
return $role->delete();
}
/**
* 확장이 소유한 역할을 식별자로 찾습니다.
*
* @param string $identifier 역할 식별자
* @param ExtensionOwnerType $extensionType 확장 타입
* @param string $extensionIdentifier 확장 식별자
* @return Role|null 찾은 역할 모델 또는 null
*/
public function findExtensionRoleByIdentifier(string $identifier, ExtensionOwnerType $extensionType, string $extensionIdentifier): ?Role
{
return Role::where('identifier', $identifier)
->where('extension_type', $extensionType)
->where('extension_identifier', $extensionIdentifier)
->first();
}
/**
* 역할에 권한을 할당합니다.
*
* 기존 권한을 유지하면서 새 권한만 추가합니다.
*
* @param Role $role 역할 모델
* @param int $permissionId 권한 ID
* @param array $pivotData 피벗 테이블에 저장할 추가 데이터
*/
public function attachPermission(Role $role, int $permissionId, array $pivotData = []): void
{
$role->permissions()->syncWithoutDetaching([
$permissionId => $pivotData,
]);
}
/**
* 역할에서 권한을 해제합니다.
*
* @param Role $role 역할 모델
* @param int $permissionId 권한 ID
* @return int 해제된 권한 수
*/
public function detachPermission(Role $role, int $permissionId): int
{
return $role->permissions()->detach($permissionId);
}
/**
* 역할의 모든 권한을 해제합니다.
*
* @param Role $role 역할 모델
* @return int 해제된 권한 수
*/
public function detachAllPermissions(Role $role): int
{
return $role->permissions()->detach();
}
/**
* 역할 목록을 페이지네이션하여 조회합니다.
*
* @param array $filters 필터 조건
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator 페이지네이션된 역할 목록
*/
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator
{
$query = Role::query()
->withCount('users')
->with('permissions');
// 검색 필터
if (! empty($filters['search'])) {
$search = $filters['search'];
$query->where(function ($q) use ($search) {
$q->where('identifier', 'like', "%{$search}%")
->orWhere('name->ko', 'like', "%{$search}%")
->orWhere('name->en', 'like', "%{$search}%");
});
}
// 활성화 상태 필터
if (isset($filters['is_active'])) {
$query->where('is_active', $filters['is_active']);
}
// 정렬 (코어/확장 소유 역할 먼저, 그 다음 사용자 생성 역할)
$query->orderByRaw('CASE WHEN extension_type IS NOT NULL THEN 0 ELSE 1 END')
->orderBy('created_at', 'desc');
return $query->paginate($perPage);
}
/**
* 역할에 할당된 권한 개수를 반환합니다.
*
* @param Role $role 역할 모델
* @return int 권한 개수
*/
public function getPermissionCount(Role $role): int
{
return $role->permissions()->count();
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\ScheduleHistoryRepositoryInterface;
use App\Models\ScheduleHistory;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
class ScheduleHistoryRepository implements ScheduleHistoryRepositoryInterface
{
/**
* ID로 실행 이력을 찾습니다.
*
* @param int $id 이력 ID
* @return ScheduleHistory|null 찾은 이력 모델 또는 null
*/
public function findById(int $id): ?ScheduleHistory
{
return ScheduleHistory::with(['schedule', 'triggeredBy'])->find($id);
}
/**
* 새로운 실행 이력을 생성합니다.
*
* @param array $data 이력 생성 데이터
* @return ScheduleHistory 생성된 이력 모델
*/
public function create(array $data): ScheduleHistory
{
return ScheduleHistory::create($data);
}
/**
* 기존 실행 이력을 업데이트합니다.
*
* @param ScheduleHistory $history 업데이트할 이력 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(ScheduleHistory $history, array $data): bool
{
return $history->update($data);
}
/**
* 실행 이력을 삭제합니다.
*
* @param ScheduleHistory $history 삭제할 이력 모델
* @return bool 삭제 성공 여부
*/
public function delete(ScheduleHistory $history): bool
{
return $history->delete();
}
/**
* 특정 스케줄의 실행 이력을 페이지네이션하여 조회합니다.
*
* @param int $scheduleId 스케줄 ID
* @param array $filters 필터 조건 배열
* @return LengthAwarePaginator 페이지네이션된 이력 목록
*/
public function getPaginatedByScheduleId(int $scheduleId, array $filters = []): LengthAwarePaginator
{
$query = ScheduleHistory::with('triggeredBy')
->where('schedule_id', $scheduleId);
// 상태 필터
if (!empty($filters['status'])) {
$query->where('status', $filters['status']);
}
// 트리거 유형 필터
if (!empty($filters['trigger_type'])) {
$query->where('trigger_type', $filters['trigger_type']);
}
// 날짜 필터
if (!empty($filters['started_from'])) {
$query->whereDate('started_at', '>=', $filters['started_from']);
}
if (!empty($filters['started_to'])) {
$query->whereDate('started_at', '<=', $filters['started_to']);
}
// 정렬 적용
$sortBy = $filters['sort_by'] ?? 'started_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
// 페이지네이션 적용
$perPage = $filters['per_page'] ?? 15;
return $query->paginate($perPage);
}
/**
* 특정 스케줄의 최근 실행 이력을 조회합니다.
*
* @param int $scheduleId 스케줄 ID
* @param int $limit 조회 개수
* @return Collection 최근 이력 컬렉션
*/
public function getRecentByScheduleId(int $scheduleId, int $limit = 10): Collection
{
return ScheduleHistory::with('triggeredBy')
->where('schedule_id', $scheduleId)
->orderByDesc('started_at')
->limit($limit)
->get();
}
/**
* 여러 이력을 일괄 삭제합니다.
*
* @param array $ids 이력 ID 배열
* @return int 삭제된 레코드 수
*/
public function bulkDelete(array $ids): int
{
return ScheduleHistory::whereIn('id', $ids)->delete();
}
/**
* 특정 스케줄의 모든 이력을 삭제합니다.
*
* @param int $scheduleId 스케줄 ID
* @return int 삭제된 레코드 수
*/
public function deleteByScheduleId(int $scheduleId): int
{
return ScheduleHistory::where('schedule_id', $scheduleId)->delete();
}
/**
* 특정 기간 이전의 이력을 삭제합니다.
*
* @param int $days 보관 기간 (일)
* @return int 삭제된 레코드 수
*/
public function deleteOlderThan(int $days): int
{
return ScheduleHistory::where('started_at', '<', now()->subDays($days))->delete();
}
}
+273
View File
@@ -0,0 +1,273 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\ScheduleRepositoryInterface;
use App\Helpers\PermissionHelper;
use App\Enums\ScheduleFrequency;
use App\Enums\ScheduleResultStatus;
use App\Enums\ScheduleType;
use App\Models\Schedule;
use App\Repositories\Concerns\HasMultipleSearchFilters;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
class ScheduleRepository implements ScheduleRepositoryInterface
{
use HasMultipleSearchFilters;
/**
* 검색 가능한 필드 목록
*/
private const SEARCHABLE_FIELDS = ['name', 'description', 'command'];
/**
* ID로 스케줄을 찾습니다.
*
* @param int $id 스케줄 ID
* @return Schedule|null 찾은 스케줄 모델 또는 null
*/
public function findById(int $id): ?Schedule
{
return Schedule::with('creator')->find($id);
}
/**
* 새로운 스케줄을 생성합니다.
*
* @param array $data 스케줄 생성 데이터
* @return Schedule 생성된 스케줄 모델
*/
public function create(array $data): Schedule
{
return Schedule::create($data);
}
/**
* 기존 스케줄을 업데이트합니다.
*
* @param Schedule $schedule 업데이트할 스케줄 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(Schedule $schedule, array $data): bool
{
return $schedule->update($data);
}
/**
* 스케줄을 삭제합니다.
*
* @param Schedule $schedule 삭제할 스케줄 모델
* @return bool 삭제 성공 여부
*/
public function delete(Schedule $schedule): bool
{
return $schedule->delete();
}
/**
* 모든 스케줄을 조회합니다.
*
* @return Collection 스케줄 컬렉션
*/
public function getAll(): Collection
{
return Schedule::with('creator')->get();
}
/**
* 필터링 및 페이지네이션이 적용된 스케줄 목록을 조회합니다.
*
* @param array $filters 필터 조건 배열
* @return LengthAwarePaginator 페이지네이션된 스케줄 목록
*/
public function getPaginatedSchedules(array $filters = []): LengthAwarePaginator
{
$query = Schedule::query()->with('creator');
// 권한 스코프 필터링
PermissionHelper::applyPermissionScope($query, 'core.schedules.read');
// 필터 조건 적용
$this->applyFilters($query, $filters);
// 정렬 적용
$sortBy = $filters['sort_by'] ?? 'created_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
// 페이지네이션 적용
$perPage = $filters['per_page'] ?? 15;
return $query->paginate($perPage);
}
/**
* 쿼리에 필터 조건을 적용합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param array $filters 적용할 필터 조건 배열
* @return void
*/
private function applyFilters(Builder $query, array $filters): void
{
// 다중 검색 조건 적용
if (!empty($filters['filters']) && is_array($filters['filters'])) {
$this->applyMultipleSearchFilters($query, $filters['filters'], self::SEARCHABLE_FIELDS);
}
// 타입 필터
if (!empty($filters['type'])) {
$type = ScheduleType::tryFrom($filters['type']);
if ($type) {
$query->where('type', $type);
}
}
// 주기 필터
if (!empty($filters['frequency'])) {
$frequency = ScheduleFrequency::tryFrom($filters['frequency']);
if ($frequency) {
$query->where('frequency', $frequency);
}
}
// 상태 필터
if (!empty($filters['status'])) {
if ($filters['status'] === 'active') {
$query->where('is_active', true);
} elseif ($filters['status'] === 'inactive') {
$query->where('is_active', false);
}
}
// 마지막 실행 결과 필터
if (!empty($filters['last_result'])) {
$result = ScheduleResultStatus::tryFrom($filters['last_result']);
if ($result) {
$query->where('last_result', $result);
}
}
// 중복 실행 방지 필터
if (isset($filters['without_overlapping']) && $filters['without_overlapping'] !== '') {
$query->where('without_overlapping', (bool) $filters['without_overlapping']);
}
// 점검 모드 실행 필터
if (isset($filters['run_in_maintenance']) && $filters['run_in_maintenance'] !== '') {
$query->where('run_in_maintenance', (bool) $filters['run_in_maintenance']);
}
// 확장 타입 필터
if (!empty($filters['extension_type'])) {
$query->where('extension_type', $filters['extension_type']);
if (!empty($filters['extension_identifier'])) {
$query->where('extension_identifier', $filters['extension_identifier']);
}
}
// 날짜 필터
$this->applyDateFilters($query, $filters);
}
/**
* 날짜 필터를 적용합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param array $filters 필터 조건 배열
* @return void
*/
private function applyDateFilters(Builder $query, array $filters): void
{
if (!empty($filters['created_from'])) {
$query->whereDate('created_at', '>=', $filters['created_from']);
}
if (!empty($filters['created_to'])) {
$query->whereDate('created_at', '<=', $filters['created_to']);
}
}
/**
* 스케줄 관련 통계 정보를 조회합니다.
*
* @return array 스케줄 통계 데이터 배열
*/
public function getStatistics(): array
{
return [
'total' => Schedule::count(),
'active' => Schedule::where('is_active', true)->count(),
'inactive' => Schedule::where('is_active', false)->count(),
'success' => Schedule::where('last_result', ScheduleResultStatus::Success)->count(),
'failed' => Schedule::where('last_result', ScheduleResultStatus::Failed)->count(),
'running' => Schedule::where('last_result', ScheduleResultStatus::Running)->count(),
'never_run' => Schedule::where('last_result', ScheduleResultStatus::Never)->count(),
];
}
/**
* 활성화된 스케줄들을 조회합니다.
*
* @return Collection 활성화된 스케줄 컬렉션
*/
public function getActiveSchedules(): Collection
{
return Schedule::active()->get();
}
/**
* 실행 대기 중인 스케줄들을 조회합니다.
*
* @return Collection 실행 대기 중인 스케줄 컬렉션
*/
public function getDueSchedules(): Collection
{
return Schedule::due()->get();
}
/**
* 여러 스케줄의 상태를 일괄 업데이트합니다.
*
* @param array $ids 스케줄 ID 배열
* @param bool $isActive 활성화 여부
* @return int 업데이트된 레코드 수
*/
public function bulkUpdateStatus(array $ids, bool $isActive): int
{
return Schedule::whereIn('id', $ids)->update(['is_active' => $isActive]);
}
/**
* 여러 스케줄을 일괄 삭제합니다.
*
* @param array $ids 스케줄 ID 배열
* @return int 삭제된 레코드 수
*/
public function bulkDelete(array $ids): int
{
return Schedule::whereIn('id', $ids)->delete();
}
/**
* 스케줄을 복제합니다.
*
* @param Schedule $schedule 복제할 스케줄
* @return Schedule 복제된 스케줄
*/
public function duplicate(Schedule $schedule): Schedule
{
$newSchedule = $schedule->replicate();
$newSchedule->name = $schedule->name . ' (' . __('schedule.copy') . ')';
$newSchedule->is_active = false;
$newSchedule->last_result = ScheduleResultStatus::Never;
$newSchedule->last_run_at = null;
$newSchedule->save();
return $newSchedule;
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\SystemConfigRepositoryInterface;
use App\Models\SystemConfig;
use Illuminate\Database\Eloquent\Collection;
class SystemConfigRepository implements SystemConfigRepositoryInterface
{
/**
* 모든 시스템 설정을 조회합니다.
*
* @return Collection 시스템 설정 컬렉션
*/
public function getAll(): Collection
{
return SystemConfig::all();
}
/**
* 키로 시스템 설정을 찾습니다.
*
* @param string $key 설정 키
* @return SystemConfig|null 찾은 설정 모델 또는 null
*/
public function findByKey(string $key): ?SystemConfig
{
return SystemConfig::where('key', $key)->first();
}
/**
* 새로운 시스템 설정을 생성합니다.
*
* @param array $data 설정 생성 데이터
* @return SystemConfig 생성된 설정 모델
*/
public function create(array $data): SystemConfig
{
return SystemConfig::create($data);
}
/**
* 기존 시스템 설정을 업데이트합니다.
*
* @param SystemConfig $config 업데이트할 설정 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(SystemConfig $config, array $data): bool
{
return $config->update($data);
}
/**
* 시스템 설정을 삭제합니다.
*
* @param SystemConfig $config 삭제할 설정 모델
* @return bool 삭제 성공 여부
*/
public function delete(SystemConfig $config): bool
{
return $config->delete();
}
/**
* 키로 시스템 설정을 삭제합니다.
*
* @param string $key 삭제할 설정 키
* @return bool 삭제 성공 여부
*/
public function deleteByKey(string $key): bool
{
return SystemConfig::where('key', $key)->delete() > 0;
}
/**
* 주어진 키의 시스템 설정 존재 여부를 확인합니다.
*
* @param string $key 확인할 설정 키
* @return bool 설정 존재 여부
*/
public function exists(string $key): bool
{
return SystemConfig::where('key', $key)->exists();
}
}
+225
View File
@@ -0,0 +1,225 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\TemplateRepositoryInterface;
use App\Enums\ExtensionStatus;
use App\Models\Template;
use Illuminate\Database\Eloquent\Collection;
class TemplateRepository implements TemplateRepositoryInterface
{
/**
* 모든 템플릿 조회
*/
public function getAll(?string $type = null): Collection
{
$query = Template::query()
->orderBy('created_at', 'desc');
if ($type !== null) {
$query->where('type', $type);
}
return $query->get();
}
/**
* ID로 템플릿 조회
*/
public function findById(int $id): ?Template
{
return Template::find($id);
}
/**
* identifier로 템플릿 조회
*/
public function findByIdentifier(string $identifier): ?Template
{
return Template::where('identifier', $identifier)->first();
}
/**
* 타입별 활성화된 템플릿 조회
*/
public function findActiveByType(string $type): ?Template
{
return Template::where('type', $type)
->where('status', ExtensionStatus::Active->value)
->first();
}
/**
* 템플릿 업데이트
*/
public function update(int $id, array $data): Template
{
$template = $this->findById($id);
$template->update($data);
return $template->fresh();
}
/**
* 템플릿 삭제 (Soft Delete)
*/
public function delete(int $id): bool
{
$template = $this->findById($id);
return $template->delete();
}
/**
* 특정 타입의 활성화된 모든 템플릿을 조회합니다.
*
* @param string $type 템플릿 타입 (admin, user 등)
* @return Collection 활성화된 템플릿 컬렉션
*/
public function getActiveByType(string $type): Collection
{
return Template::where('type', $type)
->where('status', ExtensionStatus::Active->value)
->get();
}
/**
* 모든 활성화된 템플릿을 조회합니다.
*
* @return Collection 모든 활성화된 템플릿 컬렉션
*/
public function getActive(): Collection
{
return Template::where('status', ExtensionStatus::Active->value)->get();
}
/**
* 모든 템플릿을 identifier로 키잉하여 조회합니다.
*
* @return Collection identifier를 키로 하는 템플릿 컬렉션
*/
public function getAllKeyedByIdentifier(): Collection
{
return Template::all()->keyBy('identifier');
}
/**
* 설치된 모든 템플릿의 identifier 목록을 조회합니다.
*
* @return array 설치된 템플릿 identifier 배열
*/
public function getInstalledIdentifiers(): array
{
return Template::pluck('identifier')->toArray();
}
/**
* 템플릿을 생성하거나 업데이트합니다.
*
* @param array $attributes 조회 조건
* @param array $values 생성/업데이트할 데이터
* @return Template 생성 또는 업데이트된 템플릿 모델
*/
public function updateOrCreate(array $attributes, array $values): Template
{
return Template::updateOrCreate($attributes, $values);
}
/**
* 식별자로 템플릿 상태를 업데이트합니다.
*
* @param string $identifier 템플릿 식별자
* @param array $data 업데이트할 데이터
* @return int 업데이트된 레코드 수
*/
public function updateByIdentifier(string $identifier, array $data): int
{
return Template::where('identifier', $identifier)->update($data);
}
/**
* 식별자로 템플릿을 삭제합니다.
*
* @param string $identifier 템플릿 식별자
* @return int 삭제된 레코드 수
*/
public function deleteByIdentifier(string $identifier): int
{
return Template::where('identifier', $identifier)->delete();
}
/**
* 특정 모듈에 의존하는 활성 템플릿을 조회합니다.
*
* DB에서 활성화된 템플릿을 조회한 후, TemplateManager를 통해
* 각 템플릿의 template.json에서 dependencies.modules를 확인하여
* 해당 모듈에 의존하는 템플릿만 필터링합니다.
*
* @param string $moduleIdentifier 모듈 식별자
* @return Collection 해당 모듈에 의존하는 활성 템플릿 컬렉션
*/
public function findActiveByModuleDependency(string $moduleIdentifier): Collection
{
// 활성화된 모든 템플릿 조회
$activeTemplates = Template::where('status', ExtensionStatus::Active->value)->get();
if ($activeTemplates->isEmpty()) {
return new Collection();
}
// TemplateManager를 통해 각 템플릿의 의존성 확인
$templateManager = app(\App\Contracts\Extension\TemplateManagerInterface::class);
return $activeTemplates->filter(function (Template $template) use ($templateManager, $moduleIdentifier) {
$templateData = $templateManager->getTemplate($template->identifier);
if (! $templateData) {
return false;
}
$dependencies = $templateData['dependencies'] ?? [];
$moduleDependencies = $dependencies['modules'] ?? [];
// 해당 모듈이 의존성에 포함되어 있는지 확인
return array_key_exists($moduleIdentifier, $moduleDependencies);
})->values();
}
/**
* 특정 플러그인에 의존하는 활성 템플릿을 조회합니다.
*
* DB에서 활성화된 템플릿을 조회한 후, TemplateManager를 통해
* 각 템플릿의 template.json에서 dependencies.plugins를 확인하여
* 해당 플러그인에 의존하는 템플릿만 필터링합니다.
*
* @param string $pluginIdentifier 플러그인 식별자
* @return Collection 해당 플러그인에 의존하는 활성 템플릿 컬렉션
*/
public function findActiveByPluginDependency(string $pluginIdentifier): Collection
{
// 활성화된 모든 템플릿 조회
$activeTemplates = Template::where('status', ExtensionStatus::Active->value)->get();
if ($activeTemplates->isEmpty()) {
return new Collection();
}
// TemplateManager를 통해 각 템플릿의 의존성 확인
$templateManager = app(\App\Contracts\Extension\TemplateManagerInterface::class);
return $activeTemplates->filter(function (Template $template) use ($templateManager, $pluginIdentifier) {
$templateData = $templateManager->getTemplate($template->identifier);
if (! $templateData) {
return false;
}
$dependencies = $templateData['dependencies'] ?? [];
$pluginDependencies = $dependencies['plugins'] ?? [];
// 해당 플러그인이 의존성에 포함되어 있는지 확인
return array_key_exists($pluginIdentifier, $pluginDependencies);
})->values();
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\UserConsentRepositoryInterface;
use App\Models\UserConsent;
use Illuminate\Database\Eloquent\Collection;
class UserConsentRepository implements UserConsentRepositoryInterface
{
public function __construct(
private UserConsent $model
) {}
/**
* 새로운 동의 이력을 기록합니다.
*
* @param array $data 동의 데이터
* @return UserConsent 생성된 동의 이력 모델
*/
public function record(array $data): UserConsent
{
return $this->model->create($data);
}
/**
* 특정 사용자의 모든 동의 이력을 조회합니다 (최신순).
*
* @param int $userId 사용자 ID
* @return Collection 동의 이력 컬렉션
*/
public function getByUser(int $userId): Collection
{
return $this->model
->where('user_id', $userId)
->orderByDesc('agreed_at')
->get();
}
/**
* 특정 사용자의 특정 유형 최신 동의 이력을 조회합니다.
*
* @param int $userId 사용자 ID
* @param string $consentType 동의 유형 (ConsentType 값)
* @return UserConsent|null 최신 동의 이력 또는 null
*/
public function getLatestByType(int $userId, string $consentType): ?UserConsent
{
return $this->model
->where('user_id', $userId)
->where('consent_type', $consentType)
->orderByDesc('agreed_at')
->first();
}
}
+223
View File
@@ -0,0 +1,223 @@
<?php
namespace App\Repositories;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\Helpers\PermissionHelper;
use App\Models\User;
use App\Repositories\Concerns\HasMultipleSearchFilters;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
class UserRepository implements UserRepositoryInterface
{
use HasMultipleSearchFilters;
/**
* 검색 가능한 필드 목록
*/
private const SEARCHABLE_FIELDS = ['name', 'email'];
/**
* 이메일로 사용자를 찾습니다.
*
* @param string $email 찾을 사용자의 이메일
* @return User|null 찾은 사용자 모델 또는 null
*/
public function findByEmail(string $email): ?User
{
return User::where('email', $email)->first();
}
/**
* 새로운 사용자를 생성합니다.
*
* @param array $data 사용자 생성 데이터
* @return User 생성된 사용자 모델
*/
public function create(array $data): User
{
return User::create($data);
}
/**
* 기존 사용자를 업데이트합니다.
*
* @param User $user 업데이트할 사용자 모델
* @param array $data 업데이트할 데이터
* @return bool 업데이트 성공 여부
*/
public function update(User $user, array $data): bool
{
return $user->update($data);
}
/**
* 사용자를 삭제합니다.
*
* @param User $user 삭제할 사용자 모델
* @return bool 삭제 성공 여부
*/
public function delete(User $user): bool
{
return $user->delete();
}
/**
* 모든 사용자를 조회합니다.
*
* @return Collection 사용자 컬렉션
*/
public function getAll(): Collection
{
return User::all();
}
/**
* ID로 사용자를 찾습니다.
*
* @param int $id 사용자 ID
* @return User|null 찾은 사용자 모델 또는 null
*/
public function findById(int $id): ?User
{
return User::find($id);
}
/**
* 필터링 및 페이지네이션이 적용된 사용자 목록을 조회합니다.
*
* @param array $filters 필터 조건 배열
* @return LengthAwarePaginator 페이지네이션된 사용자 목록
*/
public function getPaginatedUsers(array $filters = []): LengthAwarePaginator
{
$query = User::query();
// 권한 스코프 필터링
PermissionHelper::applyPermissionScope($query, 'core.users.read');
// roles 관계 eager loading
$query->with('roles');
// 검색 조건 적용
$this->applyFilters($query, $filters);
// 정렬 적용
$sortBy = $filters['sort_by'] ?? 'created_at';
$sortOrder = $filters['sort_order'] ?? 'desc';
$query->orderBy($sortBy, $sortOrder);
// 페이지네이션 적용
$perPage = $filters['per_page'] ?? 15;
return $query->paginate($perPage);
}
/**
* 쿼리에 필터 조건을 적용합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param array $filters 적용할 필터 조건 배열
*/
private function applyFilters(Builder $query, array $filters): void
{
// 다중 검색 조건 적용
if (! empty($filters['filters']) && is_array($filters['filters'])) {
$this->applyMultipleSearchFilters($query, $filters['filters'], self::SEARCHABLE_FIELDS);
}
// 날짜 필터
$this->applyDateFilters($query, $filters);
}
/**
* 날짜 필터를 적용합니다.
*
* @param Builder $query Eloquent 쿼리 빌더
* @param array $filters 필터 조건 배열
*/
private function applyDateFilters(Builder $query, array $filters): void
{
if (! empty($filters['start_date'])) {
$query->whereDate('created_at', '>=', $filters['start_date']);
}
if (! empty($filters['end_date'])) {
$query->whereDate('created_at', '<=', $filters['end_date']);
}
// 기본 날짜 필터 (전체가 아닌 경우)
if (empty($filters['start_date']) && empty($filters['end_date']) &&
($filters['date_filter'] ?? 'all') !== 'all') {
$dateFilter = $filters['date_filter'] ?? 'all';
match ($dateFilter) {
'week' => $query->where('created_at', '>=', now()->subWeek()),
'month' => $query->where('created_at', '>=', now()->subMonth()),
default => null,
};
}
}
/**
* 사용자 관련 통계 정보를 조회합니다.
*
* @return array 사용자 통계 데이터 배열
*/
public function getStatistics(): array
{
return [
'total_users' => User::count(),
'users_this_week' => User::where('created_at', '>=', now()->subWeek())->count(),
'users_this_month' => User::where('created_at', '>=', now()->subMonth())->count(),
'users_today' => User::whereDate('created_at', today())->count(),
'active_users_this_week' => User::where('last_login_at', '>=', now()->subWeek())->count(),
];
}
/**
* 키워드로 사용자를 검색합니다. (이름, 닉네임, 이메일)
*
* @param string $keyword 검색할 키워드
* @return Collection 검색된 사용자 컬렉션
*/
public function searchByKeyword(string $keyword): Collection
{
$query = User::where(function ($q) use ($keyword) {
$q->where('name', 'like', "%{$keyword}%")
->orWhere('nickname', 'like', "%{$keyword}%")
->orWhere('email', 'like', "%{$keyword}%");
});
// 권한 스코프 필터링
PermissionHelper::applyPermissionScope($query, 'core.users.read');
return $query->get();
}
/**
* 최근 등록된 사용자들을 조회합니다.
*
* @param int $limit 조회할 사용자 수 (기본값: 10)
* @return Collection 최근 사용자 컬렉션
*/
public function getRecentUsers(int $limit = 10): Collection
{
return User::orderBy('created_at', 'desc')->limit($limit)->get();
}
/**
* 언어별 사용자 수를 조회합니다.
*
* @return array 언어별 사용자 수 배열
*/
public function getUsersByLanguage(): array
{
return User::selectRaw('language, count(*) as count')
->groupBy('language')
->pluck('count', 'language')
->toArray();
}
}