v7.0.0-beta.2 release
This commit is contained in:
1 parent
6595fd0eb5
commit
fa8eba7a0d
1165 files changed
+107118
-762127
No files matched your search
@@ -10,9 +10,6 @@ use App\Enums\ConsentType;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use App\Notifications\Auth\PasswordChangedNotification;
|
||||
use App\Notifications\Auth\ResetPasswordNotification;
|
||||
use App\Notifications\Auth\WelcomeNotification;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
@@ -175,24 +172,13 @@ class AuthService
|
||||
|
||||
$token = $user->createToken('auth-token', ['*'], $this->getTokenExpiresAt())->plainTextToken;
|
||||
|
||||
// Hook 발생 (회원가입 완료)
|
||||
HookManager::doAction('core.auth.register', $user, [
|
||||
// Hook 발생 (회원가입 완료) — 알림 발송은 NotificationHookListener가 처리
|
||||
HookManager::doAction('core.auth.after_register', $user, [
|
||||
'registration_time' => now(),
|
||||
'ip_address' => request()->ip(),
|
||||
'user_agent' => request()->userAgent(),
|
||||
]);
|
||||
|
||||
// 회원가입 완료 알림 발송
|
||||
try {
|
||||
$user->notify(new WelcomeNotification);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('회원가입 완료 알림 발송 실패', [
|
||||
'user_id' => $user->id,
|
||||
'email' => $user->email,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
return [
|
||||
'user' => $user,
|
||||
'token' => $token,
|
||||
@@ -318,22 +304,19 @@ class AuthService
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
// 비밀번호 재설정 알림 발송
|
||||
try {
|
||||
$user->notify(new ResetPasswordNotification($token, $redirectPrefix));
|
||||
} catch (\Exception $e) {
|
||||
Log::error('비밀번호 재설정 이메일 발송 실패', [
|
||||
'email' => $email,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
// 리셋 URL 생성 (extract_data 필터에서 사용)
|
||||
$resetPath = $redirectPrefix
|
||||
? '/' . $redirectPrefix . '/reset-password'
|
||||
: '/reset-password';
|
||||
$resetUrl = config('app.url') . $resetPath . '?' . http_build_query([
|
||||
'token' => $token,
|
||||
'email' => $user->email,
|
||||
]);
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => [__('auth.email_send_failed')],
|
||||
]);
|
||||
}
|
||||
|
||||
// Hook 발생 (비밀번호 찾기 완료)
|
||||
HookManager::doAction('core.auth.forgot_password', $user);
|
||||
// Hook 발생 (비밀번호 재설정 요청) — 알림 발송은 NotificationHookListener가 처리
|
||||
HookManager::doAction('core.auth.after_reset_password_request', $user, [
|
||||
'reset_url' => $resetUrl,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -443,20 +426,8 @@ class AuthService
|
||||
// 사용된 토큰 삭제
|
||||
$record->delete();
|
||||
|
||||
// 비밀번호 변경 완료 알림 발송
|
||||
try {
|
||||
$user->notify(new PasswordChangedNotification);
|
||||
} catch (\Exception $e) {
|
||||
// 알림 발송 실패는 로그만 남기고 계속 진행 (비밀번호는 이미 변경됨)
|
||||
Log::error('비밀번호 변경 완료 알림 발송 실패', [
|
||||
'user_id' => $user->id,
|
||||
'email' => $user->email,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
// Hook 발생 (비밀번호 재설정 완료)
|
||||
HookManager::doAction('core.auth.reset_password', $user);
|
||||
// Hook 발생 (비밀번호 변경 완료) — 알림 발송은 NotificationHookListener가 처리
|
||||
HookManager::doAction('core.auth.after_password_changed', $user);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 범용 캐시 서비스
|
||||
*
|
||||
* 시스템 전반에서 사용되는 캐시를 일관되게 관리합니다.
|
||||
* ServiceProvider register() 시점에서도 안전하게 사용할 수 있습니다.
|
||||
*/
|
||||
class CacheService
|
||||
{
|
||||
/**
|
||||
* 캐시 키 prefix
|
||||
*/
|
||||
private const PREFIX = 'g7';
|
||||
|
||||
/**
|
||||
* 기본 TTL (24시간)
|
||||
*/
|
||||
private const DEFAULT_TTL = 86400;
|
||||
|
||||
/**
|
||||
* 캐시 키 생성
|
||||
*
|
||||
* @param string $group 캐시 그룹 (예: 'modules', 'plugins', 'templates')
|
||||
* @param string $key 캐시 키
|
||||
* @return string 전체 캐시 키
|
||||
*/
|
||||
public static function key(string $group, string $key): string
|
||||
{
|
||||
return self::PREFIX.':'.$group.':'.$key;
|
||||
}
|
||||
|
||||
/**
|
||||
* DB 연결이 준비되었는지 확인합니다.
|
||||
*
|
||||
* @return bool DB 연결 가능 여부
|
||||
*/
|
||||
protected static function isDatabaseReady(): bool
|
||||
{
|
||||
try {
|
||||
DB::connection()->getPdo();
|
||||
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시에서 값을 조회하거나 콜백 결과를 캐시합니다.
|
||||
* DB 테이블이 없거나 연결 오류 시 빈 배열을 반환합니다.
|
||||
*
|
||||
* 중요: 빈 배열([])은 캐시하지 않습니다.
|
||||
* - 모듈/플러그인 활성 목록이 빈 배열로 캐시되면 리스너 등록 실패 문제 방지
|
||||
* - 빈 배열이 정상적인 상태라면 매 요청마다 DB 조회 (성능 영향 최소화)
|
||||
*
|
||||
* @param string $group 캐시 그룹
|
||||
* @param string $key 캐시 키
|
||||
* @param callable $callback 캐시 미스 시 실행할 콜백
|
||||
* @param int|null $ttl 캐시 TTL (초), null이면 기본값 사용
|
||||
* @param string|null $requiredTable 필수 테이블명 (DB 준비 상태 확인용)
|
||||
* @return mixed 캐시된 값 또는 콜백 결과
|
||||
*/
|
||||
public static function remember(
|
||||
string $group,
|
||||
string $key,
|
||||
callable $callback,
|
||||
?int $ttl = null,
|
||||
?string $requiredTable = null
|
||||
): mixed {
|
||||
// DB 테이블 확인이 필요한 경우
|
||||
if ($requiredTable !== null) {
|
||||
// DB 연결 확인
|
||||
if (! self::isDatabaseReady()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
if (! Schema::hasTable($requiredTable)) {
|
||||
return [];
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
$cacheKey = self::key($group, $key);
|
||||
$ttl = $ttl ?? self::DEFAULT_TTL;
|
||||
|
||||
try {
|
||||
// 캐시에서 값 조회
|
||||
$cached = Cache::get($cacheKey);
|
||||
if ($cached !== null) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
// 캐시 미스: 콜백 실행
|
||||
$value = $callback();
|
||||
|
||||
// 빈 배열은 캐시하지 않음 (모듈/플러그인 상태 캐시 문제 방지)
|
||||
if (is_array($value) && empty($value)) {
|
||||
Log::debug('빈 배열은 캐시하지 않음', [
|
||||
'key' => $cacheKey,
|
||||
]);
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
// 값이 있는 경우에만 캐시 저장
|
||||
Cache::put($cacheKey, $value, $ttl);
|
||||
|
||||
return $value;
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('캐시 조회 실패, 콜백 직접 실행', [
|
||||
'key' => $cacheKey,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} catch (\Exception $e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시에서 값을 조회합니다.
|
||||
*
|
||||
* @param string $group 캐시 그룹
|
||||
* @param string $key 캐시 키
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 캐시된 값 또는 기본값
|
||||
*/
|
||||
public static function get(string $group, string $key, mixed $default = null): mixed
|
||||
{
|
||||
return Cache::get(self::key($group, $key), $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시에 값을 저장합니다.
|
||||
*
|
||||
* @param string $group 캐시 그룹
|
||||
* @param string $key 캐시 키
|
||||
* @param mixed $value 저장할 값
|
||||
* @param int|null $ttl 캐시 TTL (초)
|
||||
* @return bool 저장 성공 여부
|
||||
*/
|
||||
public static function put(string $group, string $key, mixed $value, ?int $ttl = null): bool
|
||||
{
|
||||
return Cache::put(self::key($group, $key), $value, $ttl ?? self::DEFAULT_TTL);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 캐시 키를 삭제합니다.
|
||||
*
|
||||
* @param string $group 캐시 그룹
|
||||
* @param string $key 캐시 키
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public static function forget(string $group, string $key): bool
|
||||
{
|
||||
return Cache::forget(self::key($group, $key));
|
||||
}
|
||||
|
||||
/**
|
||||
* 그룹 내 여러 캐시 키를 삭제합니다.
|
||||
*
|
||||
* @param string $group 캐시 그룹
|
||||
* @param array<string> $keys 삭제할 캐시 키 배열
|
||||
* @return void
|
||||
*/
|
||||
public static function forgetMany(string $group, array $keys): void
|
||||
{
|
||||
foreach ($keys as $key) {
|
||||
self::forget($group, $key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 태그가 지원되는 경우 태그로 캐시를 삭제합니다.
|
||||
*
|
||||
* @param array<string> $tags 삭제할 태그 배열
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public static function flushTags(array $tags): bool
|
||||
{
|
||||
try {
|
||||
if (method_exists(Cache::getStore(), 'tags')) {
|
||||
Cache::tags($tags)->flush();
|
||||
|
||||
return true;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
Log::warning('태그 기반 캐시 삭제 실패', [
|
||||
'tags' => $tags,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시를 무효화하고 새로고침합니다.
|
||||
*
|
||||
* @param string $group 캐시 그룹
|
||||
* @param string $key 캐시 키
|
||||
* @param callable $callback 새 값을 생성할 콜백
|
||||
* @param int|null $ttl 캐시 TTL (초)
|
||||
* @return mixed 새로 캐시된 값
|
||||
*/
|
||||
public static function refresh(string $group, string $key, callable $callback, ?int $ttl = null): mixed
|
||||
{
|
||||
self::forget($group, $key);
|
||||
|
||||
return self::remember($group, $key, $callback, $ttl);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Notifications\ChannelReadinessCheckerInterface;
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 알림 채널 발송 준비 상태 검증 서비스
|
||||
*
|
||||
* 각 채널의 설정 완료 여부를 사전 검증합니다.
|
||||
* 코어 채널(mail, database)의 체크 로직을 내장하고,
|
||||
* 플러그인은 core.notification.channel_readiness 필터 훅으로 확장할 수 있습니다.
|
||||
*/
|
||||
class ChannelReadinessService implements ChannelReadinessCheckerInterface
|
||||
{
|
||||
/**
|
||||
* 요청 내 캐시 (동일 요청에서 반복 호출 방지).
|
||||
*
|
||||
* @var array<string, array{ready: bool, reason: string|null}>|null
|
||||
*/
|
||||
private ?array $cache = null;
|
||||
|
||||
/**
|
||||
* @param ConfigRepositoryInterface $configRepository
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly ConfigRepositoryInterface $configRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 채널이 발송 준비 상태인지 확인합니다.
|
||||
*
|
||||
* @param string $channelId 채널 식별자
|
||||
* @return bool
|
||||
*/
|
||||
public function isReady(string $channelId): bool
|
||||
{
|
||||
return $this->check($channelId)['ready'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 채널별 준비 상태와 사유를 반환합니다.
|
||||
*
|
||||
* @param string $channelId 채널 식별자
|
||||
* @return array{ready: bool, reason: string|null}
|
||||
*/
|
||||
public function check(string $channelId): array
|
||||
{
|
||||
if ($this->cache !== null && isset($this->cache[$channelId])) {
|
||||
return $this->cache[$channelId];
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->performCheck($channelId);
|
||||
} catch (\Throwable $e) {
|
||||
// 안전성: 체크 자체가 실패하면 ready=true (발송 시도 허용)
|
||||
Log::warning('ChannelReadinessService: 체크 실패, 발송 허용', [
|
||||
'channel' => $channelId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
$result = ['ready' => true, 'reason' => null];
|
||||
}
|
||||
|
||||
$this->cache ??= [];
|
||||
$this->cache[$channelId] = $result;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 여러 채널의 준비 상태를 일괄 반환합니다.
|
||||
*
|
||||
* @param array<string> $channelIds 채널 ID 배열
|
||||
* @return array<string, array{ready: bool, reason: string|null}>
|
||||
*/
|
||||
public function checkAll(array $channelIds): array
|
||||
{
|
||||
$results = [];
|
||||
foreach ($channelIds as $id) {
|
||||
$results[$id] = $this->check($id);
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 채널별 체크 로직을 실행합니다.
|
||||
*
|
||||
* 코어 채널은 내부 메서드로, 플러그인 채널은 훅으로 처리합니다.
|
||||
*
|
||||
* @param string $channelId 채널 식별자
|
||||
* @return array{ready: bool, reason: string|null}
|
||||
*/
|
||||
private function performCheck(string $channelId): array
|
||||
{
|
||||
// 코어 채널 체크
|
||||
$result = match ($channelId) {
|
||||
'mail' => $this->checkMail(),
|
||||
'database' => $this->checkDatabase(),
|
||||
default => ['ready' => true, 'reason' => null],
|
||||
};
|
||||
|
||||
// 플러그인 확장: 커스텀 채널 체커 적용
|
||||
return HookManager::applyFilters(
|
||||
'core.notification.channel_readiness',
|
||||
$result,
|
||||
$channelId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 채널 준비 상태를 검증합니다.
|
||||
*
|
||||
* @return array{ready: bool, reason: string|null}
|
||||
*/
|
||||
private function checkMail(): array
|
||||
{
|
||||
$mailSettings = $this->configRepository->getCategory('mail');
|
||||
$mailer = $mailSettings['mailer'] ?? 'smtp';
|
||||
|
||||
// from_address는 모든 mailer에 공통 필수
|
||||
$fromAddress = $mailSettings['from_address'] ?? '';
|
||||
if (empty($fromAddress) || $fromAddress === 'noreply@example.com') {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.mail_from_address_not_configured'];
|
||||
}
|
||||
|
||||
return match ($mailer) {
|
||||
'smtp' => $this->checkSmtp($mailSettings),
|
||||
'mailgun' => $this->checkMailgun($mailSettings),
|
||||
'ses' => $this->checkSes($mailSettings),
|
||||
'log', 'array' => ['ready' => true, 'reason' => null],
|
||||
default => ['ready' => true, 'reason' => null],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* SMTP mailer 필수 설정을 검증합니다.
|
||||
*
|
||||
* @param array $settings 메일 설정
|
||||
* @return array{ready: bool, reason: string|null}
|
||||
*/
|
||||
private function checkSmtp(array $settings): array
|
||||
{
|
||||
if (empty($settings['host'])) {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.mail_smtp_host_empty'];
|
||||
}
|
||||
if (empty($settings['port'])) {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.mail_smtp_port_empty'];
|
||||
}
|
||||
|
||||
return ['ready' => true, 'reason' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mailgun mailer 필수 설정을 검증합니다.
|
||||
*
|
||||
* @param array $settings 메일 설정
|
||||
* @return array{ready: bool, reason: string|null}
|
||||
*/
|
||||
private function checkMailgun(array $settings): array
|
||||
{
|
||||
if (empty($settings['mailgun_domain'])) {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.mail_mailgun_domain_empty'];
|
||||
}
|
||||
if (empty($settings['mailgun_secret'])) {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.mail_mailgun_secret_empty'];
|
||||
}
|
||||
|
||||
return ['ready' => true, 'reason' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* SES mailer 필수 설정을 검증합니다.
|
||||
*
|
||||
* @param array $settings 메일 설정
|
||||
* @return array{ready: bool, reason: string|null}
|
||||
*/
|
||||
private function checkSes(array $settings): array
|
||||
{
|
||||
if (empty($settings['ses_key'])) {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.mail_ses_key_empty'];
|
||||
}
|
||||
if (empty($settings['ses_secret'])) {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.mail_ses_secret_empty'];
|
||||
}
|
||||
|
||||
return ['ready' => true, 'reason' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* database 채널 준비 상태를 검증합니다.
|
||||
*
|
||||
* @return array{ready: bool, reason: string|null}
|
||||
*/
|
||||
private function checkDatabase(): array
|
||||
{
|
||||
try {
|
||||
if (! Schema::hasTable('notifications')) {
|
||||
return ['ready' => false, 'reason' => 'notification.readiness.database_table_missing'];
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// DB 접속 실패: 안전하게 ready=true (발송 시도 허용)
|
||||
return ['ready' => true, 'reason' => null];
|
||||
}
|
||||
|
||||
return ['ready' => true, 'reason' => null];
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Concerns;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
/**
|
||||
* 메일 템플릿 서비스 공통 Trait.
|
||||
*
|
||||
* 코어/모듈 메일 템플릿 서비스에서 공통으로 사용하는 조회, 렌더링, 리셋, 캐시 로직을 제공합니다.
|
||||
* 사용하는 서비스는 $cachePrefix와 $modelClass 속성을 정의해야 합니다.
|
||||
*/
|
||||
trait HandlesMailTemplates
|
||||
{
|
||||
/**
|
||||
* 활성 템플릿을 캐시 포함으로 조회합니다.
|
||||
*
|
||||
* @param string $type 템플릿 유형
|
||||
* @return Model|null 활성 템플릿 또는 null
|
||||
*/
|
||||
public function resolveTemplate(string $type): ?Model
|
||||
{
|
||||
$cacheKey = $this->getCacheKey($type);
|
||||
|
||||
return Cache::remember($cacheKey, 3600, function () use ($type) {
|
||||
return $this->modelClass::query()->active()->byType($type)->first();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿의 변수를 치환하여 제목과 본문을 렌더링합니다.
|
||||
*
|
||||
* @param Model $template 메일 템플릿 모델
|
||||
* @param array $variables key => value 변수 맵
|
||||
* @param string|null $locale 로케일
|
||||
* @return array{subject: string, body: string} 치환된 결과
|
||||
*/
|
||||
public function renderTemplate(Model $template, array $variables, ?string $locale = null): array
|
||||
{
|
||||
return $template->replaceVariables($variables, $locale);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿을 시더 기본값으로 복원합니다.
|
||||
*
|
||||
* @param Model $template 복원 대상 템플릿
|
||||
* @param array $defaultData 기본 데이터 (subject, body, variables)
|
||||
* @return Model 복원된 템플릿
|
||||
*/
|
||||
public function resetToDefault(Model $template, array $defaultData): Model
|
||||
{
|
||||
$template->update([
|
||||
'subject' => $defaultData['subject'],
|
||||
'body' => $defaultData['body'],
|
||||
'variables' => $defaultData['variables'] ?? $template->variables,
|
||||
'is_active' => true,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$this->invalidateCache($template->type);
|
||||
|
||||
return $template->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 유형의 캐시를 무효화합니다.
|
||||
*
|
||||
* @param string $type 템플릿 유형
|
||||
* @return void
|
||||
*/
|
||||
public function invalidateCache(string $type): void
|
||||
{
|
||||
Cache::forget($this->getCacheKey($type));
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 키를 생성합니다.
|
||||
*
|
||||
* @param string $type 템플릿 유형
|
||||
* @return string 캐시 키
|
||||
*/
|
||||
private function getCacheKey(string $type): string
|
||||
{
|
||||
return $this->cachePrefix . $type;
|
||||
}
|
||||
}
|
||||
+505
-174
@@ -14,9 +14,16 @@ use App\Extension\Helpers\ExtensionRoleSyncHelper;
|
||||
use App\Extension\Helpers\FilePermissionHelper;
|
||||
use App\Extension\Helpers\GithubHelper;
|
||||
use App\Extension\UpgradeContext;
|
||||
use App\Models\MailTemplate;
|
||||
use App\Extension\Vendor\VendorInstallContext;
|
||||
use App\Extension\Vendor\VendorInstallResult;
|
||||
use App\Extension\Vendor\VendorMode;
|
||||
use App\Extension\Vendor\VendorResolver;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
@@ -180,40 +187,39 @@ class CoreUpdateService
|
||||
$owner = $matches[1];
|
||||
$repo = $matches[2];
|
||||
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}/releases/latest";
|
||||
$token = (string) (config('app.update.github_token') ?? '');
|
||||
|
||||
$token = config('app.update.github_token');
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => $this->buildGithubHeaders($token),
|
||||
'timeout' => 5,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$response = @file_get_contents($apiUrl, false, $context);
|
||||
|
||||
if ($response === false) {
|
||||
Log::warning(__('settings.core_update.log_api_call_failed'), ['url' => $apiUrl]);
|
||||
try {
|
||||
$response = Http::withHeaders([
|
||||
'User-Agent' => 'G7',
|
||||
'Accept' => 'application/vnd.github.v3+json',
|
||||
])
|
||||
->when($token !== '', fn ($r) => $r->withToken($token))
|
||||
->timeout(5)
|
||||
->connectTimeout(5)
|
||||
->get($apiUrl);
|
||||
} catch (ConnectionException $e) {
|
||||
Log::warning(__('settings.core_update.log_api_call_failed'), [
|
||||
'url' => $apiUrl,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ['version' => null, 'error' => __('settings.core_update.github_api_failed')];
|
||||
}
|
||||
|
||||
// HTTP 상태 코드 확인
|
||||
$statusCode = $this->extractHttpStatusCode($http_response_header ?? []);
|
||||
$data = json_decode($response, true);
|
||||
$apiMessage = $data['message'] ?? '';
|
||||
$statusCode = $response->status();
|
||||
$data = $response->json();
|
||||
$apiMessage = is_array($data) && isset($data['message']) ? $data['message'] : '';
|
||||
|
||||
if ($statusCode === 401 || $statusCode === 403) {
|
||||
Log::warning(__('settings.core_update.log_auth_failed'), [
|
||||
'url' => $apiUrl,
|
||||
'status' => $statusCode,
|
||||
'has_token' => ! empty($token),
|
||||
'has_token' => $token !== '',
|
||||
'api_message' => $apiMessage,
|
||||
]);
|
||||
|
||||
return ['version' => null, 'error' => empty($token)
|
||||
return ['version' => null, 'error' => $token === ''
|
||||
? __('settings.core_update.github_token_required')
|
||||
: __('settings.core_update.github_token_invalid', ['status' => $statusCode, 'message' => $apiMessage]),
|
||||
];
|
||||
@@ -236,11 +242,11 @@ class CoreUpdateService
|
||||
// 저장소 자체를 찾을 수 없음
|
||||
Log::warning(__('settings.core_update.log_not_found'), [
|
||||
'url' => $apiUrl,
|
||||
'has_token' => ! empty($token),
|
||||
'has_token' => $token !== '',
|
||||
'api_message' => $apiMessage,
|
||||
]);
|
||||
|
||||
return ['version' => null, 'error' => empty($token)
|
||||
return ['version' => null, 'error' => $token === ''
|
||||
? __('settings.core_update.github_repo_not_found_no_token', ['status' => $statusCode, 'message' => $apiMessage])
|
||||
: __('settings.core_update.github_repo_not_found', ['status' => $statusCode, 'message' => $apiMessage]),
|
||||
];
|
||||
@@ -256,7 +262,7 @@ class CoreUpdateService
|
||||
return ['version' => null, 'error' => __('settings.core_update.github_api_error', ['status' => $statusCode, 'message' => $apiMessage])];
|
||||
}
|
||||
|
||||
if (isset($data['tag_name'])) {
|
||||
if (is_array($data) && isset($data['tag_name'])) {
|
||||
return ['version' => ltrim($data['tag_name'], 'v'), 'error' => null];
|
||||
}
|
||||
|
||||
@@ -268,28 +274,6 @@ class CoreUpdateService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP 응답 헤더에서 상태 코드를 추출합니다.
|
||||
*
|
||||
* @param array $responseHeaders $http_response_header 배열
|
||||
* @return int HTTP 상태 코드
|
||||
*/
|
||||
protected function extractHttpStatusCode(array $responseHeaders): int
|
||||
{
|
||||
return GithubHelper::extractStatusCode($responseHeaders);
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub API 요청용 HTTP 헤더를 생성합니다.
|
||||
*
|
||||
* @param string $token GitHub Personal Access Token (빈 문자열이면 인증 없음)
|
||||
* @return array HTTP 헤더 배열
|
||||
*/
|
||||
protected function buildGithubHeaders(string $token = ''): array
|
||||
{
|
||||
return GithubHelper::buildHeaders($token);
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub 저장소 존재 여부를 확인합니다.
|
||||
*
|
||||
@@ -375,8 +359,7 @@ class CoreUpdateService
|
||||
|
||||
$onProgress?->__invoke('download', __('settings.core_update.downloading'));
|
||||
|
||||
$token = config('app.update.github_token');
|
||||
$authHeaders = $this->buildGithubHeaders($token);
|
||||
$token = (string) (config('app.update.github_token') ?? '');
|
||||
$extractDir = $pendingPath.DIRECTORY_SEPARATOR.'extracted';
|
||||
|
||||
// 폴백 체인: zipball(ZipArchive → unzip) → tarball(PharData)
|
||||
@@ -389,7 +372,7 @@ class CoreUpdateService
|
||||
$label = $strategy['label'];
|
||||
|
||||
// GitHub URL 해석
|
||||
$archiveUrl = $this->resolveGithubArchiveUrl($owner, $repo, $version, $archiveType, $authHeaders);
|
||||
$archiveUrl = GithubHelper::resolveArchiveUrl($owner, $repo, $version, $archiveType, $token);
|
||||
if (! $archiveUrl) {
|
||||
$onProgress?->__invoke('fallback', __('settings.core_update.archive_url_not_found', ['type' => $archiveType]));
|
||||
|
||||
@@ -400,9 +383,8 @@ class CoreUpdateService
|
||||
$archivePath = $pendingPath.DIRECTORY_SEPARATOR.'core_update'.$extension;
|
||||
|
||||
try {
|
||||
// 다운로드
|
||||
$content = $this->downloadArchive($archiveUrl, $authHeaders);
|
||||
File::put($archivePath, $content);
|
||||
// 다운로드 (Http 파사드 sink 사용 → allow_url_fopen 의존 제거)
|
||||
GithubHelper::downloadArchive($archiveUrl, $archivePath, $token);
|
||||
|
||||
$onProgress?->__invoke('extract', __('settings.core_update.extracting_with', ['method' => $label]));
|
||||
|
||||
@@ -488,66 +470,6 @@ class CoreUpdateService
|
||||
return $strategies;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub 아카이브 URL을 해석합니다 (v 접두사 유/무 모두 시도).
|
||||
*
|
||||
* @param string $owner 저장소 소유자
|
||||
* @param string $repo 저장소명
|
||||
* @param string $version 버전
|
||||
* @param string $archiveType zipball 또는 tarball
|
||||
* @param array $authHeaders 인증 헤더
|
||||
* @return string|null 유효한 아카이브 URL 또는 null
|
||||
*/
|
||||
protected function resolveGithubArchiveUrl(string $owner, string $repo, string $version, string $archiveType, array $authHeaders): ?string
|
||||
{
|
||||
$tagVariants = ["v{$version}", $version];
|
||||
|
||||
foreach ($tagVariants as $tag) {
|
||||
$testUrl = "https://api.github.com/repos/{$owner}/{$repo}/{$archiveType}/{$tag}";
|
||||
$testContext = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'HEAD',
|
||||
'header' => $authHeaders,
|
||||
'timeout' => 10,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
@file_get_contents($testUrl, false, $testContext);
|
||||
$statusCode = $this->extractHttpStatusCode($http_response_header ?? []);
|
||||
if ($statusCode === 200 || $statusCode === 302) {
|
||||
return $testUrl;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub에서 아카이브 파일을 다운로드합니다.
|
||||
*
|
||||
* @param string $url 다운로드 URL
|
||||
* @param array $authHeaders 인증 헤더
|
||||
* @return string 다운로드된 파일 내용
|
||||
*/
|
||||
protected function downloadArchive(string $url, array $authHeaders): string
|
||||
{
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => $authHeaders,
|
||||
'follow_location' => true,
|
||||
'timeout' => 120,
|
||||
],
|
||||
]);
|
||||
|
||||
$content = @file_get_contents($url, false, $context);
|
||||
if ($content === false) {
|
||||
throw new \RuntimeException(__('settings.core_update.download_failed', ['version' => basename($url)]));
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* ZipArchive를 사용하여 ZIP 파일을 압축 해제합니다.
|
||||
*
|
||||
@@ -646,6 +568,96 @@ class CoreUpdateService
|
||||
return $pendingPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 외부 ZIP 파일을 _pending으로 추출합니다.
|
||||
*
|
||||
* --zip 모드에서 사용합니다. ZIP 구조가 GitHub 릴리스 zipball(owner-repo-hash/ 래퍼)이든
|
||||
* 평탄한 G7 루트든 모두 지원합니다. 추출 후 validatePendingUpdate() 로 G7 패키지
|
||||
* 구조(composer.json + app/ + config/app.php)를 검증합니다.
|
||||
*
|
||||
* 추출 전략은 downloadUpdate() 와 동일한 폴백 체인(ZipArchive → unzip) 을 사용하며,
|
||||
* GitHub 호출은 수행하지 않습니다.
|
||||
*
|
||||
* @param string $zipPath 외부 ZIP 파일 경로
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @return string _pending 내 추출된 소스 경로 (래퍼 감지 후)
|
||||
*
|
||||
* @throws \RuntimeException ZIP 미존재 / 추출 실패 / 패키지 검증 실패 시
|
||||
*/
|
||||
public function extractZipToPending(string $zipPath, ?\Closure $onProgress = null): string
|
||||
{
|
||||
if (! File::exists($zipPath)) {
|
||||
throw new \RuntimeException(__('settings.core_update.zip_file_not_found', ['path' => $zipPath]));
|
||||
}
|
||||
|
||||
$pendingPath = $this->createPendingDirectory();
|
||||
$extractDir = $pendingPath.DIRECTORY_SEPARATOR.'extracted';
|
||||
File::ensureDirectoryExists($extractDir);
|
||||
|
||||
$strategies = $this->buildExtractionStrategies();
|
||||
if (empty($strategies)) {
|
||||
throw new \RuntimeException(__('settings.core_update.no_extract_method_available'));
|
||||
}
|
||||
|
||||
$lastError = null;
|
||||
foreach ($strategies as $strategy) {
|
||||
$method = $strategy['method'];
|
||||
$label = $strategy['label'];
|
||||
|
||||
$onProgress?->__invoke('extract', __('settings.core_update.extracting_with', ['method' => $label]));
|
||||
|
||||
try {
|
||||
// 전 전략 잔여물 제거
|
||||
if (File::isDirectory($extractDir)) {
|
||||
File::deleteDirectory($extractDir);
|
||||
}
|
||||
File::ensureDirectoryExists($extractDir);
|
||||
|
||||
$this->$method($zipPath, $extractDir);
|
||||
|
||||
$sourcePath = $this->resolveExtractedRoot($extractDir);
|
||||
|
||||
$onProgress?->__invoke('validate', __('settings.core_update.validating'));
|
||||
$this->validatePendingUpdate($sourcePath);
|
||||
|
||||
return $sourcePath;
|
||||
} catch (\Throwable $e) {
|
||||
$lastError = $e;
|
||||
$onProgress?->__invoke('fallback', __('settings.core_update.extract_fallback', [
|
||||
'method' => $label,
|
||||
'error' => $e->getMessage(),
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
throw new \RuntimeException(
|
||||
__('settings.core_update.all_extract_methods_failed'),
|
||||
0,
|
||||
$lastError
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 추출 디렉토리에서 G7 소스 루트를 판별합니다.
|
||||
*
|
||||
* - 하위에 디렉토리 1개, 파일 0개 → 래퍼 디렉토리(GitHub zipball 등) → 하위 반환
|
||||
* - 그 외 → extractDir 자체를 반환 (composer.json 등이 루트에 있다고 가정)
|
||||
*
|
||||
* @param string $extractDir 추출 대상 디렉토리
|
||||
* @return string 확장 소스 디렉토리 경로
|
||||
*/
|
||||
protected function resolveExtractedRoot(string $extractDir): string
|
||||
{
|
||||
$dirs = File::directories($extractDir);
|
||||
$files = File::files($extractDir);
|
||||
|
||||
if (count($dirs) === 1 && count($files) === 0) {
|
||||
return $dirs[0];
|
||||
}
|
||||
|
||||
return $extractDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 핵심 파일을 백업합니다.
|
||||
*
|
||||
@@ -712,6 +724,55 @@ class CoreUpdateService
|
||||
$this->executeComposerInstall($pendingPath, $onProgress, noScripts: true);
|
||||
}
|
||||
|
||||
/**
|
||||
* _pending 디렉토리의 vendor/ 를 구성합니다 (VendorResolver 경유).
|
||||
*
|
||||
* VendorMode에 따라:
|
||||
* - Composer: 기존 흐름 재사용 (runComposerInstallInPending + copyVendorFromPending)
|
||||
* - Bundled: vendor-bundle.zip 추출 (pending 디렉토리에 배치 후 운영 vendor로 복사 필요)
|
||||
* - Auto: EnvironmentDetector 기반 자동 결정
|
||||
*
|
||||
* 본 메서드 완료 후 vendor/ 는 _pending 내부에 위치하며,
|
||||
* 이후 copyVendorFromPending() 또는 bundle 내장 vendor 직접 사용으로 운영 반영됨.
|
||||
*
|
||||
* @param string $pendingPath _pending 내 소스 경로
|
||||
* @param VendorMode $mode 요청된 vendor 설치 모드
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
*
|
||||
* @throws \RuntimeException 실행 실패 시
|
||||
*/
|
||||
public function runVendorInstallInPending(
|
||||
string $pendingPath,
|
||||
VendorMode $mode = VendorMode::Auto,
|
||||
?\Closure $onProgress = null,
|
||||
): VendorInstallResult {
|
||||
$resolver = App::make(VendorResolver::class);
|
||||
|
||||
$context = new VendorInstallContext(
|
||||
target: 'core',
|
||||
identifier: null,
|
||||
sourceDir: $pendingPath,
|
||||
targetDir: $pendingPath,
|
||||
requestedMode: $mode,
|
||||
composerBinaryHint: config('process.composer_binary'),
|
||||
operation: 'update',
|
||||
);
|
||||
|
||||
// Composer 전략 시 기존 코어 로직을 콜백으로 전달 (코드 중복 방지)
|
||||
$composerExecutor = function (VendorInstallContext $ctx) use ($onProgress): VendorInstallResult {
|
||||
$this->runComposerInstallInPending($ctx->sourceDir, $onProgress);
|
||||
|
||||
return new VendorInstallResult(
|
||||
mode: VendorMode::Composer,
|
||||
strategy: 'composer',
|
||||
packageCount: 0,
|
||||
details: ['pending_path' => $ctx->sourceDir],
|
||||
);
|
||||
};
|
||||
|
||||
return $resolver->install($context, $composerExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* _pending과 운영 디렉토리의 composer.json/composer.lock이 동일한지 확인합니다.
|
||||
*
|
||||
@@ -795,9 +856,14 @@ class CoreUpdateService
|
||||
|
||||
$onProgress?->__invoke('vendor', 'vendor 디렉토리 복사 중...');
|
||||
|
||||
// 기존 vendor 삭제
|
||||
// 기존 vendor/ 내용만 비움 — 디렉토리 자체는 유지하여 공유 호스팅에서
|
||||
// 프로젝트 루트 쓰기 권한이 없어도 작동하도록 한다.
|
||||
// (File::deleteDirectory($destVendor) 는 vendor/ 자체를 삭제하므로
|
||||
// base_path() 에 쓰기 권한이 있어야 하는 문제를 회피)
|
||||
if (File::isDirectory($destVendor)) {
|
||||
File::deleteDirectory($destVendor);
|
||||
File::cleanDirectory($destVendor);
|
||||
} else {
|
||||
File::ensureDirectoryExists($destVendor);
|
||||
}
|
||||
|
||||
FilePermissionHelper::copyDirectory($sourceVendor, $destVendor, $onProgress);
|
||||
@@ -898,7 +964,9 @@ class CoreUpdateService
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
otherAttributes: [
|
||||
'type' => PermissionType::Admin,
|
||||
'type' => isset($moduleConfig['type'])
|
||||
? PermissionType::from($moduleConfig['type'])
|
||||
: PermissionType::Admin,
|
||||
'order' => $moduleConfig['order'],
|
||||
'parent_id' => null,
|
||||
],
|
||||
@@ -911,6 +979,22 @@ class CoreUpdateService
|
||||
$categories = $permConfig['categories'];
|
||||
|
||||
foreach ($categories as $categoryData) {
|
||||
// 카테고리 type 결정 우선순위:
|
||||
// 1. 카테고리에 명시적 type 필드
|
||||
// 2. 모든 하위 권한이 동일한 type → 그 type
|
||||
// 3. 그 외 → admin (기본값)
|
||||
$childTypes = collect($categoryData['permissions'] ?? [])
|
||||
->map(fn ($p) => $p['type'] ?? 'admin')
|
||||
->unique();
|
||||
|
||||
$categoryType = ($childTypes->count() === 1 && $childTypes->first() === 'user')
|
||||
? PermissionType::User
|
||||
: PermissionType::Admin;
|
||||
|
||||
if (isset($categoryData['type'])) {
|
||||
$categoryType = PermissionType::from($categoryData['type']);
|
||||
}
|
||||
|
||||
$category = $roleSyncHelper->syncPermission(
|
||||
identifier: $categoryData['identifier'],
|
||||
newName: $categoryData['name'],
|
||||
@@ -918,13 +1002,18 @@ class CoreUpdateService
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
otherAttributes: [
|
||||
'type' => PermissionType::Admin,
|
||||
'type' => $categoryType,
|
||||
'order' => $categoryData['order'],
|
||||
'parent_id' => $coreModule->id,
|
||||
],
|
||||
);
|
||||
|
||||
foreach ($categoryData['permissions'] as $permData) {
|
||||
// 개별 권한 type: 명시 우선, 없으면 카테고리 type 상속
|
||||
$permissionType = isset($permData['type'])
|
||||
? PermissionType::from($permData['type'])
|
||||
: $categoryType;
|
||||
|
||||
$roleSyncHelper->syncPermission(
|
||||
identifier: $permData['identifier'],
|
||||
newName: $permData['name'],
|
||||
@@ -932,9 +1021,11 @@ class CoreUpdateService
|
||||
extensionType: ExtensionOwnerType::Core,
|
||||
extensionIdentifier: 'core',
|
||||
otherAttributes: [
|
||||
'type' => PermissionType::Admin,
|
||||
'type' => $permissionType,
|
||||
'order' => $permData['order'],
|
||||
'parent_id' => $category->id,
|
||||
'resource_route_key' => $permData['resource_route_key'] ?? null,
|
||||
'owner_key' => $permData['owner_key'] ?? null,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -972,9 +1063,38 @@ class CoreUpdateService
|
||||
}
|
||||
|
||||
// 3. 역할-권한 할당 동기화 (user_overrides 보호)
|
||||
$roleSyncHelper->syncAllRoleAssignments($permissionRoleMap, $allLeafIdentifiers);
|
||||
// 코어: core/core 소유 전체 권한을 diff 범위로 사용해 이관된 구 식별자도 detach 가능
|
||||
$allCorePermIdentifiers = app(\App\Contracts\Repositories\PermissionRepositoryInterface::class)
|
||||
->getByExtension(ExtensionOwnerType::Core, 'core')
|
||||
->pluck('identifier')
|
||||
->all();
|
||||
$roleSyncHelper->syncAllRoleAssignments($permissionRoleMap, $allCorePermIdentifiers);
|
||||
|
||||
Log::info('코어 역할/권한 동기화 완료');
|
||||
// 완전 동기화: config 에서 제거된 stale 권한 삭제 (user_overrides 보존)
|
||||
// leaf + 카테고리 + 모듈 레벨 식별자를 모두 수집해서 diff
|
||||
$allDefinedIdentifiers = array_merge(
|
||||
[$moduleConfig['identifier']],
|
||||
array_column($categories, 'identifier'),
|
||||
$allLeafIdentifiers,
|
||||
);
|
||||
$deletedPerms = $roleSyncHelper->cleanupStalePermissions(
|
||||
ExtensionOwnerType::Core,
|
||||
'core',
|
||||
$allDefinedIdentifiers,
|
||||
);
|
||||
|
||||
// 완전 동기화: config 에서 제거된 stale 역할 삭제 (user_overrides + user_roles 참조 보존)
|
||||
$definedRoleIdentifiers = array_column($coreRoles, 'identifier');
|
||||
$deletedRoles = $roleSyncHelper->cleanupStaleRoles(
|
||||
ExtensionOwnerType::Core,
|
||||
'core',
|
||||
$definedRoleIdentifiers,
|
||||
);
|
||||
|
||||
Log::info('코어 역할/권한 동기화 완료', [
|
||||
'stale_permissions_deleted' => $deletedPerms,
|
||||
'stale_roles_deleted' => $deletedRoles,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1000,59 +1120,62 @@ class CoreUpdateService
|
||||
);
|
||||
}
|
||||
|
||||
Log::info('코어 메뉴 동기화 완료');
|
||||
// 완전 동기화: config 에서 제거된 stale 메뉴 삭제 (user_overrides 보존)
|
||||
$currentSlugs = $menuSyncHelper->collectSlugsRecursive($coreMenus);
|
||||
$deleted = $menuSyncHelper->cleanupStaleMenus(
|
||||
ExtensionOwnerType::Core,
|
||||
'core',
|
||||
$currentSlugs,
|
||||
);
|
||||
|
||||
Log::info('코어 메뉴 동기화 완료', ['stale_deleted' => $deleted]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 메일 템플릿을 동기화합니다.
|
||||
* 디스크의 config/core.php 를 재로드하고 코어 권한/메뉴를 재동기화합니다.
|
||||
*
|
||||
* MailTemplateSeeder와 달리 기존 데이터를 삭제하지 않고,
|
||||
* user_overrides를 확인하여 사용자 커스터마이징을 보존합니다.
|
||||
* Laravel 은 프로세스 시작 시점에 로드한 config 를 재로드하지 않으므로,
|
||||
* 업데이트로 config/core.php 가 교체되어도 현재 프로세스의 `config('core.*')`
|
||||
* 는 이전 값을 반환한다. 본 메서드는 디스크 값을 다시 require 하여 Config
|
||||
* Repository 에 주입한 뒤 syncCoreRolesAndPermissions/syncCoreMenus 를
|
||||
* 재호출하여 신규 권한·메뉴를 DB 에 반영한다.
|
||||
*
|
||||
* - 신규 템플릿 (type 기준): 생성
|
||||
* - 기존 템플릿: user_overrides에 없는 필드(subject, body, is_active)만 갱신
|
||||
* - variables: 항상 최신 정의로 덮어쓰기 (사용자 수정 대상 아님)
|
||||
* 주 사용처: CoreUpdateCommand Step 10 에서 별도 프로세스 spawn 이
|
||||
* 실패했을 때의 in-process fallback. 수동 복구 도구로도 사용 가능.
|
||||
*
|
||||
* ⚠ 경로 A(beta.1 → beta.2) 에서는 직접 호출 금지. beta.1 메모리에는
|
||||
* 본 메서드가 존재하지 않으므로 Fatal 발생. 해당 경로의 upgrade step 은
|
||||
* 파일 내부 로컬 로직으로 config 재로드 + sync 재호출을 직접 구현해야 한다.
|
||||
*/
|
||||
public function syncCoreMailTemplates(): void
|
||||
public function reloadCoreConfigAndResync(): void
|
||||
{
|
||||
$coreTemplates = $this->getCoreMailTemplateDefinitions();
|
||||
$path = config_path('core.php');
|
||||
if (! File::exists($path)) {
|
||||
Log::warning('reloadCoreConfigAndResync: config/core.php 미존재 — 스킵');
|
||||
|
||||
foreach ($coreTemplates as $templateDef) {
|
||||
$existing = MailTemplate::where('type', $templateDef['type'])->first();
|
||||
|
||||
if (! $existing) {
|
||||
// 신규 생성
|
||||
MailTemplate::create(array_merge($templateDef, [
|
||||
'is_default' => true,
|
||||
'is_active' => true,
|
||||
]));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 기존 템플릿 업데이트: user_overrides에 없는 필드만 갱신
|
||||
$userOverrides = $existing->user_overrides ?? [];
|
||||
|
||||
$updateData = [
|
||||
'variables' => $templateDef['variables'] ?? $existing->variables,
|
||||
];
|
||||
|
||||
if (! in_array('subject', $userOverrides, true)) {
|
||||
$updateData['subject'] = $templateDef['subject'];
|
||||
}
|
||||
|
||||
if (! in_array('body', $userOverrides, true)) {
|
||||
$updateData['body'] = $templateDef['body'];
|
||||
}
|
||||
|
||||
if (! in_array('is_active', $userOverrides, true) && isset($templateDef['is_active'])) {
|
||||
$updateData['is_active'] = $templateDef['is_active'];
|
||||
}
|
||||
|
||||
$existing->update($updateData);
|
||||
return;
|
||||
}
|
||||
|
||||
Log::info('코어 메일 템플릿 동기화 완료');
|
||||
$fresh = require $path;
|
||||
if (! is_array($fresh)) {
|
||||
Log::warning('reloadCoreConfigAndResync: config/core.php 반환값이 배열이 아님 — 스킵');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
config(['core' => $fresh]);
|
||||
|
||||
try {
|
||||
$this->syncCoreRolesAndPermissions();
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('reloadCoreConfigAndResync: 권한 재동기화 실패', ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
try {
|
||||
$this->syncCoreMenus();
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('reloadCoreConfigAndResync: 메뉴 재동기화 실패', ['error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1062,8 +1185,9 @@ class CoreUpdateService
|
||||
* @param string $fromVersion 시작 버전
|
||||
* @param string $toVersion 종료 버전
|
||||
* @param \Closure|null $onStep 각 스텝 실행 시 콜백 (버전 문자열 전달)
|
||||
* @param bool $force true 시 fromVersion == toVersion이면 해당 버전 스텝도 포함
|
||||
*/
|
||||
public function runUpgradeSteps(string $fromVersion, string $toVersion, ?\Closure $onStep = null): void
|
||||
public function runUpgradeSteps(string $fromVersion, string $toVersion, ?\Closure $onStep = null, bool $force = false): void
|
||||
{
|
||||
$upgradesPath = base_path('upgrades');
|
||||
|
||||
@@ -1071,6 +1195,9 @@ class CoreUpdateService
|
||||
return;
|
||||
}
|
||||
|
||||
// force + 동일 버전: 해당 버전의 스텝도 포함 (>= 비교)
|
||||
$sameVersion = version_compare($fromVersion, $toVersion, '==');
|
||||
|
||||
$steps = [];
|
||||
$files = File::files($upgradesPath);
|
||||
|
||||
@@ -1090,7 +1217,11 @@ class CoreUpdateService
|
||||
$version .= '-'.str_replace('_', '.', $matches[4]);
|
||||
}
|
||||
|
||||
if (version_compare($version, $fromVersion, '>') && version_compare($version, $toVersion, '<=')) {
|
||||
$included = $force && $sameVersion
|
||||
? version_compare($version, $toVersion, '==')
|
||||
: version_compare($version, $fromVersion, '>') && version_compare($version, $toVersion, '<=');
|
||||
|
||||
if ($included) {
|
||||
require_once $file->getPathname();
|
||||
$className = "App\\Upgrades\\{$filename}";
|
||||
|
||||
@@ -1286,6 +1417,215 @@ class CoreUpdateService
|
||||
Artisan::call('extension:update-autoload');
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 업그레이드 컨텍스트의 번들 확장 업데이트 감지.
|
||||
*
|
||||
* `_bundled/{id}/{manifest}.json` 의 version 과 DB 에 설치된 현재 version 을
|
||||
* 직접 비교하여 "번들에 최신 버전이 포함된" 확장 목록을 반환한다.
|
||||
*
|
||||
* `Manager::checkXxxUpdate()` 와의 차이:
|
||||
* - 일반 update 커맨드용 `checkXxxUpdate()` 는 GitHub 엄격 우선 정책
|
||||
* (GitHub URL 조회 성공 시 _bundled 폴백 없음)
|
||||
* - 본 메서드는 **코어 업그레이드 후 _bundled 자동 반영** 용도이므로
|
||||
* GitHub 상태와 무관하게 _bundled 버전만 기준으로 판정
|
||||
* - beta.2 가 GitHub 미릴리스 상태에서도 _bundled 신버전을 정확히 감지
|
||||
*
|
||||
* 호출처:
|
||||
* - `BundledExtensionUpdatePrompt::collectBundledUpdates()` (beta.2+ 프롬프트)
|
||||
* - `Upgrade_7_0_0_beta_2::spawnResyncInlineLocal()` inline PHP (beta.1 → beta.2 경로 C)
|
||||
*
|
||||
* @return array{
|
||||
* modules: array<int, array{identifier:string, current_version:string, latest_version:string, update_source:string}>,
|
||||
* plugins: array<int, array{identifier:string, current_version:string, latest_version:string, update_source:string}>,
|
||||
* templates: array<int, array{identifier:string, current_version:string, latest_version:string, update_source:string}>
|
||||
* }
|
||||
*/
|
||||
public function collectBundledExtensionUpdates(): array
|
||||
{
|
||||
return [
|
||||
'modules' => $this->detectBundledUpdatesFor('modules', 'module.json'),
|
||||
'plugins' => $this->detectBundledUpdatesFor('plugins', 'plugin.json'),
|
||||
'templates' => $this->detectBundledUpdatesFor('templates', 'template.json'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 확장 타입의 _bundled 업데이트 목록을 조회합니다.
|
||||
*
|
||||
* @param string $tableAndDir 'modules' | 'plugins' | 'templates' (DB 테이블명 + 디렉토리명 일치 전제)
|
||||
* @param string $manifestName 'module.json' | 'plugin.json' | 'template.json'
|
||||
* @return array<int, array{identifier:string, current_version:string, latest_version:string, update_source:string}>
|
||||
*/
|
||||
private function detectBundledUpdatesFor(string $tableAndDir, string $manifestName): array
|
||||
{
|
||||
if (! \Illuminate\Support\Facades\Schema::hasTable($tableAndDir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$results = [];
|
||||
foreach (DB::table($tableAndDir)->get(['identifier', 'version']) as $record) {
|
||||
$identifier = (string) $record->identifier;
|
||||
$current = (string) $record->version;
|
||||
$bundledPath = base_path($tableAndDir.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.$identifier.DIRECTORY_SEPARATOR.$manifestName);
|
||||
|
||||
if (! is_file($bundledPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$manifest = json_decode((string) file_get_contents($bundledPath), true);
|
||||
$bundled = is_array($manifest) ? ($manifest['version'] ?? null) : null;
|
||||
|
||||
if ($bundled === null || version_compare((string) $bundled, $current, '<=')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$results[] = [
|
||||
'identifier' => $identifier,
|
||||
'current_version' => $current,
|
||||
'latest_version' => (string) $bundled,
|
||||
'update_source' => 'bundled',
|
||||
];
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 업데이트 시작 시점의 원본 소유자·그룹을 스냅샷합니다.
|
||||
*
|
||||
* 이 스냅샷은 업데이트 종료 시점 `restoreOwnership()` 에 전달되어 각 경로를
|
||||
* **원래 자신의 소유자** 로 정확히 복원한다. base_path 기준 통일 방식과 달리
|
||||
* 비대칭 환경(예: 루트=someuser, vendor=www-data) 에서도 원본을 유지한다.
|
||||
*
|
||||
* 대상 경로는 config('app.update.restore_ownership') 에 정의된 목록.
|
||||
* chown 미지원 환경(Windows 등) 은 빈 배열을 반환한다.
|
||||
*
|
||||
* @return array<string, array{owner:int|false, group:int|false}> target => {owner, group}
|
||||
*/
|
||||
public function snapshotOwnership(): array
|
||||
{
|
||||
$targets = config('app.update.restore_ownership', ['vendor']);
|
||||
|
||||
return $this->snapshotOwnershipFor($targets);
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정한 경로 목록의 소유자·그룹을 스냅샷합니다.
|
||||
*
|
||||
* 확장 업데이트(모듈/플러그인/템플릿) 에서 업데이트 전 해당 확장 스코프의
|
||||
* 경로만 스냅샷하고 싶을 때 사용. 예: `['bootstrap/cache', "modules/{$id}"]`.
|
||||
* 본 메서드 결과는 `restoreOwnership()` 에 그대로 전달 가능.
|
||||
*
|
||||
* @param array $paths base_path() 기준 상대 경로 배열
|
||||
* @return array<string, array{owner:int|false, group:int|false}>
|
||||
*/
|
||||
public function snapshotOwnershipFor(array $paths): array
|
||||
{
|
||||
if (! function_exists('chown')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$snapshot = [];
|
||||
foreach ($paths as $target) {
|
||||
$path = base_path($target);
|
||||
if (! File::exists($path) && ! File::isDirectory($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$snapshot[$target] = [
|
||||
'owner' => @fileowner($path),
|
||||
'group' => @filegroup($path),
|
||||
];
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* 업데이트 경로의 소유권을 스냅샷 기준으로 복원합니다.
|
||||
*
|
||||
* sudo 로 실행된 외부 프로세스(composer install, package:discover,
|
||||
* extension:update-autoload 등)가 root 소유로 생성한 파일을 **업데이트 전의
|
||||
* 각 경로 원본 소유자** 로 되돌린다. 스냅샷은 `snapshotOwnership()` 로 업데이트
|
||||
* 초반에 수집하여 전달한다.
|
||||
*
|
||||
* 동작 원칙:
|
||||
* - target 별로 스냅샷에 기록된 원본 owner/group 을 기준으로 재귀 chown
|
||||
* - 스냅샷에 없거나 수집 실패(false)한 target 은 `FilePermissionHelper::inferWebServerOwnership()`
|
||||
* 의 웹서버 계정 추정값으로 fallback (storage 등 웹서버 쓰기 디렉토리 기준)
|
||||
* - 이미 일치하는 항목은 no-op
|
||||
* - 소유권만 복원, 퍼미션은 건드리지 않음
|
||||
* - @chown/@chgrp suppress 로 권한 부족 시 silent fail
|
||||
* - 대상 경로 목록은 config('app.update.restore_ownership') 기준
|
||||
*
|
||||
* @param array<string, array{owner:int|false, group:int|false}> $snapshot snapshotOwnership() 결과
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
* @return void
|
||||
*/
|
||||
public function restoreOwnership(array $snapshot, ?\Closure $onProgress = null): void
|
||||
{
|
||||
if (! function_exists('chown')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 스냅샷이 제공되면 그 키를 복원 대상 범위로 사용 (스코프 복원).
|
||||
// 스냅샷이 비어있으면 전체 config 범위로 fallback (기존 동작 유지).
|
||||
$targets = ! empty($snapshot)
|
||||
? array_keys($snapshot)
|
||||
: config('app.update.restore_ownership', ['vendor']);
|
||||
$restoredCount = 0;
|
||||
$fallbackOwner = null;
|
||||
$fallbackGroup = null;
|
||||
$fallbackSource = null;
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$path = base_path($target);
|
||||
if (! File::exists($path) && ! File::isDirectory($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 1순위: 스냅샷의 원본 소유자
|
||||
$owner = $snapshot[$target]['owner'] ?? false;
|
||||
$group = $snapshot[$target]['group'] ?? false;
|
||||
$source = 'snapshot';
|
||||
|
||||
// 2순위: inferWebServerOwnership fallback
|
||||
if ($owner === false) {
|
||||
if ($fallbackOwner === null) {
|
||||
[$fallbackOwner, $fallbackGroup, $fallbackSource] = FilePermissionHelper::inferWebServerOwnership();
|
||||
}
|
||||
$owner = $fallbackOwner;
|
||||
$group = $fallbackGroup;
|
||||
$source = 'infer:'.$fallbackSource;
|
||||
}
|
||||
|
||||
if ($owner === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$onProgress?->__invoke('ownership', $target);
|
||||
$changed = FilePermissionHelper::chownRecursive($path, $owner, $group);
|
||||
|
||||
if ($changed > 0) {
|
||||
Log::info('코어 업데이트: 소유권 복원', [
|
||||
'target' => $target,
|
||||
'owner' => $owner,
|
||||
'group' => $group,
|
||||
'source' => $source,
|
||||
'changed_entries' => $changed,
|
||||
]);
|
||||
$restoredCount += $changed;
|
||||
}
|
||||
}
|
||||
|
||||
if ($restoredCount > 0) {
|
||||
Log::info('코어 업데이트: 소유권 복원 완료', [
|
||||
'restored_entries_total' => $restoredCount,
|
||||
'targets' => $targets,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 업데이트 실패 리포트를 생성합니다.
|
||||
*
|
||||
@@ -1360,13 +1700,4 @@ class CoreUpdateService
|
||||
return config('core.menus', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* 코어 메일 템플릿 정의를 반환합니다.
|
||||
*
|
||||
* @return array 메일 템플릿 정의 배열
|
||||
*/
|
||||
protected function getCoreMailTemplateDefinitions(): array
|
||||
{
|
||||
return config('core.mail_templates', []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Repositories\JsonConfigRepository;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 코어 드라이버 레지스트리 서비스
|
||||
*
|
||||
* 코어 환경설정의 드라이버 영역(스토리지, 캐시, 세션, 큐, 로그, 웹소켓, 메일)을
|
||||
* 관리합니다. 플러그인이 필터 훅으로 새 드라이버를 등록할 수 있으며,
|
||||
* 플러그인 비활성화 시 기본 드라이버로 안전하게 폴백합니다.
|
||||
*/
|
||||
class DriverRegistryService
|
||||
{
|
||||
/**
|
||||
* 카테고리별 코어 드라이버 목록
|
||||
*
|
||||
* @var array<string, array<array{id: string, label: array{ko: string, en: string}}>>
|
||||
*/
|
||||
private const CORE_DRIVERS = [
|
||||
'storage' => [
|
||||
['id' => 'local', 'label' => ['ko' => '로컬', 'en' => 'Local']],
|
||||
['id' => 's3', 'label' => ['ko' => 'Amazon S3', 'en' => 'Amazon S3']],
|
||||
],
|
||||
'cache' => [
|
||||
['id' => 'file', 'label' => ['ko' => '파일', 'en' => 'File']],
|
||||
['id' => 'redis', 'label' => ['ko' => 'Redis', 'en' => 'Redis']],
|
||||
],
|
||||
'session' => [
|
||||
['id' => 'file', 'label' => ['ko' => '파일', 'en' => 'File']],
|
||||
['id' => 'database', 'label' => ['ko' => '데이터베이스', 'en' => 'Database']],
|
||||
['id' => 'redis', 'label' => ['ko' => 'Redis', 'en' => 'Redis']],
|
||||
],
|
||||
'queue' => [
|
||||
['id' => 'sync', 'label' => ['ko' => '동기', 'en' => 'Sync']],
|
||||
['id' => 'database', 'label' => ['ko' => '데이터베이스', 'en' => 'Database']],
|
||||
['id' => 'redis', 'label' => ['ko' => 'Redis', 'en' => 'Redis']],
|
||||
],
|
||||
'log' => [
|
||||
['id' => 'single', 'label' => ['ko' => '단일 파일', 'en' => 'Single File']],
|
||||
['id' => 'daily', 'label' => ['ko' => '일별 파일', 'en' => 'Daily File']],
|
||||
],
|
||||
'websocket' => [
|
||||
['id' => 'reverb', 'label' => ['ko' => 'Laravel Reverb', 'en' => 'Laravel Reverb']],
|
||||
],
|
||||
'mail' => [
|
||||
['id' => 'smtp', 'label' => ['ko' => 'SMTP', 'en' => 'SMTP']],
|
||||
['id' => 'mailgun', 'label' => ['ko' => 'Mailgun', 'en' => 'Mailgun']],
|
||||
['id' => 'ses', 'label' => ['ko' => 'SES (Amazon)', 'en' => 'SES (Amazon)']],
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* 카테고리별 기본 폴백 드라이버
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const DEFAULT_DRIVERS = [
|
||||
'storage' => 'local',
|
||||
'cache' => 'file',
|
||||
'session' => 'database',
|
||||
'queue' => 'database',
|
||||
'log' => 'daily',
|
||||
'websocket' => '',
|
||||
'mail' => 'smtp',
|
||||
];
|
||||
|
||||
/**
|
||||
* 카테고리별 Laravel Config 키 매핑
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const CONFIG_KEYS = [
|
||||
'storage' => 'filesystems.default',
|
||||
'cache' => 'cache.default',
|
||||
'session' => 'session.driver',
|
||||
'queue' => 'queue.default',
|
||||
'log' => 'logging.default',
|
||||
'websocket' => 'broadcasting.default',
|
||||
'mail' => 'mail.default',
|
||||
];
|
||||
|
||||
/**
|
||||
* 카테고리별 JSON 설정 키 매핑 (JsonConfigRepository 카테고리 + 키)
|
||||
*
|
||||
* @var array<string, array{category: string, key: string}>
|
||||
*/
|
||||
private const SETTINGS_KEYS = [
|
||||
'storage' => ['category' => 'drivers', 'key' => 'storage_driver'],
|
||||
'cache' => ['category' => 'drivers', 'key' => 'cache_driver'],
|
||||
'session' => ['category' => 'drivers', 'key' => 'session_driver'],
|
||||
'queue' => ['category' => 'drivers', 'key' => 'queue_driver'],
|
||||
'log' => ['category' => 'drivers', 'key' => 'log_driver'],
|
||||
'websocket' => ['category' => 'drivers', 'key' => 'websocket_driver'],
|
||||
'mail' => ['category' => 'mail', 'key' => 'mailer'],
|
||||
];
|
||||
|
||||
/**
|
||||
* 필터 훅 이름 접두사
|
||||
*/
|
||||
private const HOOK_PREFIX = 'core.settings.available_';
|
||||
|
||||
/**
|
||||
* 필터 훅 이름 접미사
|
||||
*/
|
||||
private const HOOK_SUFFIX = '_drivers';
|
||||
|
||||
/**
|
||||
* 특정 카테고리의 사용 가능한 드라이버 목록을 반환합니다.
|
||||
*
|
||||
* 코어 드라이버 + 플러그인 필터 훅으로 추가된 드라이버를 병합합니다.
|
||||
*
|
||||
* @param string $category 드라이버 카테고리 (storage, cache, session, queue, log, websocket, mail)
|
||||
* @return array<array{id: string, label: array{ko: string, en: string}, provider?: string}> 사용 가능한 드라이버 배열
|
||||
*/
|
||||
public function getAvailableDrivers(string $category): array
|
||||
{
|
||||
$coreDrivers = self::CORE_DRIVERS[$category] ?? [];
|
||||
|
||||
$hookName = self::HOOK_PREFIX.$category.self::HOOK_SUFFIX;
|
||||
|
||||
return HookManager::applyFilters($hookName, $coreDrivers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 카테고리의 사용 가능한 드라이버 목록을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<array{id: string, label: array{ko: string, en: string}, provider?: string}>>
|
||||
*/
|
||||
public function getAllAvailableDrivers(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach (array_keys(self::CORE_DRIVERS) as $category) {
|
||||
$result[$category] = $this->getAvailableDrivers($category);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 드라이버가 코어 드라이버인지 확인합니다.
|
||||
*
|
||||
* @param string $category 드라이버 카테고리
|
||||
* @param string $driverId 드라이버 ID
|
||||
* @return bool 코어 드라이버이면 true
|
||||
*/
|
||||
public function isCoreDriver(string $category, string $driverId): bool
|
||||
{
|
||||
$coreDrivers = self::CORE_DRIVERS[$category] ?? [];
|
||||
|
||||
foreach ($coreDrivers as $driver) {
|
||||
if ($driver['id'] === $driverId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 드라이버가 현재 사용 가능한지 확인합니다.
|
||||
*
|
||||
* 코어 드라이버이거나, 플러그인 필터 훅으로 등록된 드라이버인 경우 true.
|
||||
*
|
||||
* @param string $category 드라이버 카테고리
|
||||
* @param string $driverId 드라이버 ID
|
||||
* @return bool 사용 가능하면 true
|
||||
*/
|
||||
public function isDriverAvailable(string $category, string $driverId): bool
|
||||
{
|
||||
$availableDrivers = $this->getAvailableDrivers($category);
|
||||
|
||||
foreach ($availableDrivers as $driver) {
|
||||
if ($driver['id'] === $driverId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리별 기본 폴백 드라이버 ID를 반환합니다.
|
||||
*
|
||||
* @param string $category 드라이버 카테고리
|
||||
* @return string 기본 드라이버 ID
|
||||
*/
|
||||
public function getDefaultDriver(string $category): string
|
||||
{
|
||||
return self::DEFAULT_DRIVERS[$category] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 플러그인이 제공하는 드라이버 중 현재 사용 중인 것을 반환합니다.
|
||||
*
|
||||
* @param string $pluginIdentifier 플러그인 식별자 (예: sirsoft-custom_mail)
|
||||
* @return array<array{category: string, driver_id: string}> 사용 중인 드라이버 목록
|
||||
*/
|
||||
public function getPluginProvidedDriversInUse(string $pluginIdentifier): array
|
||||
{
|
||||
$inUse = [];
|
||||
|
||||
$configRepository = app(JsonConfigRepository::class);
|
||||
|
||||
foreach (self::SETTINGS_KEYS as $category => $settingKey) {
|
||||
$settings = $configRepository->getCategory($settingKey['category']);
|
||||
$selectedDriver = $settings[$settingKey['key']] ?? '';
|
||||
|
||||
if (empty($selectedDriver)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 코어 드라이버면 스킵
|
||||
if ($this->isCoreDriver($category, $selectedDriver)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 필터 훅으로 등록된 드라이버 중 해당 플러그인이 제공하는지 확인
|
||||
$availableDrivers = $this->getAvailableDrivers($category);
|
||||
|
||||
foreach ($availableDrivers as $driver) {
|
||||
if ($driver['id'] === $selectedDriver && ($driver['provider'] ?? '') === $pluginIdentifier) {
|
||||
$inUse[] = [
|
||||
'category' => $category,
|
||||
'driver_id' => $selectedDriver,
|
||||
];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $inUse;
|
||||
}
|
||||
|
||||
/**
|
||||
* 지원되는 카테고리 목록을 반환합니다.
|
||||
*
|
||||
* @return array<string> 카테고리 이름 배열
|
||||
*/
|
||||
public function getCategories(): array
|
||||
{
|
||||
return array_keys(self::CORE_DRIVERS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리에 해당하는 JSON 설정 키 정보를 반환합니다.
|
||||
*
|
||||
* @param string $category 드라이버 카테고리
|
||||
* @return array{category: string, key: string}|null 설정 키 정보 또는 null
|
||||
*/
|
||||
public function getSettingsKey(string $category): ?array
|
||||
{
|
||||
return self::SETTINGS_KEYS[$category] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리에 해당하는 Laravel Config 키를 반환합니다.
|
||||
*
|
||||
* @param string $category 드라이버 카테고리
|
||||
* @return string|null Config 키 또는 null
|
||||
*/
|
||||
public function getConfigKey(string $category): ?string
|
||||
{
|
||||
return self::CONFIG_KEYS[$category] ?? null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* MaxMind GeoLite2 데이터베이스 관리 서비스.
|
||||
*
|
||||
* 다운로드/압축 해제/원자적 교체/메타데이터 기록을 담당합니다.
|
||||
* GeoIpService(IP → 타임존 조회)와 책임이 분리되어 있습니다.
|
||||
*/
|
||||
class GeoIpDatabaseService
|
||||
{
|
||||
public function __construct(
|
||||
private ConfigRepositoryInterface $configRepository
|
||||
) {}
|
||||
|
||||
/**
|
||||
* MaxMind GeoLite2 DB를 다운로드하여 원자적으로 교체합니다.
|
||||
*
|
||||
* @param bool $force 파일이 이미 존재해도 재다운로드
|
||||
* @return array{success: bool, status: string, message?: string, data?: array<string, mixed>}
|
||||
* status: 'updated' | 'skipped' | 'missing_license_key' | 'download_failed' |
|
||||
* 'unauthorized' | 'extract_failed' | 'file_not_found' | 'replace_failed' |
|
||||
* 'connection_failed' | 'empty_response'
|
||||
*/
|
||||
public function updateDatabase(bool $force = false): array
|
||||
{
|
||||
$licenseKey = (string) config('geoip.license_key', '');
|
||||
|
||||
if ($licenseKey === '') {
|
||||
return [
|
||||
'success' => false,
|
||||
'status' => 'missing_license_key',
|
||||
'message' => 'MaxMind 라이선스 키가 설정되지 않았습니다.',
|
||||
];
|
||||
}
|
||||
|
||||
$finalPath = (string) config('geoip.database_path');
|
||||
|
||||
// 최근 업데이트 건너뛰기 (force 없이, 24시간 이내)
|
||||
if (! $force && File::exists($finalPath)) {
|
||||
$ageSeconds = time() - File::lastModified($finalPath);
|
||||
if ($ageSeconds < 86400) {
|
||||
return [
|
||||
'success' => true,
|
||||
'status' => 'skipped',
|
||||
'message' => sprintf('최근 %d시간 전에 업데이트되었습니다.', (int) floor($ageSeconds / 3600)),
|
||||
'data' => $this->getDatabaseStatus(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$editionId = (string) config('geoip.download.edition_id', 'GeoLite2-City');
|
||||
|
||||
// Before 훅: 확장이 업데이트 시작 시점에 부가 작업을 수행할 수 있음
|
||||
HookManager::doAction('core.geoip.database.before_update', [
|
||||
'edition_id' => $editionId,
|
||||
'force' => $force,
|
||||
]);
|
||||
|
||||
// Filter 훅: 확장이 다운로드 옵션을 변형할 수 있음 (edition_id, base_url 등 오버라이드 가능)
|
||||
$downloadContext = HookManager::applyFilters('core.geoip.database.filter_download_context', [
|
||||
'edition_id' => $editionId,
|
||||
'base_url' => (string) config('geoip.download.base_url', 'https://download.maxmind.com/app/geoip_download'),
|
||||
'timeout' => (int) config('geoip.download.timeout', 120),
|
||||
'retry_attempts' => (int) config('geoip.download.retry_attempts', 3),
|
||||
'retry_delay_ms' => (int) config('geoip.download.retry_delay_ms', 10000),
|
||||
'user_agent' => (string) config('geoip.download.user_agent', 'g7-core/1.0'),
|
||||
]);
|
||||
|
||||
$url = $this->buildDownloadUrl($licenseKey, (string) $downloadContext['edition_id'], (string) $downloadContext['base_url']);
|
||||
|
||||
$geoipDir = dirname($finalPath);
|
||||
$tmpDir = $geoipDir.DIRECTORY_SEPARATOR.'.tmp';
|
||||
$archivePath = $tmpDir.DIRECTORY_SEPARATOR.$editionId.'.tar.gz';
|
||||
$extractPath = $tmpDir.DIRECTORY_SEPARATOR.'extract';
|
||||
|
||||
try {
|
||||
$this->prepareDirectories($geoipDir, $tmpDir, $extractPath);
|
||||
|
||||
$startedAt = microtime(true);
|
||||
|
||||
// 1. 다운로드
|
||||
$downloadResult = $this->downloadArchive($url, $archivePath, $downloadContext);
|
||||
if (! $downloadResult['success']) {
|
||||
HookManager::doAction('core.geoip.database.after_update_failed', $downloadResult);
|
||||
|
||||
return $downloadResult;
|
||||
}
|
||||
|
||||
// 2. 압축 해제
|
||||
$extractResult = $this->extractArchive($archivePath, $extractPath);
|
||||
if (! $extractResult['success']) {
|
||||
HookManager::doAction('core.geoip.database.after_update_failed', $extractResult);
|
||||
|
||||
return $extractResult;
|
||||
}
|
||||
|
||||
// 3. mmdb 파일 탐색
|
||||
$extractedMmdb = $this->findMmdbFile($extractPath, $editionId);
|
||||
if ($extractedMmdb === null) {
|
||||
$result = [
|
||||
'success' => false,
|
||||
'status' => 'file_not_found',
|
||||
'message' => '압축 파일 내부에서 mmdb 파일을 찾을 수 없습니다.',
|
||||
];
|
||||
HookManager::doAction('core.geoip.database.after_update_failed', $result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
// 4. 원자적 교체
|
||||
if (! @rename($extractedMmdb, $finalPath)) {
|
||||
$result = [
|
||||
'success' => false,
|
||||
'status' => 'replace_failed',
|
||||
'message' => 'mmdb 파일을 최종 경로로 이동할 수 없습니다.',
|
||||
];
|
||||
HookManager::doAction('core.geoip.database.after_update_failed', $result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
// 5. 메타데이터 갱신
|
||||
$this->updateLastUpdatedAt();
|
||||
|
||||
$elapsed = round(microtime(true) - $startedAt, 2);
|
||||
$finalSize = File::size($finalPath);
|
||||
|
||||
Log::info('GeoIP DB updated successfully', [
|
||||
'path' => $finalPath,
|
||||
'size_bytes' => $finalSize,
|
||||
'elapsed_seconds' => $elapsed,
|
||||
]);
|
||||
|
||||
$result = [
|
||||
'success' => true,
|
||||
'status' => 'updated',
|
||||
'message' => 'GeoIP DB 업데이트가 완료되었습니다.',
|
||||
'data' => [
|
||||
'database_path' => $finalPath,
|
||||
'file_size_bytes' => $finalSize,
|
||||
'elapsed_seconds' => $elapsed,
|
||||
'last_updated_at' => date('c', File::lastModified($finalPath)),
|
||||
],
|
||||
];
|
||||
|
||||
// After 훅: 확장이 업데이트 완료 시점에 부가 작업 수행 (캐시 워밍, 알림 등)
|
||||
HookManager::doAction('core.geoip.database.after_update', $result);
|
||||
|
||||
return $result;
|
||||
} finally {
|
||||
// 임시 파일 정리 (성공/실패 무관)
|
||||
if (File::isDirectory($tmpDir)) {
|
||||
File::deleteDirectory($tmpDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 DB 파일의 상태 정보를 반환합니다.
|
||||
*
|
||||
* @return array{exists: bool, database_path: string, file_size_bytes: int, last_updated_at: ?string}
|
||||
*/
|
||||
public function getDatabaseStatus(): array
|
||||
{
|
||||
$finalPath = (string) config('geoip.database_path');
|
||||
$exists = File::exists($finalPath);
|
||||
|
||||
return [
|
||||
'exists' => $exists,
|
||||
'database_path' => $finalPath,
|
||||
'file_size_bytes' => $exists ? File::size($finalPath) : 0,
|
||||
'last_updated_at' => $exists ? date('c', File::lastModified($finalPath)) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 라이선스 키 설정 여부를 확인합니다.
|
||||
*
|
||||
* @return bool 설정 여부
|
||||
*/
|
||||
public function isLicenseKeyConfigured(): bool
|
||||
{
|
||||
return (string) config('geoip.license_key', '') !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 다운로드 URL(dry-run용 마스킹 포함)을 반환합니다.
|
||||
*
|
||||
* @param bool $masked true면 라이선스 키를 마스킹
|
||||
* @return string 다운로드 URL
|
||||
*/
|
||||
public function buildDownloadUrlForDisplay(bool $masked = true): string
|
||||
{
|
||||
$licenseKey = (string) config('geoip.license_key', '');
|
||||
$editionId = (string) config('geoip.download.edition_id', 'GeoLite2-City');
|
||||
$url = $this->buildDownloadUrl($licenseKey, $editionId);
|
||||
|
||||
if ($masked && $licenseKey !== '') {
|
||||
return str_replace($licenseKey, $this->maskKey($licenseKey), $url);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 라이선스 키의 앞 4자만 남기고 나머지를 마스킹합니다.
|
||||
*
|
||||
* @param string $key 원본 키
|
||||
* @return string 마스킹된 키
|
||||
*/
|
||||
public function maskKey(string $key): string
|
||||
{
|
||||
$length = strlen($key);
|
||||
if ($length <= 4) {
|
||||
return str_repeat('*', $length);
|
||||
}
|
||||
|
||||
return substr($key, 0, 4).str_repeat('*', $length - 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다운로드 URL을 조합합니다.
|
||||
*
|
||||
* @param string $licenseKey 라이선스 키
|
||||
* @param string $editionId 에디션 ID (예: GeoLite2-City)
|
||||
* @param string|null $baseUrl 베이스 URL (null이면 config 기본값)
|
||||
* @return string 전체 URL
|
||||
*/
|
||||
private function buildDownloadUrl(string $licenseKey, string $editionId, ?string $baseUrl = null): string
|
||||
{
|
||||
$baseUrl ??= (string) config('geoip.download.base_url', 'https://download.maxmind.com/app/geoip_download');
|
||||
|
||||
return sprintf('%s?edition_id=%s&license_key=%s&suffix=tar.gz', $baseUrl, $editionId, $licenseKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 작업 디렉토리를 준비합니다.
|
||||
*
|
||||
* @param string $geoipDir GeoIP 최종 디렉토리
|
||||
* @param string $tmpDir 임시 디렉토리
|
||||
* @param string $extractPath 추출 경로
|
||||
*/
|
||||
private function prepareDirectories(string $geoipDir, string $tmpDir, string $extractPath): void
|
||||
{
|
||||
if (! File::isDirectory($geoipDir)) {
|
||||
File::makeDirectory($geoipDir, 0755, true);
|
||||
}
|
||||
if (File::isDirectory($tmpDir)) {
|
||||
File::deleteDirectory($tmpDir);
|
||||
}
|
||||
File::makeDirectory($tmpDir, 0755, true);
|
||||
File::makeDirectory($extractPath, 0755, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 아카이브를 다운로드합니다.
|
||||
*
|
||||
* @param string $url 다운로드 URL
|
||||
* @param string $archivePath 저장 경로
|
||||
* @param array<string, mixed> $context 다운로드 옵션 (filter 훅으로 변형된 컨텍스트)
|
||||
* @return array{success: bool, status: string, message?: string} 결과 배열
|
||||
*/
|
||||
private function downloadArchive(string $url, string $archivePath, array $context): array
|
||||
{
|
||||
$timeout = (int) ($context['timeout'] ?? 120);
|
||||
$retryAttempts = (int) ($context['retry_attempts'] ?? 3);
|
||||
$retryDelayMs = (int) ($context['retry_delay_ms'] ?? 10000);
|
||||
$userAgent = (string) ($context['user_agent'] ?? 'g7-core/1.0');
|
||||
|
||||
try {
|
||||
// retry의 기본 $throw=true는 4xx/5xx 시 RequestException을 던집니다.
|
||||
// 우리는 응답을 받아 직접 상태 코드를 검사해야 하므로 throw=false를 지정합니다.
|
||||
$response = Http::withHeaders(['User-Agent' => $userAgent])
|
||||
->timeout($timeout)
|
||||
->retry($retryAttempts, $retryDelayMs, null, false)
|
||||
->sink($archivePath)
|
||||
->get($url);
|
||||
} catch (\Illuminate\Http\Client\ConnectionException $e) {
|
||||
return [
|
||||
'success' => false,
|
||||
'status' => 'connection_failed',
|
||||
'message' => '다운로드 연결 실패: '.$e->getMessage(),
|
||||
];
|
||||
}
|
||||
|
||||
if ($response->status() === 401) {
|
||||
return [
|
||||
'success' => false,
|
||||
'status' => 'unauthorized',
|
||||
'message' => '라이선스 키가 유효하지 않습니다. (HTTP 401)',
|
||||
];
|
||||
}
|
||||
|
||||
if (! $response->successful()) {
|
||||
return [
|
||||
'success' => false,
|
||||
'status' => 'download_failed',
|
||||
'message' => sprintf('다운로드 실패: HTTP %d', $response->status()),
|
||||
];
|
||||
}
|
||||
|
||||
if (! File::exists($archivePath) || File::size($archivePath) === 0) {
|
||||
return [
|
||||
'success' => false,
|
||||
'status' => 'empty_response',
|
||||
'message' => '다운로드된 파일이 비어 있습니다.',
|
||||
];
|
||||
}
|
||||
|
||||
return ['success' => true, 'status' => 'ok'];
|
||||
}
|
||||
|
||||
/**
|
||||
* tar.gz 아카이브를 추출합니다.
|
||||
*
|
||||
* @param string $archivePath 아카이브 경로
|
||||
* @param string $extractPath 추출 대상 경로
|
||||
* @return array{success: bool, status: string, message?: string} 결과 배열
|
||||
*/
|
||||
private function extractArchive(string $archivePath, string $extractPath): array
|
||||
{
|
||||
try {
|
||||
$phar = new \PharData($archivePath);
|
||||
$phar->extractTo($extractPath, null, true);
|
||||
} catch (\Throwable $e) {
|
||||
return [
|
||||
'success' => false,
|
||||
'status' => 'extract_failed',
|
||||
'message' => '압축 해제 실패: '.$e->getMessage(),
|
||||
];
|
||||
}
|
||||
|
||||
return ['success' => true, 'status' => 'ok'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 추출된 디렉토리에서 mmdb 파일을 찾습니다.
|
||||
*
|
||||
* MaxMind 아카이브는 `GeoLite2-City_YYYYMMDD/GeoLite2-City.mmdb` 형식입니다.
|
||||
*
|
||||
* @param string $extractPath 추출 경로
|
||||
* @param string $editionId 에디션 ID
|
||||
* @return string|null mmdb 파일 경로 또는 null
|
||||
*/
|
||||
private function findMmdbFile(string $extractPath, string $editionId): ?string
|
||||
{
|
||||
$pattern = $extractPath.DIRECTORY_SEPARATOR.$editionId.'_*'.DIRECTORY_SEPARATOR.$editionId.'.mmdb';
|
||||
$found = glob($pattern);
|
||||
|
||||
return ! empty($found) ? $found[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* settings의 cache 카테고리에 geoip_last_updated_at을 기록합니다.
|
||||
*/
|
||||
private function updateLastUpdatedAt(): void
|
||||
{
|
||||
try {
|
||||
$current = $this->configRepository->getCategory('geoip');
|
||||
$current['last_updated_at'] = now()->toIso8601String();
|
||||
$this->configRepository->saveCategory('geoip', $current);
|
||||
|
||||
// Laravel config 캐시 재로드 강제
|
||||
Artisan::call('config:clear');
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('GeoIP last_updated_at 갱신 실패', ['error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,17 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use GeoIp2\Database\Reader;
|
||||
use GeoIp2\Exception\AddressNotFoundException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class GeoIpService
|
||||
{
|
||||
private ?Reader $reader = null;
|
||||
|
||||
public function __construct(private CacheInterface $cache) {}
|
||||
|
||||
/**
|
||||
* IP 주소로부터 타임존을 조회합니다.
|
||||
*
|
||||
@@ -25,10 +27,12 @@ class GeoIpService
|
||||
return null;
|
||||
}
|
||||
|
||||
// 캐시 확인
|
||||
if (config('geoip.cache.enabled', true)) {
|
||||
$cacheKey = config('geoip.cache.prefix', 'geoip.timezone.').$ip;
|
||||
$cached = Cache::get($cacheKey);
|
||||
// 캐시 확인 (g7_core_settings 우선, fallback config)
|
||||
$cacheEnabled = (bool) g7_core_settings('cache.geoip_enabled', config('geoip.cache.enabled', true));
|
||||
$cacheKey = 'geoip.timezone.'.$ip;
|
||||
|
||||
if ($cacheEnabled) {
|
||||
$cached = $this->cache->get($cacheKey);
|
||||
|
||||
if ($cached !== null) {
|
||||
// 빈 문자열은 이전 조회 실패를 의미
|
||||
@@ -45,9 +49,9 @@ class GeoIpService
|
||||
$timezone = $this->lookupTimezone($ip);
|
||||
|
||||
// 캐시 저장 (조회 실패 시에도 빈 문자열 저장하여 반복 조회 방지)
|
||||
if (config('geoip.cache.enabled', true)) {
|
||||
$ttl = config('geoip.cache.ttl', 86400);
|
||||
Cache::put($cacheKey, $timezone ?? '', $ttl);
|
||||
if ($cacheEnabled) {
|
||||
$ttl = (int) g7_core_settings('cache.geoip_ttl', config('geoip.cache.ttl', 86400));
|
||||
$this->cache->put($cacheKey, $timezone ?? '', $ttl);
|
||||
}
|
||||
|
||||
// 지원 타임존 확인
|
||||
|
||||
@@ -279,13 +279,17 @@ class LayoutExtensionService
|
||||
$content = $extension->content;
|
||||
$mode = $content['mode'] ?? 'append';
|
||||
|
||||
// 컴포넌트 추가 (extension_point props를 주입 컴포넌트에 전달)
|
||||
// 컴포넌트 추가 (extension_point props/callbacks를 주입 컴포넌트에 전달)
|
||||
if (isset($content['components'])) {
|
||||
$extensionPointProps = $component['props'] ?? [];
|
||||
$componentsWithProps = array_map(function ($injectedComponent) use ($extensionPointProps) {
|
||||
$extensionPointCallbacks = $component['callbacks'] ?? [];
|
||||
$componentsWithProps = array_map(function ($injectedComponent) use ($extensionPointProps, $extensionPointCallbacks) {
|
||||
if (! empty($extensionPointProps)) {
|
||||
$injectedComponent['extensionPointProps'] = $extensionPointProps;
|
||||
}
|
||||
if (! empty($extensionPointCallbacks)) {
|
||||
$injectedComponent['extensionPointCallbacks'] = $extensionPointCallbacks;
|
||||
}
|
||||
|
||||
return $injectedComponent;
|
||||
}, $content['components']);
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\LayoutRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Models\TemplateLayout;
|
||||
use Composer\Semver\Semver;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
@@ -32,7 +32,8 @@ class LayoutResolverService
|
||||
*/
|
||||
public function __construct(
|
||||
private LayoutRepositoryInterface $layoutRepository,
|
||||
private ModuleManager $moduleManager
|
||||
private ModuleManager $moduleManager,
|
||||
private CacheInterface $cache
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -40,7 +41,7 @@ class LayoutResolverService
|
||||
*/
|
||||
private function getCacheTtl(): int
|
||||
{
|
||||
return config('template.layout.cache_ttl', 3600);
|
||||
return (int) g7_core_settings('cache.layout_ttl', config('template.layout.cache_ttl', 3600));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,7 +61,7 @@ class LayoutResolverService
|
||||
|
||||
// 캐시 확인
|
||||
$cacheKey = $this->getResolutionCacheKey($layoutName, $templateId);
|
||||
$cachedId = Cache::get($cacheKey);
|
||||
$cachedId = $this->cache->get($cacheKey);
|
||||
|
||||
if ($cachedId !== null) {
|
||||
$this->cacheStats['hits']++;
|
||||
@@ -101,7 +102,7 @@ class LayoutResolverService
|
||||
// 캐시에 결과 저장 (없는 경우 0으로 저장하여 null 구분)
|
||||
$cacheValue = $layout ? $layout->id : 0;
|
||||
$cacheTtl = $this->getCacheTtl();
|
||||
Cache::put($cacheKey, $cacheValue, $cacheTtl);
|
||||
$this->cache->put($cacheKey, $cacheValue, $cacheTtl);
|
||||
|
||||
Log::info('레이아웃 해석 완료 및 캐싱', [
|
||||
'layout_name' => $layoutName,
|
||||
@@ -254,7 +255,7 @@ class LayoutResolverService
|
||||
HookManager::doAction('core.layout_resolver.before_cache_clear', $layoutName, $templateId);
|
||||
|
||||
$cacheKey = $this->getResolutionCacheKey($layoutName, $templateId);
|
||||
Cache::forget($cacheKey);
|
||||
$this->cache->forget($cacheKey);
|
||||
|
||||
Log::info('레이아웃 해석 캐시 무효화', [
|
||||
'layout_name' => $layoutName,
|
||||
@@ -279,7 +280,7 @@ class LayoutResolverService
|
||||
|
||||
foreach ($layouts as $layoutName) {
|
||||
$cacheKey = $this->getResolutionCacheKey($layoutName, $templateId);
|
||||
Cache::forget($cacheKey);
|
||||
$this->cache->forget($cacheKey);
|
||||
}
|
||||
|
||||
Log::info('템플릿의 모든 레이아웃 해석 캐시 무효화', [
|
||||
@@ -304,7 +305,7 @@ class LayoutResolverService
|
||||
|
||||
foreach ($layouts as $layout) {
|
||||
$cacheKey = $this->getResolutionCacheKey($layout->name, $layout->template_id);
|
||||
Cache::forget($cacheKey);
|
||||
$this->cache->forget($cacheKey);
|
||||
}
|
||||
|
||||
Log::info('모듈의 모든 레이아웃 해석 캐시 무효화', [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\LayoutRepositoryInterface;
|
||||
use App\Contracts\Repositories\LayoutVersionRepositoryInterface;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
@@ -12,7 +13,6 @@ use App\Helpers\PermissionHelper;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class LayoutService
|
||||
@@ -25,7 +25,8 @@ class LayoutService
|
||||
private LayoutVersionRepositoryInterface $versionRepository,
|
||||
private TemplateRepositoryInterface $templateRepository,
|
||||
private LayoutResolverService $layoutResolverService,
|
||||
private LayoutExtensionService $layoutExtensionService
|
||||
private LayoutExtensionService $layoutExtensionService,
|
||||
private CacheInterface $cache
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -38,10 +39,12 @@ class LayoutService
|
||||
|
||||
/**
|
||||
* 병합된 레이아웃 캐시 TTL을 반환합니다.
|
||||
*
|
||||
* g7_core_settings('cache.layout_ttl') 우선, 없으면 config('template.layout.cache_ttl').
|
||||
*/
|
||||
private function getCacheTtl(): int
|
||||
{
|
||||
return config('template.layout.cache_ttl', 3600);
|
||||
return (int) g7_core_settings('cache.layout_ttl', config('template.layout.cache_ttl', 3600));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -229,11 +232,20 @@ class LayoutService
|
||||
$result['errorHandling'] = $mergedErrorHandling;
|
||||
}
|
||||
|
||||
// transition_overlay 병합 (자식 우선, 부모 폴백)
|
||||
// transition_overlay 병합 (shallow merge — 자식 키가 부모 키를 override)
|
||||
// @since engine-v1.23.0
|
||||
$transitionOverlay = $childLayout['transition_overlay'] ?? $parentLayout['transition_overlay'] ?? null;
|
||||
if ($transitionOverlay !== null) {
|
||||
$result['transition_overlay'] = $transitionOverlay;
|
||||
// @since engine-v1.30.0 — shallow merge 도입. 자식이 wait_for 만 명시해도 부모의
|
||||
// enabled/style/target/spinner 가 보존되어 자식이 부분 override 가능.
|
||||
// 부모 또는 자식 어느 한쪽이라도 transition_overlay 를 정의하면 결과에 포함.
|
||||
$parentOverlay = $parentLayout['transition_overlay'] ?? null;
|
||||
$childOverlay = $childLayout['transition_overlay'] ?? null;
|
||||
if ($parentOverlay !== null || $childOverlay !== null) {
|
||||
// boolean 또는 그 외 비배열 케이스는 shallow merge 가 의미 없으므로 자식 우선/부모 폴백
|
||||
if (! is_array($parentOverlay) || ! is_array($childOverlay)) {
|
||||
$result['transition_overlay'] = $childOverlay ?? $parentOverlay;
|
||||
} else {
|
||||
$result['transition_overlay'] = array_merge($parentOverlay, $childOverlay);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 불필요한 필드 제거 (extends, slots, slot)
|
||||
@@ -607,10 +619,20 @@ class LayoutService
|
||||
// Before 훅 - 로드 전
|
||||
HookManager::doAction('core.layout.before_load', $templateId, $layoutName);
|
||||
|
||||
$cacheEnabled = (bool) g7_core_settings('cache.layout_enabled', true);
|
||||
|
||||
// 캐시 비활성 시 매번 병합 실행
|
||||
if (! $cacheEnabled) {
|
||||
$merged = $this->loadAndMergeLayoutInternal($templateId, $layoutName);
|
||||
HookManager::doAction('core.layout.after_load', $merged, $templateId, $layoutName, false);
|
||||
|
||||
return $merged;
|
||||
}
|
||||
|
||||
$cacheKey = $this->getMergedLayoutCacheKey($templateId, $layoutName);
|
||||
|
||||
// 캐시에서 시도
|
||||
$cached = Cache::get($cacheKey);
|
||||
$cached = $this->cache->get($cacheKey);
|
||||
|
||||
if ($cached !== null) {
|
||||
$this->cacheStats['hits']++;
|
||||
@@ -641,7 +663,7 @@ class LayoutService
|
||||
|
||||
// 캐시에 저장
|
||||
$cacheTtl = $this->getCacheTtl();
|
||||
Cache::put($cacheKey, $mergedLayout, $cacheTtl);
|
||||
$this->cache->put($cacheKey, $mergedLayout, $cacheTtl);
|
||||
|
||||
Log::info('레이아웃 병합 및 캐싱 완료', [
|
||||
'template_id' => $templateId,
|
||||
@@ -821,7 +843,7 @@ class LayoutService
|
||||
HookManager::doAction('core.layout.before_cache_clear', $templateId, $layoutName);
|
||||
|
||||
$cacheKey = $this->getMergedLayoutCacheKey($templateId, $layoutName);
|
||||
Cache::forget($cacheKey);
|
||||
$this->cache->forget($cacheKey);
|
||||
|
||||
// PublicLayoutController 서빙 캐시도 무효화
|
||||
// PublicLayoutController::serve()에서 "layout.{identifier}.{name}.v{version}" 키로 별도 캐싱
|
||||
@@ -860,8 +882,8 @@ class LayoutService
|
||||
}
|
||||
|
||||
$identifier = $template->identifier;
|
||||
$cacheVersion = (int) Cache::get('extension_cache_version', 0);
|
||||
Cache::forget("layout.{$identifier}.{$layoutName}.v{$cacheVersion}");
|
||||
$cacheVersion = (int) $this->cache->get('ext.cache_version', 0);
|
||||
$this->cache->forget("layout.{$identifier}.{$layoutName}.v{$cacheVersion}");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1041,10 +1063,10 @@ class LayoutService
|
||||
// 캐시 무효화
|
||||
$this->clearDependentLayoutsCache($templateId, $name);
|
||||
|
||||
// 프론트엔드 브라우저 캐시 무효화를 위해 extension_cache_version 증가
|
||||
// 프론트엔드 브라우저 캐시 무효화를 위해 ext.cache_version 증가
|
||||
// PublicLayoutController가 ?v={version} 기반 HTTP 캐시를 사용하므로
|
||||
// 버전 변경 시 브라우저가 새 URL로 인식하여 캐시를 우회합니다.
|
||||
Cache::put('extension_cache_version', time());
|
||||
$this->cache->put('ext.cache_version', time());
|
||||
|
||||
// After 훅 - 레이아웃 업데이트 후
|
||||
HookManager::doAction('core.layout.after_update', $layout, $templateId, $name, $data);
|
||||
@@ -1136,7 +1158,7 @@ class LayoutService
|
||||
$this->clearDependentLayoutsCache($templateId, $name);
|
||||
|
||||
// 프론트엔드 브라우저 캐시 무효화
|
||||
Cache::put('extension_cache_version', time());
|
||||
$this->cache->put('ext.cache_version', time());
|
||||
|
||||
// After 훅 - 버전 복원 후
|
||||
HookManager::doAction('core.layout.after_version_restore', $newVersion, $templateId, $name, $versionId);
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\MailSendLogRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Enums\MailSendStatus;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\MailSendLog;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 메일 발송 이력 서비스
|
||||
*/
|
||||
class MailSendLogService
|
||||
{
|
||||
/**
|
||||
* MailSendLogService 생성자.
|
||||
*
|
||||
* @param MailSendLogRepositoryInterface $repository 메일 발송 이력 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private MailSendLogRepositoryInterface $repository
|
||||
) {}
|
||||
|
||||
public function logSent(
|
||||
string $recipientEmail,
|
||||
?string $recipientName = null,
|
||||
?string $subject = null,
|
||||
?string $body = null,
|
||||
?string $templateType = null,
|
||||
ExtensionOwnerType $extensionType = ExtensionOwnerType::Core,
|
||||
string $extensionIdentifier = 'core',
|
||||
?string $source = null,
|
||||
?string $senderEmail = null,
|
||||
?string $senderName = null,
|
||||
): MailSendLog {
|
||||
// Before 훅
|
||||
HookManager::doAction('core.mail_send_log.before_log_sent', $recipientEmail, $templateType, $extensionIdentifier);
|
||||
|
||||
$log = $this->repository->create([
|
||||
'sender_email' => $senderEmail,
|
||||
'sender_name' => $senderName,
|
||||
'recipient_email' => $recipientEmail,
|
||||
'recipient_name' => $recipientName,
|
||||
'subject' => $subject,
|
||||
'body' => $body,
|
||||
'template_type' => $templateType,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'source' => $source,
|
||||
'status' => MailSendStatus::Sent->value,
|
||||
'sent_at' => now(),
|
||||
]);
|
||||
|
||||
// After 훅
|
||||
HookManager::doAction('core.mail_send_log.after_log_sent', $log);
|
||||
|
||||
return $log;
|
||||
}
|
||||
|
||||
public function logFailed(
|
||||
string $recipientEmail,
|
||||
?string $recipientName = null,
|
||||
?string $subject = null,
|
||||
?string $body = null,
|
||||
?string $templateType = null,
|
||||
ExtensionOwnerType $extensionType = ExtensionOwnerType::Core,
|
||||
string $extensionIdentifier = 'core',
|
||||
?string $source = null,
|
||||
?string $errorMessage = null,
|
||||
?string $senderEmail = null,
|
||||
?string $senderName = null,
|
||||
): MailSendLog {
|
||||
// Before 훅
|
||||
HookManager::doAction('core.mail_send_log.before_log_failed', $recipientEmail, $templateType, $errorMessage);
|
||||
|
||||
$log = $this->repository->create([
|
||||
'sender_email' => $senderEmail,
|
||||
'sender_name' => $senderName,
|
||||
'recipient_email' => $recipientEmail,
|
||||
'recipient_name' => $recipientName,
|
||||
'subject' => $subject,
|
||||
'body' => $body,
|
||||
'template_type' => $templateType,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'source' => $source,
|
||||
'status' => MailSendStatus::Failed->value,
|
||||
'error_message' => $errorMessage,
|
||||
'sent_at' => now(),
|
||||
]);
|
||||
|
||||
// After 훅
|
||||
HookManager::doAction('core.mail_send_log.after_log_failed', $log);
|
||||
|
||||
return $log;
|
||||
}
|
||||
|
||||
public function logSkipped(
|
||||
string $recipientEmail,
|
||||
?string $recipientName = null,
|
||||
?string $templateType = null,
|
||||
ExtensionOwnerType $extensionType = ExtensionOwnerType::Core,
|
||||
string $extensionIdentifier = 'core',
|
||||
?string $source = null,
|
||||
?string $errorMessage = null,
|
||||
?string $senderEmail = null,
|
||||
?string $senderName = null,
|
||||
): MailSendLog {
|
||||
// Before 훅
|
||||
HookManager::doAction('core.mail_send_log.before_log_skipped', $recipientEmail, $templateType, $errorMessage);
|
||||
|
||||
$log = $this->repository->create([
|
||||
'sender_email' => $senderEmail,
|
||||
'sender_name' => $senderName,
|
||||
'recipient_email' => $recipientEmail,
|
||||
'recipient_name' => $recipientName,
|
||||
'subject' => null,
|
||||
'template_type' => $templateType,
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'source' => $source,
|
||||
'status' => MailSendStatus::Skipped->value,
|
||||
'error_message' => $errorMessage,
|
||||
'sent_at' => now(),
|
||||
]);
|
||||
|
||||
// After 훅
|
||||
HookManager::doAction('core.mail_send_log.after_log_skipped', $log);
|
||||
|
||||
return $log;
|
||||
}
|
||||
|
||||
/**
|
||||
* 발송 이력 목록을 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @param int $perPage 페이지 당 항목 수
|
||||
* @return LengthAwarePaginator 페이지네이션 결과
|
||||
*/
|
||||
public function getLogs(array $filters = [], int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
return $this->repository->getPaginated($filters, $perPage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 발송 통계를 조회합니다.
|
||||
*
|
||||
* @return array{total: int, sent: int, failed: int, today: int} 통계 정보
|
||||
*/
|
||||
public function getStatistics(): array
|
||||
{
|
||||
return $this->repository->getStatistics();
|
||||
}
|
||||
|
||||
/**
|
||||
* 발송 이력을 삭제합니다.
|
||||
*
|
||||
* @param int $id 삭제할 발송 이력 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(int $id): bool
|
||||
{
|
||||
HookManager::doAction('core.mail_send_log.before_delete', $id);
|
||||
|
||||
$result = $this->repository->delete($id);
|
||||
|
||||
HookManager::doAction('core.mail_send_log.after_delete', $id);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 여러 발송 이력을 일괄 삭제합니다.
|
||||
*
|
||||
* @param array<int> $ids 삭제할 발송 이력 ID 목록
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function deleteMany(array $ids): int
|
||||
{
|
||||
HookManager::doAction('core.mail_send_log.before_delete_many', $ids);
|
||||
|
||||
$count = $this->repository->deleteMany($ids);
|
||||
|
||||
HookManager::doAction('core.mail_send_log.after_delete_many', $ids, $count);
|
||||
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\MailTemplateRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\MailTemplate;
|
||||
use App\Services\Concerns\HandlesMailTemplates;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
/**
|
||||
* 메일 템플릿 서비스
|
||||
*
|
||||
* 메일 템플릿의 조회, 수정, 미리보기, 초기화 등 비즈니스 로직을 처리합니다.
|
||||
*/
|
||||
class MailTemplateService
|
||||
{
|
||||
use HandlesMailTemplates;
|
||||
|
||||
/**
|
||||
* @var string 캐시 키 prefix
|
||||
*/
|
||||
protected string $cachePrefix = 'mail_template:core:';
|
||||
|
||||
/**
|
||||
* @var string 모델 클래스
|
||||
*/
|
||||
protected string $modelClass = MailTemplate::class;
|
||||
|
||||
/**
|
||||
* MailTemplateService 생성자.
|
||||
*
|
||||
* @param MailTemplateRepositoryInterface $repository 메일 템플릿 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private MailTemplateRepositoryInterface $repository
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 환경설정 탭용 전체 템플릿 목록을 반환합니다.
|
||||
*
|
||||
* @return Collection 메일 템플릿 컬렉션
|
||||
*/
|
||||
public function getTemplatesForSettings(): Collection
|
||||
{
|
||||
return $this->repository->getAllTemplates();
|
||||
}
|
||||
|
||||
public function updateTemplate(MailTemplate $template, array $data, ?int $userId = null): MailTemplate
|
||||
{
|
||||
// Before 훅
|
||||
HookManager::doAction('core.mail_template.before_update', $template, $data);
|
||||
|
||||
// 스냅샷 캡처 (ChangeDetector용)
|
||||
$snapshot = $template->toArray();
|
||||
|
||||
// 필터 훅 - 수정 데이터 변형
|
||||
$data = HookManager::applyFilters('core.mail_template.filter_update_data', $data, $template);
|
||||
|
||||
$updateData = [
|
||||
'subject' => $data['subject'],
|
||||
'body' => $data['body'],
|
||||
'is_active' => $data['is_active'] ?? $template->is_active,
|
||||
'is_default' => false,
|
||||
'updated_by' => $userId,
|
||||
];
|
||||
|
||||
$this->repository->update($template, $updateData);
|
||||
$this->invalidateCache($template->type);
|
||||
|
||||
$updatedTemplate = $template->fresh();
|
||||
|
||||
// After 훅 (스냅샷 전달)
|
||||
HookManager::doAction('core.mail_template.after_update', $updatedTemplate, $snapshot);
|
||||
|
||||
return $updatedTemplate;
|
||||
}
|
||||
|
||||
public function toggleActive(MailTemplate $template): MailTemplate
|
||||
{
|
||||
// Before 훅
|
||||
HookManager::doAction('core.mail_template.before_toggle_active', $template);
|
||||
|
||||
$this->repository->update($template, [
|
||||
'is_active' => ! $template->is_active,
|
||||
]);
|
||||
|
||||
$this->invalidateCache($template->type);
|
||||
|
||||
$toggledTemplate = $template->fresh();
|
||||
|
||||
// After 훅
|
||||
HookManager::doAction('core.mail_template.after_toggle_active', $toggledTemplate);
|
||||
|
||||
return $toggledTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 시더에 정의된 기본 템플릿 데이터를 반환합니다.
|
||||
*
|
||||
* @param string $type 템플릿 유형
|
||||
* @return array|null 기본 데이터 또는 null
|
||||
*/
|
||||
public function getDefaultTemplateData(string $type): ?array
|
||||
{
|
||||
$seeder = app(\Database\Seeders\MailTemplateSeeder::class);
|
||||
|
||||
$defaults = $seeder->getDefaultTemplates();
|
||||
|
||||
foreach ($defaults as $default) {
|
||||
if ($default['type'] === $type) {
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 템플릿 목록을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @param int $perPage 페이지 당 항목 수
|
||||
* @return LengthAwarePaginator 페이지네이션 결과
|
||||
*/
|
||||
public function getTemplates(array $filters = [], int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
return $this->repository->getPaginated($filters, $perPage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 미리보기용 렌더링 결과를 반환합니다.
|
||||
*
|
||||
* @param array $data 미리보기 데이터 (subject, body, variables)
|
||||
* @return array{subject: string, body: string} 렌더링 결과
|
||||
*/
|
||||
public function getPreview(array $data): array
|
||||
{
|
||||
$subject = $data['subject'] ?? '';
|
||||
$body = $data['body'] ?? '';
|
||||
$sampleVariables = [];
|
||||
|
||||
foreach ($data['variables'] ?? [] as $variable) {
|
||||
$key = $variable['key'] ?? '';
|
||||
$sampleVariables[$key] = '{'.$key.'}';
|
||||
}
|
||||
|
||||
$replacements = [];
|
||||
foreach ($sampleVariables as $key => $value) {
|
||||
$replacements['{'.$key.'}'] = $value;
|
||||
}
|
||||
|
||||
return [
|
||||
'subject' => strtr($subject, $replacements),
|
||||
'body' => strtr($body, $replacements),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -168,17 +168,28 @@ class ModuleService
|
||||
* 지정된 모듈을 업데이트합니다.
|
||||
*
|
||||
* @param string $moduleName 업데이트할 모듈 identifier
|
||||
* @param \App\Extension\Vendor\VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param string $layoutStrategy 레이아웃 전략 (overwrite|keep)
|
||||
* @return array 업데이트 결과 (identifier, from_version, to_version 등)
|
||||
*
|
||||
* @throws ValidationException 업데이트 실패 시
|
||||
*/
|
||||
public function updateModule(string $moduleName): array
|
||||
{
|
||||
public function updateModule(
|
||||
string $moduleName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
string $layoutStrategy = 'overwrite',
|
||||
): array {
|
||||
HookManager::doAction('core.modules.before_update', $moduleName);
|
||||
|
||||
try {
|
||||
$this->moduleManager->loadModules();
|
||||
$result = $this->moduleManager->updateModule($moduleName);
|
||||
$result = $this->moduleManager->updateModule(
|
||||
$moduleName,
|
||||
false,
|
||||
null,
|
||||
$vendorMode,
|
||||
$layoutStrategy,
|
||||
);
|
||||
|
||||
$moduleInfo = $this->moduleManager->getModuleInfo($moduleName);
|
||||
|
||||
@@ -198,21 +209,46 @@ class ModuleService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정된 모듈의 수정된 레이아웃을 확인합니다.
|
||||
*
|
||||
* @param string $moduleName 확인할 모듈 identifier
|
||||
* @return array{has_modified_layouts: bool, modified_count: int, modified_layouts: array}
|
||||
*
|
||||
* @throws ValidationException 확인 실패 시
|
||||
*/
|
||||
public function checkModifiedLayouts(string $moduleName): array
|
||||
{
|
||||
try {
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
return $this->moduleManager->hasModifiedLayouts($moduleName);
|
||||
} catch (\Exception $e) {
|
||||
throw ValidationException::withMessages([
|
||||
'module_name' => [__('modules.check_modified_layouts_failed', ['error' => $e->getMessage()])],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈을 시스템에 설치합니다.
|
||||
*
|
||||
* @param string $moduleName 설치할 모듈명
|
||||
* @param \App\Extension\Vendor\VendorMode $vendorMode Vendor 설치 모드
|
||||
* @return array|null 설치된 모듈 정보 또는 null
|
||||
*
|
||||
* @throws ValidationException 모듈 설치 실패 시
|
||||
*/
|
||||
public function installModule(string $moduleName): ?array
|
||||
{
|
||||
public function installModule(
|
||||
string $moduleName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
bool $force = false,
|
||||
): ?array {
|
||||
HookManager::doAction('core.modules.before_install', $moduleName);
|
||||
|
||||
try {
|
||||
$this->moduleManager->loadModules();
|
||||
$result = $this->moduleManager->installModule($moduleName);
|
||||
$result = $this->moduleManager->installModule($moduleName, null, $vendorMode, $force);
|
||||
|
||||
if ($result) {
|
||||
// 설치 후 모듈 정보 반환
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class NotificationChannelService
|
||||
{
|
||||
/**
|
||||
* 확장 × 채널 조합별 전역 활성 여부 메모이제이션 캐시.
|
||||
*
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
private array $channelEnabledCache = [];
|
||||
|
||||
/**
|
||||
* 사용 가능한 알림 채널 목록을 반환합니다.
|
||||
*
|
||||
* config 기본 채널 + Filter 훅으로 플러그인 채널 확장 가능.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getAvailableChannels(): array
|
||||
{
|
||||
$defaultChannels = config('notification.default_channels', []);
|
||||
|
||||
return HookManager::applyFilters(
|
||||
'core.notification.filter_available_channels',
|
||||
$defaultChannels
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 채널이 사용 가능한지 확인합니다.
|
||||
*
|
||||
* @param string $channelId
|
||||
* @return bool
|
||||
*/
|
||||
public function isChannelAvailable(string $channelId): bool
|
||||
{
|
||||
$channels = $this->getAvailableChannels();
|
||||
|
||||
return collect($channels)->contains('id', $channelId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장(core/module/plugin) 단위의 채널 전역 활성 여부를 확인합니다.
|
||||
*
|
||||
* 코어 환경설정 / 모듈 환경설정 / 플러그인 환경설정의 "알림 채널 관리"
|
||||
* 섹션에서 토글된 `notifications.channels[*].is_active` 값을 조회합니다.
|
||||
*
|
||||
* 엔트리 자체가 저장되어 있지 않으면 `true`(활성)를 반환합니다 —
|
||||
* 하위호환과 플러그인이 신규 채널을 추가했을 때 기본 활성을 보장합니다.
|
||||
*
|
||||
* `core.notification.channel_enabled` 필터 훅으로 재정의 가능합니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입 (core, module, plugin)
|
||||
* @param string|null $extensionIdentifier 확장 식별자 (core는 'core' 허용)
|
||||
* @param string $channelId 채널 식별자 (mail, database 등)
|
||||
* @return bool true = 발송 허용, false = 발송 차단
|
||||
*/
|
||||
public function isChannelEnabledForExtension(
|
||||
string $extensionType,
|
||||
?string $extensionIdentifier,
|
||||
string $channelId
|
||||
): bool {
|
||||
$cacheKey = $extensionType.'|'.($extensionIdentifier ?? '').'|'.$channelId;
|
||||
|
||||
if (array_key_exists($cacheKey, $this->channelEnabledCache)) {
|
||||
return $this->channelEnabledCache[$cacheKey];
|
||||
}
|
||||
|
||||
$channels = $this->resolveExtensionChannels($extensionType, $extensionIdentifier);
|
||||
$enabled = $this->extractChannelActive($channels, $channelId);
|
||||
|
||||
$enabled = HookManager::applyFilters(
|
||||
'core.notification.channel_enabled',
|
||||
$enabled,
|
||||
$extensionType,
|
||||
$extensionIdentifier,
|
||||
$channelId
|
||||
);
|
||||
|
||||
$this->channelEnabledCache[$cacheKey] = (bool) $enabled;
|
||||
|
||||
return $this->channelEnabledCache[$cacheKey];
|
||||
}
|
||||
|
||||
/**
|
||||
* 메모이제이션 캐시를 초기화합니다. (테스트 및 설정 변경 후 사용)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearChannelEnabledCache(): void
|
||||
{
|
||||
$this->channelEnabledCache = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 타입별 notifications.channels 배열을 조회합니다.
|
||||
*
|
||||
* @param string $extensionType
|
||||
* @param string|null $extensionIdentifier
|
||||
* @return array
|
||||
*/
|
||||
private function resolveExtensionChannels(string $extensionType, ?string $extensionIdentifier): array
|
||||
{
|
||||
try {
|
||||
switch ($extensionType) {
|
||||
case 'core':
|
||||
$settingsService = app(SettingsService::class);
|
||||
$value = $settingsService->getSetting('notifications.channels', []);
|
||||
|
||||
return is_array($value) ? $value : [];
|
||||
|
||||
case 'module':
|
||||
if (empty($extensionIdentifier)) {
|
||||
return [];
|
||||
}
|
||||
$moduleSettings = app(ModuleSettingsService::class);
|
||||
$value = $moduleSettings->get($extensionIdentifier, 'notifications.channels', []);
|
||||
|
||||
return is_array($value) ? $value : [];
|
||||
|
||||
case 'plugin':
|
||||
if (empty($extensionIdentifier)) {
|
||||
return [];
|
||||
}
|
||||
$pluginSettings = app(PluginSettingsService::class);
|
||||
$value = $pluginSettings->get($extensionIdentifier, 'notifications.channels', []);
|
||||
|
||||
return is_array($value) ? $value : [];
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// 설정 조회 실패 시 기본 활성 동작을 위해 빈 배열 반환
|
||||
return [];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* notifications.channels 배열에서 특정 채널의 is_active 값을 추출합니다.
|
||||
*
|
||||
* 엔트리가 없으면 true(기본 활성)를 반환합니다.
|
||||
*
|
||||
* @param array $channels
|
||||
* @param string $channelId
|
||||
* @return bool
|
||||
*/
|
||||
private function extractChannelActive(array $channels, string $channelId): bool
|
||||
{
|
||||
foreach ($channels as $entry) {
|
||||
$id = Arr::get($entry, 'id');
|
||||
if ($id === $channelId) {
|
||||
return (bool) Arr::get($entry, 'is_active', true);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\NotificationDefinitionRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\NotificationDefinition;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class NotificationDefinitionService
|
||||
{
|
||||
/**
|
||||
* 캐시 키 접두사 (드라이버 접두사 `g7:core:` 다음에 붙음).
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $cachePrefix = 'notification.definition.';
|
||||
|
||||
/**
|
||||
* 캐시 TTL (초) — g7_core_settings('cache.notification_ttl') 추종.
|
||||
*/
|
||||
protected function getCacheTtl(): int
|
||||
{
|
||||
$value = g7_core_settings('cache.notification_ttl', 3600);
|
||||
|
||||
return $value !== null ? (int) $value : 3600;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param NotificationDefinitionRepositoryInterface $repository
|
||||
* @param CacheInterface $cache
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly NotificationDefinitionRepositoryInterface $repository,
|
||||
private readonly CacheInterface $cache,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 타입으로 알림 정의 조회 (캐싱).
|
||||
*
|
||||
* @param string $type
|
||||
* @return NotificationDefinition|null
|
||||
*/
|
||||
public function resolve(string $type): ?NotificationDefinition
|
||||
{
|
||||
return $this->cache->remember(
|
||||
$this->getCacheKey($type),
|
||||
fn () => $this->repository->getActiveByType($type),
|
||||
$this->getCacheTtl(),
|
||||
['notification']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 알림 정의 조회 (캐싱).
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
public function getAllActive(): Collection
|
||||
{
|
||||
return $this->cache->remember(
|
||||
$this->cachePrefix . 'all_active',
|
||||
fn () => $this->repository->getAllActive(),
|
||||
$this->getCacheTtl(),
|
||||
['notification']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 확장의 알림 정의 목록 조회.
|
||||
*
|
||||
* @param string $extensionType
|
||||
* @param string $extensionIdentifier
|
||||
* @return Collection
|
||||
*/
|
||||
public function getByExtension(string $extensionType, string $extensionIdentifier): Collection
|
||||
{
|
||||
return $this->repository->getByExtension($extensionType, $extensionIdentifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림 정의 수정.
|
||||
*
|
||||
* @param NotificationDefinition $definition
|
||||
* @param array $data
|
||||
* @param int|null $userId
|
||||
* @return NotificationDefinition
|
||||
*/
|
||||
public function updateDefinition(NotificationDefinition $definition, array $data, ?int $userId = null): NotificationDefinition
|
||||
{
|
||||
HookManager::doAction('core.notification_definition.before_update', $definition, $data);
|
||||
|
||||
$data = HookManager::applyFilters(
|
||||
'core.notification_definition.filter_update_data',
|
||||
$data,
|
||||
$definition
|
||||
);
|
||||
|
||||
$updated = $this->repository->update($definition, $data);
|
||||
|
||||
$this->invalidateCache($definition->type);
|
||||
|
||||
HookManager::doAction('core.notification_definition.after_update', $updated, $data);
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성/비활성 토글.
|
||||
*
|
||||
* @param NotificationDefinition $definition
|
||||
* @return NotificationDefinition
|
||||
*/
|
||||
public function toggleActive(NotificationDefinition $definition): NotificationDefinition
|
||||
{
|
||||
HookManager::doAction('core.notification_definition.before_toggle_active', $definition);
|
||||
|
||||
$updated = $this->repository->update($definition, [
|
||||
'is_active' => ! $definition->is_active,
|
||||
]);
|
||||
|
||||
$this->invalidateCache($definition->type);
|
||||
|
||||
HookManager::doAction('core.notification_definition.after_toggle_active', $updated);
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정의를 기본 상태로 마킹합니다 (모든 템플릿 리셋 후 호출).
|
||||
*
|
||||
* @param NotificationDefinition $definition
|
||||
* @return NotificationDefinition
|
||||
*/
|
||||
public function markAsDefault(NotificationDefinition $definition): NotificationDefinition
|
||||
{
|
||||
if ($definition->is_default) {
|
||||
return $definition;
|
||||
}
|
||||
|
||||
$updated = $this->repository->update($definition, ['is_default' => true]);
|
||||
|
||||
$this->invalidateCache($definition->type);
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 페이지네이션 목록 조회.
|
||||
*
|
||||
* @param array $filters
|
||||
* @param int $perPage
|
||||
* @return LengthAwarePaginator
|
||||
*/
|
||||
public function getDefinitions(array $filters = [], int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
return $this->repository->getPaginated($filters, $perPage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 타입의 캐시 무효화.
|
||||
*
|
||||
* @param string $type
|
||||
* @return void
|
||||
*/
|
||||
public function invalidateCache(string $type): void
|
||||
{
|
||||
$this->cache->forget($this->getCacheKey($type));
|
||||
$this->cache->forget($this->cachePrefix . 'all_active');
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 캐시 무효화.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function invalidateAllCache(): void
|
||||
{
|
||||
$this->cache->flushTags(['notification']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 키 생성.
|
||||
*
|
||||
* @param string $type
|
||||
* @return string
|
||||
*/
|
||||
private function getCacheKey(string $type): string
|
||||
{
|
||||
return $this->cachePrefix . $type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\NotificationLogRepositoryInterface;
|
||||
use App\Enums\NotificationLogStatus;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\NotificationLog;
|
||||
use App\Models\User;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class NotificationLogService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly NotificationLogRepositoryInterface $repository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 발송 성공 로그를 기록합니다.
|
||||
*/
|
||||
public function logSent(array $data): NotificationLog
|
||||
{
|
||||
$data['status'] = NotificationLogStatus::Sent->value;
|
||||
|
||||
HookManager::doAction('core.notification_log.before_log_sent', $data);
|
||||
|
||||
$log = $this->repository->create($data);
|
||||
|
||||
HookManager::doAction('core.notification_log.after_log_sent', $log);
|
||||
|
||||
return $log;
|
||||
}
|
||||
|
||||
/**
|
||||
* 발송 실패 로그를 기록합니다.
|
||||
*/
|
||||
public function logFailed(array $data): NotificationLog
|
||||
{
|
||||
$data['status'] = NotificationLogStatus::Failed->value;
|
||||
|
||||
HookManager::doAction('core.notification_log.before_log_failed', $data);
|
||||
|
||||
$log = $this->repository->create($data);
|
||||
|
||||
HookManager::doAction('core.notification_log.after_log_failed', $log);
|
||||
|
||||
return $log;
|
||||
}
|
||||
|
||||
/**
|
||||
* 발송 건너뜀 로그를 기록합니다.
|
||||
*/
|
||||
public function logSkipped(array $data): NotificationLog
|
||||
{
|
||||
$data['status'] = NotificationLogStatus::Skipped->value;
|
||||
|
||||
HookManager::doAction('core.notification_log.before_log_skipped', $data);
|
||||
|
||||
$log = $this->repository->create($data);
|
||||
|
||||
HookManager::doAction('core.notification_log.after_log_skipped', $log);
|
||||
|
||||
return $log;
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그를 삭제합니다.
|
||||
*/
|
||||
public function deleteLog(NotificationLog $log): bool
|
||||
{
|
||||
HookManager::doAction('core.notification_log.before_delete', $log);
|
||||
|
||||
$result = $this->repository->delete($log);
|
||||
|
||||
HookManager::doAction('core.notification_log.after_delete', $log);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 다건 삭제합니다.
|
||||
*/
|
||||
public function bulkDelete(array $ids): int
|
||||
{
|
||||
HookManager::doAction('core.notification_log.before_bulk_delete', $ids);
|
||||
|
||||
$count = $this->repository->bulkDelete($ids);
|
||||
|
||||
HookManager::doAction('core.notification_log.after_bulk_delete', $ids, $count);
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 페이지네이션 목록을 조회합니다.
|
||||
*
|
||||
* @param User|null $user 스코프 적용 대상 사용자 (null이면 스코프 미적용)
|
||||
*/
|
||||
public function getLogs(array $filters = [], int $perPage = 20, ?User $user = null): LengthAwarePaginator
|
||||
{
|
||||
return $this->repository->getPaginated($filters, $perPage, $user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 알림 수신자 해석 서비스
|
||||
*
|
||||
* recipients JSON 규칙 배열을 해석하여
|
||||
* 최종 수신자 User 컬렉션을 반환합니다.
|
||||
*
|
||||
* 수신자 타입:
|
||||
* - trigger_user: 이벤트를 유발한 사용자 (주문자, 가입자 등)
|
||||
* - related_user: 관련 사용자 (문의 답변 → 문의 작성자)
|
||||
* - role: 특정 역할의 사용자들 (admin, manager 등)
|
||||
* - specific_users: 지정된 사용자 UUID 목록
|
||||
*/
|
||||
class NotificationRecipientResolver
|
||||
{
|
||||
/**
|
||||
* recipients 규칙 배열을 해석하여 수신자 목록을 반환합니다.
|
||||
*
|
||||
* @param array $rules 수신자 규칙 배열
|
||||
* @param array $context 컨텍스트 데이터 (trigger_user_id, related_users 등)
|
||||
* @return Collection<int, User>
|
||||
*/
|
||||
public function resolve(array $rules, array $context): Collection
|
||||
{
|
||||
if (empty($rules)) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$recipients = collect();
|
||||
$triggerUserId = $context['trigger_user_id'] ?? null;
|
||||
|
||||
foreach ($rules as $rule) {
|
||||
$type = $rule['type'] ?? null;
|
||||
|
||||
try {
|
||||
match ($type) {
|
||||
'trigger_user' => $this->addTriggerUser($recipients, $context),
|
||||
'related_user' => $this->addRelatedUser($recipients, $context, $rule),
|
||||
'role' => $this->addByRole($recipients, $rule),
|
||||
'specific_users' => $this->addSpecificUsers($recipients, $rule),
|
||||
default => Log::warning('NotificationRecipientResolver: 알 수 없는 수신자 타입', [
|
||||
'type' => $type,
|
||||
]),
|
||||
};
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('NotificationRecipientResolver: 수신자 해석 실패', [
|
||||
'rule_type' => $type,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// exclude_trigger_user 규칙 적용
|
||||
if ($triggerUserId) {
|
||||
$shouldExclude = collect($rules)->contains(fn ($rule) => ! empty($rule['exclude_trigger_user']));
|
||||
if ($shouldExclude) {
|
||||
$recipients = $recipients->filter(fn (User $user) => $user->id !== $triggerUserId);
|
||||
}
|
||||
}
|
||||
|
||||
return $recipients->unique('id')->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* 이벤트 유발자를 수신자에 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $context 컨텍스트
|
||||
* @return void
|
||||
*/
|
||||
private function addTriggerUser(Collection $recipients, array $context): void
|
||||
{
|
||||
$triggerUserId = $context['trigger_user_id'] ?? null;
|
||||
if (! $triggerUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user = $context['trigger_user'] ?? User::find($triggerUserId);
|
||||
if ($user) {
|
||||
$recipients->push($user);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 관련 사용자를 수신자에 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $context 컨텍스트
|
||||
* @param array $rule 수신자 규칙 (relation 키 필요)
|
||||
* @return void
|
||||
*/
|
||||
private function addRelatedUser(Collection $recipients, array $context, array $rule): void
|
||||
{
|
||||
$relation = $rule['relation'] ?? null;
|
||||
if (! $relation) {
|
||||
return;
|
||||
}
|
||||
|
||||
$relatedUsers = $context['related_users'] ?? [];
|
||||
$user = $relatedUsers[$relation] ?? null;
|
||||
|
||||
if ($user instanceof User) {
|
||||
$recipients->push($user);
|
||||
} elseif ($user instanceof Collection) {
|
||||
$recipients->push(...$user->all());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 역할 기반 수신자를 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = role identifier)
|
||||
* @return void
|
||||
*/
|
||||
private function addByRole(Collection $recipients, array $rule): void
|
||||
{
|
||||
$roleIdentifier = $rule['value'] ?? null;
|
||||
if (! $roleIdentifier) {
|
||||
return;
|
||||
}
|
||||
|
||||
$role = Role::where('identifier', $roleIdentifier)->first();
|
||||
$roleUsers = $role ? $role->users()->get() : collect();
|
||||
|
||||
// 역할 사용자가 없으면 superAdmin 폴백
|
||||
if ($roleUsers->isEmpty()) {
|
||||
$superAdmin = User::superAdmins()->first();
|
||||
if ($superAdmin) {
|
||||
$roleUsers = collect([$superAdmin]);
|
||||
}
|
||||
}
|
||||
|
||||
$recipients->push(...$roleUsers->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 사용자 UUID 목록을 수신자에 추가합니다.
|
||||
*
|
||||
* @param Collection $recipients 수신자 컬렉션
|
||||
* @param array $rule 수신자 규칙 (value = user UUID 배열)
|
||||
* @return void
|
||||
*/
|
||||
private function addSpecificUsers(Collection $recipients, array $rule): void
|
||||
{
|
||||
$userIds = $rule['value'] ?? [];
|
||||
if (empty($userIds) || ! is_array($userIds)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$users = User::whereIn('uuid', $userIds)->get();
|
||||
$recipients->push(...$users->all());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Repositories\NotificationRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\User;
|
||||
use Illuminate\Notifications\DatabaseNotification;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class NotificationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly NotificationRepositoryInterface $notificationRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 사용자의 알림 목록을 조회합니다.
|
||||
*/
|
||||
public function getNotifications(User $user, array $filters = [], int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
$filters = HookManager::applyFilters('core.notification.filter_list_params', $filters, $user);
|
||||
|
||||
$result = $this->notificationRepository->getByUser($user, $filters, $perPage);
|
||||
|
||||
HookManager::doAction('core.notification.after_list', $result, $user);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 미읽음 알림 수를 반환합니다.
|
||||
*/
|
||||
public function getUnreadCount(User $user): int
|
||||
{
|
||||
return $this->notificationRepository->getUnreadCount($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림을 읽음 처리합니다.
|
||||
*/
|
||||
public function markAsRead(User $user, string $notificationId): ?DatabaseNotification
|
||||
{
|
||||
HookManager::doAction('core.notification.before_mark_read', $user, $notificationId);
|
||||
|
||||
$notification = $this->notificationRepository->markAsRead($user, $notificationId);
|
||||
|
||||
if ($notification) {
|
||||
HookManager::doAction('core.notification.after_mark_read', $notification, $user);
|
||||
}
|
||||
|
||||
return $notification;
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정된 알림들을 일괄 읽음 처리합니다.
|
||||
*
|
||||
* @param array $ids 읽음 처리할 알림 ID 목록
|
||||
* @return int 읽음 처리된 알림 수
|
||||
*/
|
||||
public function markBatchAsRead(User $user, array $ids): int
|
||||
{
|
||||
HookManager::doAction('core.notification.before_mark_batch_read', $user, $ids);
|
||||
|
||||
$count = $this->notificationRepository->markBatchAsRead($user, $ids);
|
||||
|
||||
HookManager::doAction('core.notification.after_mark_batch_read', $user, $ids, $count);
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 모든 알림을 읽음 처리합니다.
|
||||
*
|
||||
* @return int 읽음 처리된 알림 수
|
||||
*/
|
||||
public function markAllAsRead(User $user): int
|
||||
{
|
||||
HookManager::doAction('core.notification.before_mark_all_read', $user);
|
||||
|
||||
$count = $this->notificationRepository->markAllAsRead($user);
|
||||
|
||||
HookManager::doAction('core.notification.after_mark_all_read', $user, $count);
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림을 삭제합니다.
|
||||
*/
|
||||
public function deleteNotification(User $user, string $notificationId): bool
|
||||
{
|
||||
HookManager::doAction('core.notification.before_delete', $user, $notificationId);
|
||||
|
||||
$result = $this->notificationRepository->delete($user, $notificationId);
|
||||
|
||||
if ($result) {
|
||||
HookManager::doAction('core.notification.after_delete', $user, $notificationId);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 모든 알림을 삭제합니다.
|
||||
*
|
||||
* @param User $user
|
||||
* @return int 삭제된 알림 수
|
||||
*/
|
||||
public function deleteAllNotifications(User $user): int
|
||||
{
|
||||
HookManager::doAction('core.notification.before_delete_all', $user);
|
||||
|
||||
$count = $this->notificationRepository->deleteAll($user);
|
||||
|
||||
HookManager::doAction('core.notification.after_delete_all', $user, $count);
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 오래된 알림을 정리합니다.
|
||||
*
|
||||
* @return array{deleted_read: int, deleted_unread: int}
|
||||
*/
|
||||
public function cleanup(): array
|
||||
{
|
||||
$config = config('notification.database_channel', []);
|
||||
$readDays = $config['read_retention_days'] ?? 30;
|
||||
$unreadDays = $config['unread_retention_days'] ?? 90;
|
||||
|
||||
HookManager::doAction('core.notification.before_cleanup', $readDays, $unreadDays);
|
||||
|
||||
$result = $this->notificationRepository->cleanup($readDays, $unreadDays);
|
||||
|
||||
HookManager::doAction('core.notification.after_cleanup', $result);
|
||||
|
||||
Log::info('알림 정리 완료', $result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\NotificationDefinitionRepositoryInterface;
|
||||
use App\Contracts\Repositories\NotificationTemplateRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Models\NotificationTemplate;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class NotificationTemplateService
|
||||
{
|
||||
/**
|
||||
* 캐시 키 접두사 (드라이버 접두사 `g7:core:` 다음에 붙음).
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $cachePrefix = 'notification.template.';
|
||||
|
||||
/**
|
||||
* 캐시 TTL (초) — g7_core_settings('cache.notification_ttl') 추종.
|
||||
*/
|
||||
protected function getCacheTtl(): int
|
||||
{
|
||||
return (int) g7_core_settings('cache.notification_ttl', 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param NotificationTemplateRepositoryInterface $templateRepository
|
||||
* @param NotificationDefinitionRepositoryInterface $definitionRepository
|
||||
* @param CacheInterface $cache
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly NotificationTemplateRepositoryInterface $templateRepository,
|
||||
private readonly NotificationDefinitionRepositoryInterface $definitionRepository,
|
||||
private readonly CacheInterface $cache,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 알림 타입 + 채널로 활성 템플릿 조회 (캐싱).
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @return NotificationTemplate|null
|
||||
*/
|
||||
public function resolve(string $type, string $channel): ?NotificationTemplate
|
||||
{
|
||||
return $this->cache->remember(
|
||||
$this->getCacheKey($type, $channel),
|
||||
fn () => $this->templateRepository->getActiveByTypeAndChannel($type, $channel),
|
||||
$this->getCacheTtl(),
|
||||
['notification']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 알림 정의의 모든 템플릿 조회.
|
||||
*
|
||||
* @param int $definitionId
|
||||
* @return Collection
|
||||
*/
|
||||
public function getByDefinitionId(int $definitionId): Collection
|
||||
{
|
||||
return $this->templateRepository->getByDefinitionId($definitionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 수정.
|
||||
*
|
||||
* @param NotificationTemplate $template
|
||||
* @param array $data
|
||||
* @param int|null $userId
|
||||
* @return NotificationTemplate
|
||||
*/
|
||||
public function updateTemplate(NotificationTemplate $template, array $data, ?int $userId = null): NotificationTemplate
|
||||
{
|
||||
$snapshot = $template->toArray();
|
||||
|
||||
HookManager::doAction('core.notification_template.before_update', $template, $data);
|
||||
|
||||
$data = HookManager::applyFilters(
|
||||
'core.notification_template.filter_update_data',
|
||||
$data,
|
||||
$template
|
||||
);
|
||||
|
||||
if ($userId) {
|
||||
$data['updated_by'] = $userId;
|
||||
}
|
||||
|
||||
// 사용자가 편집한 템플릿은 더 이상 기본 상태가 아님
|
||||
$data['is_default'] = false;
|
||||
|
||||
$updated = $this->templateRepository->update($template, $data);
|
||||
|
||||
$definition = $updated->definition;
|
||||
if ($definition) {
|
||||
// 소속 정의도 "커스터마이징됨" 상태로 전환 (리셋 버튼 노출 근거)
|
||||
if ($definition->is_default) {
|
||||
$this->definitionRepository->update($definition, ['is_default' => false]);
|
||||
}
|
||||
|
||||
$this->invalidateCache($definition->type, $updated->channel);
|
||||
}
|
||||
|
||||
HookManager::doAction('core.notification_template.after_update', $updated, $data, $snapshot);
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성/비활성 토글.
|
||||
*
|
||||
* @param NotificationTemplate $template
|
||||
* @return NotificationTemplate
|
||||
*/
|
||||
public function toggleActive(NotificationTemplate $template): NotificationTemplate
|
||||
{
|
||||
HookManager::doAction('core.notification_template.before_toggle_active', $template);
|
||||
|
||||
$updated = $this->templateRepository->update($template, [
|
||||
'is_active' => ! $template->is_active,
|
||||
]);
|
||||
|
||||
$definition = $updated->definition;
|
||||
if ($definition) {
|
||||
$this->invalidateCache($definition->type, $updated->channel);
|
||||
}
|
||||
|
||||
HookManager::doAction('core.notification_template.after_toggle_active', $updated);
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본값으로 복원.
|
||||
*
|
||||
* @param NotificationTemplate $template
|
||||
* @param array $defaultData
|
||||
* @return NotificationTemplate
|
||||
*/
|
||||
public function resetToDefault(NotificationTemplate $template, array $defaultData): NotificationTemplate
|
||||
{
|
||||
$updated = $this->templateRepository->update($template, array_merge($defaultData, [
|
||||
'is_default' => true,
|
||||
'user_overrides' => null,
|
||||
]));
|
||||
|
||||
$definition = $updated->definition;
|
||||
if ($definition) {
|
||||
$this->invalidateCache($definition->type, $updated->channel);
|
||||
}
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 시더에서 기본 템플릿 데이터를 조회합니다.
|
||||
*
|
||||
* @param string $type 알림 정의 타입
|
||||
* @param string $channel 채널명
|
||||
* @return array 기본 템플릿 데이터 (subject, body)
|
||||
*/
|
||||
public function getDefaultTemplateData(string $type, string $channel): array
|
||||
{
|
||||
$seeder = new \Database\Seeders\NotificationDefinitionSeeder();
|
||||
$definitions = $seeder->getDefaultDefinitions();
|
||||
|
||||
// 확장(모듈/플러그인)이 자신의 기본 정의를 추가할 수 있도록 필터 훅 노출
|
||||
$definitions = HookManager::applyFilters(
|
||||
'core.notification.filter_default_definitions',
|
||||
$definitions,
|
||||
['type' => $type, 'channel' => $channel]
|
||||
);
|
||||
|
||||
foreach ($definitions as $def) {
|
||||
if ($def['type'] === $type) {
|
||||
foreach ($def['templates'] as $tpl) {
|
||||
if ($tpl['channel'] === $channel) {
|
||||
return [
|
||||
'subject' => $tpl['subject'] ?? null,
|
||||
'body' => $tpl['body'],
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 미리보기용 렌더링.
|
||||
*
|
||||
* definition_id가 제공되면 해당 정의의 변수 메타데이터를 조회하여
|
||||
* 샘플 값으로 치환합니다.
|
||||
*
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
public function getPreview(array $data): array
|
||||
{
|
||||
$locale = $data['locale'] ?? app()->getLocale();
|
||||
$subject = $data['subject'][$locale] ?? '';
|
||||
$body = $data['body'][$locale] ?? '';
|
||||
|
||||
$replacements = [];
|
||||
|
||||
// definition_id로 변수 메타데이터 조회
|
||||
if (isset($data['definition_id'])) {
|
||||
$definition = $this->definitionRepository->findById((int) $data['definition_id']);
|
||||
if ($definition) {
|
||||
foreach ($definition->variables ?? [] as $var) {
|
||||
$key = $var['key'] ?? '';
|
||||
if ($key !== '') {
|
||||
$description = $var['description'] ?? $key;
|
||||
$replacements['{' . $key . '}'] = '[' . $description . ']';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 명시적으로 전달된 variables가 있으면 덮어쓰기
|
||||
foreach ($data['variables'] ?? [] as $key => $value) {
|
||||
$replacements['{' . $key . '}'] = (string) $value;
|
||||
}
|
||||
|
||||
return [
|
||||
'subject' => strtr($subject, $replacements),
|
||||
'body' => strtr($body, $replacements),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 타입+채널의 캐시 무효화.
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @return void
|
||||
*/
|
||||
public function invalidateCache(string $type, string $channel): void
|
||||
{
|
||||
$this->cache->forget($this->getCacheKey($type, $channel));
|
||||
}
|
||||
|
||||
/**
|
||||
* 캐시 키 생성.
|
||||
*
|
||||
* @param string $type
|
||||
* @param string $channel
|
||||
* @return string
|
||||
*/
|
||||
private function getCacheKey(string $type, string $channel): string
|
||||
{
|
||||
return $this->cachePrefix . $type . '.' . $channel;
|
||||
}
|
||||
}
|
||||
@@ -106,13 +106,16 @@ class PluginService
|
||||
return $this->pluginManager->getPluginUninstallInfo($pluginName);
|
||||
}
|
||||
|
||||
public function installPlugin(string $pluginName): ?array
|
||||
{
|
||||
public function installPlugin(
|
||||
string $pluginName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
bool $force = false,
|
||||
): ?array {
|
||||
HookManager::doAction('core.plugins.before_install', $pluginName);
|
||||
|
||||
try {
|
||||
$this->pluginManager->loadPlugins();
|
||||
$result = $this->pluginManager->installPlugin($pluginName);
|
||||
$result = $this->pluginManager->installPlugin($pluginName, null, $vendorMode, $force);
|
||||
|
||||
if ($result) {
|
||||
// 설치 후 플러그인 정보 반환
|
||||
@@ -417,17 +420,28 @@ class PluginService
|
||||
* 지정된 플러그인을 업데이트합니다.
|
||||
*
|
||||
* @param string $pluginName 업데이트할 플러그인 identifier
|
||||
* @param \App\Extension\Vendor\VendorMode $vendorMode Vendor 설치 모드
|
||||
* @param string $layoutStrategy 레이아웃 전략 (overwrite|keep)
|
||||
* @return array 업데이트 결과 (identifier, from_version, to_version 등)
|
||||
*
|
||||
* @throws ValidationException 업데이트 실패 시
|
||||
*/
|
||||
public function updatePlugin(string $pluginName): array
|
||||
{
|
||||
public function updatePlugin(
|
||||
string $pluginName,
|
||||
\App\Extension\Vendor\VendorMode $vendorMode = \App\Extension\Vendor\VendorMode::Auto,
|
||||
string $layoutStrategy = 'overwrite',
|
||||
): array {
|
||||
HookManager::doAction('core.plugins.before_update', $pluginName);
|
||||
|
||||
try {
|
||||
$this->pluginManager->loadPlugins();
|
||||
$result = $this->pluginManager->updatePlugin($pluginName);
|
||||
$result = $this->pluginManager->updatePlugin(
|
||||
$pluginName,
|
||||
false,
|
||||
null,
|
||||
$vendorMode,
|
||||
$layoutStrategy,
|
||||
);
|
||||
|
||||
$pluginInfo = $this->pluginManager->getPluginInfo($pluginName);
|
||||
|
||||
@@ -447,6 +461,27 @@ class PluginService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정된 플러그인의 수정된 레이아웃을 확인합니다.
|
||||
*
|
||||
* @param string $pluginName 확인할 플러그인 identifier
|
||||
* @return array{has_modified_layouts: bool, modified_count: int, modified_layouts: array}
|
||||
*
|
||||
* @throws ValidationException 확인 실패 시
|
||||
*/
|
||||
public function checkModifiedLayouts(string $pluginName): array
|
||||
{
|
||||
try {
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
return $this->pluginManager->hasModifiedLayouts($pluginName);
|
||||
} catch (\Exception $e) {
|
||||
throw ValidationException::withMessages([
|
||||
'plugin_name' => [__('plugins.check_modified_layouts_failed', ['error' => $e->getMessage()])],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인의 레이아웃을 파일에서 다시 읽어 DB에 갱신합니다.
|
||||
*
|
||||
|
||||
@@ -2,15 +2,16 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Contracts\Extension\CacheInterface;
|
||||
use App\Contracts\Repositories\AttachmentRepositoryInterface;
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Http\Resources\AttachmentResource;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
@@ -23,9 +24,23 @@ class SettingsService
|
||||
{
|
||||
public function __construct(
|
||||
private ConfigRepositoryInterface $configRepository,
|
||||
private AttachmentRepositoryInterface $attachmentRepository
|
||||
private AttachmentRepositoryInterface $attachmentRepository,
|
||||
private CacheInterface $cache
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 시스템 설정 캐시를 무효화합니다.
|
||||
*
|
||||
* 설정 저장 시 4곳에서 중복되던 로직을 단일 메서드로 통합했습니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function invalidateSettingsCache(): void
|
||||
{
|
||||
$this->cache->forget('settings.system');
|
||||
Artisan::call('config:clear');
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 시스템 설정을 조회합니다.
|
||||
*
|
||||
@@ -157,12 +172,65 @@ class SettingsService
|
||||
}
|
||||
|
||||
$value = config($configKey);
|
||||
|
||||
if ($frontendKey === 'supportedTimezones' && is_array($value)) {
|
||||
$result[$frontendKey] = $this->buildTimezoneOptions($value);
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[$frontendKey] = $this->castValue($value, $fieldSchema);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* IANA 타임존 배열을 프론트엔드 Select 옵션 형식으로 변환합니다.
|
||||
*
|
||||
* 각 타임존의 현재 시점 UTC 오프셋을 계산하여
|
||||
* "(UTC±HH:MM) Asia/Seoul" 형식의 라벨을 생성합니다.
|
||||
* DST 전환 시점에 자동으로 정확한 오프셋이 반영됩니다.
|
||||
*
|
||||
* 정렬 순서: 오프셋 오름차순 → 식별자 알파벳순
|
||||
*
|
||||
* @param array<int, string> $timezones IANA 타임존 식별자 배열
|
||||
* @return array<int, array{value: string, label: string}> Select 옵션 배열
|
||||
*/
|
||||
private function buildTimezoneOptions(array $timezones): array
|
||||
{
|
||||
$now = new \DateTime('now', new \DateTimeZone('UTC'));
|
||||
|
||||
$items = [];
|
||||
foreach ($timezones as $tz) {
|
||||
if (! is_string($tz) || $tz === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$offsetSec = (new \DateTimeZone($tz))->getOffset($now);
|
||||
} catch (\Exception) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sign = $offsetSec >= 0 ? '+' : '-';
|
||||
$h = intdiv(abs($offsetSec), 3600);
|
||||
$m = intdiv(abs($offsetSec) % 3600, 60);
|
||||
|
||||
$items[] = [
|
||||
'value' => $tz,
|
||||
'label' => sprintf('(UTC%s%02d:%02d) %s', $sign, $h, $m, $tz),
|
||||
'offset' => $offsetSec,
|
||||
];
|
||||
}
|
||||
|
||||
usort($items, fn ($a, $b) => [$a['offset'], $a['value']] <=> [$b['offset'], $b['value']]);
|
||||
|
||||
return array_map(
|
||||
fn ($i) => ['value' => $i['value'], 'label' => $i['label']],
|
||||
$items
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 스키마에 따라 카테고리 설정을 포맷팅합니다.
|
||||
*
|
||||
@@ -385,8 +453,20 @@ class SettingsService
|
||||
$result = $this->configRepository->saveCategory($tab, $mergedSettings);
|
||||
|
||||
if ($result) {
|
||||
// 캐시 클리어
|
||||
Cache::forget('system_settings');
|
||||
$this->invalidateSettingsCache();
|
||||
|
||||
// drivers 탭은 queue/broadcasting/cache 등 long-running worker에 영향
|
||||
// SettingsServiceProvider는 worker boot 시점에 한 번만 config 적용하므로
|
||||
// 워커가 정상 종료 후 재시작되도록 신호 전송 (cache 기반, 즉시 종료 X)
|
||||
if ($tab === 'drivers') {
|
||||
try {
|
||||
Artisan::call('queue:restart');
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('queue:restart 실행 실패', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// After 훅
|
||||
@@ -454,52 +534,42 @@ class SettingsService
|
||||
*/
|
||||
private function saveAdvancedSettings(array $settings): bool
|
||||
{
|
||||
// cache 카테고리 필드
|
||||
$cacheFields = ['enabled', 'layout_enabled', 'layout_ttl', 'stats_enabled', 'stats_ttl', 'seo_enabled', 'seo_ttl'];
|
||||
// debug 카테고리 필드
|
||||
$debugFields = ['mode', 'sql_query_log', 'log_level'];
|
||||
// core_update 카테고리 필드
|
||||
$coreUpdateFields = ['github_url', 'github_token'];
|
||||
// 각 카테고리에 속하는 원본 필드명 목록
|
||||
// (frontend_key → 원본 키 역변환 후의 키 기준)
|
||||
$categoryFieldMap = [
|
||||
'cache' => ['enabled', 'layout_enabled', 'layout_ttl', 'stats_enabled', 'stats_ttl', 'seo_enabled', 'seo_ttl'],
|
||||
'debug' => ['mode', 'sql_query_log', 'log_level'],
|
||||
'core_update' => ['github_url', 'github_token'],
|
||||
'geoip' => ['feature_enabled', 'license_key', 'auto_update_enabled', 'last_updated_at'],
|
||||
];
|
||||
|
||||
$cacheSettings = [];
|
||||
$debugSettings = [];
|
||||
$coreUpdateSettings = [];
|
||||
// 설정을 카테고리별로 분류
|
||||
$categorized = array_fill_keys(array_keys($categoryFieldMap), []);
|
||||
|
||||
foreach ($settings as $key => $value) {
|
||||
if (in_array($key, $cacheFields)) {
|
||||
$cacheSettings[$key] = $value;
|
||||
} elseif (in_array($key, $debugFields)) {
|
||||
$debugSettings[$key] = $value;
|
||||
} elseif (in_array($key, $coreUpdateFields)) {
|
||||
$coreUpdateSettings[$key] = $value;
|
||||
foreach ($categoryFieldMap as $category => $fields) {
|
||||
if (in_array($key, $fields)) {
|
||||
$categorized[$category][$key] = $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$result = true;
|
||||
|
||||
// cache 설정 저장
|
||||
if (! empty($cacheSettings)) {
|
||||
$existingCache = $this->configRepository->getCategory('cache');
|
||||
$mergedCache = array_merge($existingCache, $cacheSettings);
|
||||
$result = $result && $this->configRepository->saveCategory('cache', $mergedCache);
|
||||
}
|
||||
// 각 카테고리별 병합 저장
|
||||
foreach ($categorized as $category => $categorySettings) {
|
||||
if (empty($categorySettings)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// debug 설정 저장
|
||||
if (! empty($debugSettings)) {
|
||||
$existingDebug = $this->configRepository->getCategory('debug');
|
||||
$mergedDebug = array_merge($existingDebug, $debugSettings);
|
||||
$result = $result && $this->configRepository->saveCategory('debug', $mergedDebug);
|
||||
}
|
||||
|
||||
// core_update 설정 저장
|
||||
if (! empty($coreUpdateSettings)) {
|
||||
$existingCoreUpdate = $this->configRepository->getCategory('core_update');
|
||||
$mergedCoreUpdate = array_merge($existingCoreUpdate, $coreUpdateSettings);
|
||||
$result = $result && $this->configRepository->saveCategory('core_update', $mergedCoreUpdate);
|
||||
$existing = $this->configRepository->getCategory($category);
|
||||
$merged = array_merge($existing, $categorySettings);
|
||||
$result = $result && $this->configRepository->saveCategory($category, $merged);
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
Cache::forget('system_settings');
|
||||
$this->invalidateSettingsCache();
|
||||
}
|
||||
|
||||
return $result;
|
||||
@@ -538,7 +608,7 @@ class SettingsService
|
||||
$result = $this->configRepository->set($key, $value);
|
||||
|
||||
if ($result) {
|
||||
Cache::forget('system_settings');
|
||||
$this->cache->forget('settings.system');
|
||||
}
|
||||
|
||||
// After 훅
|
||||
@@ -573,7 +643,7 @@ class SettingsService
|
||||
$result = $this->configRepository->restore($backupPath);
|
||||
|
||||
if ($result) {
|
||||
Cache::forget('system_settings');
|
||||
$this->cache->forget('settings.system');
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
@@ -359,16 +359,17 @@ class TemplateService
|
||||
* 템플릿을 설치합니다.
|
||||
*
|
||||
* @param string $identifier 설치할 템플릿 식별자
|
||||
* @param bool $force 활성 디렉토리가 있어도 원본으로 덮어쓰고 재설치
|
||||
* @return array|null 설치된 템플릿 정보 또는 null
|
||||
*
|
||||
* @throws ValidationException 설치 실패 시
|
||||
*/
|
||||
public function installTemplate(string $identifier): ?array
|
||||
public function installTemplate(string $identifier, bool $force = false): ?array
|
||||
{
|
||||
HookManager::doAction('core.templates.before_install', $identifier);
|
||||
|
||||
try {
|
||||
$result = $this->templateManager->installTemplate($identifier);
|
||||
$result = $this->templateManager->installTemplate($identifier, null, $force);
|
||||
|
||||
if ($result) {
|
||||
$templateInfo = $this->templateManager->getTemplateInfo($identifier);
|
||||
@@ -1465,7 +1466,7 @@ class TemplateService
|
||||
|
||||
try {
|
||||
$this->templateManager->loadTemplates();
|
||||
$result = $this->templateManager->updateTemplate($templateName, $layoutStrategy);
|
||||
$result = $this->templateManager->updateTemplate($templateName, false, null, $layoutStrategy);
|
||||
|
||||
$templateInfo = $this->templateManager->getTemplateInfo($templateName);
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Exceptions\CannotDeleteAdminException;
|
||||
use App\Exceptions\CannotDeleteSuperAdminException;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
@@ -127,7 +128,8 @@ class UserService
|
||||
$data = HookManager::applyFilters('core.user.filter_update_data', $data, $user);
|
||||
|
||||
// 비밀번호 처리
|
||||
if (! empty($data['password'])) {
|
||||
$passwordChanged = ! empty($data['password']);
|
||||
if ($passwordChanged) {
|
||||
$data['password'] = Hash::make($data['password']);
|
||||
} else {
|
||||
// 비밀번호가 비어있으면 업데이트하지 않음
|
||||
@@ -200,6 +202,11 @@ class UserService
|
||||
// After 훅: 사용자 객체와 원본 데이터, 스냅샷 전달
|
||||
HookManager::doAction('core.user.after_update', $user, $originalData, $snapshot);
|
||||
|
||||
// 비밀번호 변경 시 알림 훅 발화 — 발송은 NotificationHookListener가 처리
|
||||
if ($passwordChanged) {
|
||||
HookManager::doAction('core.auth.after_password_changed', $user);
|
||||
}
|
||||
|
||||
return $user->fresh(['modules', 'plugins', 'menus', 'roles']);
|
||||
} catch (Exception $e) {
|
||||
if ($e instanceof ValidationException) {
|
||||
@@ -482,6 +489,29 @@ class UserService
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 활동 로그를 조회합니다.
|
||||
*
|
||||
* @param int $userId 사용자 ID
|
||||
* @param int $limit 조회 건수
|
||||
* @return \Illuminate\Support\Collection
|
||||
*/
|
||||
public function getUserActivityLogs(int $userId, int $limit = 50): \Illuminate\Support\Collection
|
||||
{
|
||||
return ActivityLog::byUser($userId)
|
||||
->latest()
|
||||
->limit($limit)
|
||||
->get()
|
||||
->map(fn (ActivityLog $log) => [
|
||||
'id' => $log->id,
|
||||
'action' => $log->action,
|
||||
'action_label' => $log->action_label,
|
||||
'description' => $log->localized_description,
|
||||
'ip_address' => $log->ip_address,
|
||||
'created_at' => $log->created_at?->toIso8601String(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 마지막 로그인 시간을 현재 시간으로 업데이트합니다.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user