v7.0.0-beta.1 release
This commit is contained in:
commit
6595fd0eb5
3967 files changed
+1875383
No files matched your search
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\ActivityLog;
|
||||
|
||||
use Monolog\Logger;
|
||||
|
||||
/**
|
||||
* Monolog 커스텀 채널 팩토리.
|
||||
*
|
||||
* config/logging.php의 'activity' 채널에서 via 클래스로 사용됩니다.
|
||||
* Laravel의 custom 드라이버가 __invoke($config)를 호출하여 Monolog Logger를 반환합니다.
|
||||
*/
|
||||
class ActivityLogChannel
|
||||
{
|
||||
/**
|
||||
* 활동 로그 전용 Monolog Logger 인스턴스를 생성합니다.
|
||||
*
|
||||
* @param array $config 채널 설정
|
||||
* @return Logger
|
||||
*/
|
||||
public function __invoke(array $config): Logger
|
||||
{
|
||||
$logger = new Logger('activity');
|
||||
$logger->pushProcessor(new ActivityLogProcessor);
|
||||
$logger->pushHandler(new ActivityLogHandler);
|
||||
|
||||
return $logger;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\ActivityLog;
|
||||
|
||||
use App\Enums\ActivityLogType;
|
||||
use App\Models\ActivityLog;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Monolog\Handler\AbstractProcessingHandler;
|
||||
use Monolog\Level;
|
||||
use Monolog\LogRecord;
|
||||
|
||||
/**
|
||||
* 활동 로그 전용 Monolog Handler.
|
||||
*
|
||||
* Monolog context에서 구조화 데이터를 추출하여 activity_logs 테이블에 저장합니다.
|
||||
* ActivityLogChannel에서 등록되어 Log::channel('activity') 호출 시 동작합니다.
|
||||
*/
|
||||
class ActivityLogHandler extends AbstractProcessingHandler
|
||||
{
|
||||
/**
|
||||
* @param Level $level 최소 로그 레벨
|
||||
* @param bool $bubble 버블링 여부
|
||||
*/
|
||||
public function __construct(Level $level = Level::Debug, bool $bubble = true)
|
||||
{
|
||||
parent::__construct($level, $bubble);
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그 레코드를 activity_logs 테이블에 저장합니다.
|
||||
*
|
||||
* @param LogRecord $record Monolog 로그 레코드
|
||||
* @return void
|
||||
*/
|
||||
protected function write(LogRecord $record): void
|
||||
{
|
||||
if (! config('activity_log.enabled', true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$context = $record->context;
|
||||
|
||||
$data = [
|
||||
'log_type' => $context['log_type'] ?? ActivityLogType::System,
|
||||
'action' => $record->message,
|
||||
'description_key' => $context['description_key'] ?? null,
|
||||
'description_params' => $context['description_params'] ?? null,
|
||||
'properties' => $context['properties'] ?? null,
|
||||
'changes' => $context['changes'] ?? null,
|
||||
'user_id' => $context['user_id'] ?? null,
|
||||
'ip_address' => $context['ip_address'] ?? null,
|
||||
'user_agent' => $this->truncateUserAgent($context['user_agent'] ?? null),
|
||||
];
|
||||
|
||||
$loggable = $context['loggable'] ?? null;
|
||||
if ($loggable instanceof Model) {
|
||||
$data['loggable_type'] = $loggable->getMorphClass();
|
||||
$data['loggable_id'] = $loggable->getKey();
|
||||
} elseif (isset($context['loggable_type'], $context['loggable_id'])) {
|
||||
$data['loggable_type'] = $context['loggable_type'];
|
||||
$data['loggable_id'] = $context['loggable_id'];
|
||||
}
|
||||
|
||||
ActivityLog::create($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* User-Agent 문자열을 최대 500자로 자릅니다.
|
||||
*
|
||||
* @param string|null $userAgent User-Agent 문자열
|
||||
* @return string|null 잘린 User-Agent
|
||||
*/
|
||||
private function truncateUserAgent(?string $userAgent): ?string
|
||||
{
|
||||
if ($userAgent === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mb_substr($userAgent, 0, 500);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\ActivityLog;
|
||||
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Request;
|
||||
use Monolog\LogRecord;
|
||||
use Monolog\Processor\ProcessorInterface;
|
||||
|
||||
/**
|
||||
* 활동 로그 전용 Monolog Processor.
|
||||
*
|
||||
* 요청별 공통 데이터(user_id, ip_address, user_agent)를 자동 주입합니다.
|
||||
* 리스너에서 명시적으로 전달하지 않은 경우에만 주입됩니다.
|
||||
*/
|
||||
class ActivityLogProcessor implements ProcessorInterface
|
||||
{
|
||||
/**
|
||||
* 로그 레코드에 요청 컨텍스트 정보를 자동 주입합니다.
|
||||
*
|
||||
* @param LogRecord $record Monolog 로그 레코드
|
||||
* @return LogRecord 컨텍스트가 주입된 로그 레코드
|
||||
*/
|
||||
public function __invoke(LogRecord $record): LogRecord
|
||||
{
|
||||
$context = $record->context;
|
||||
|
||||
// 리스너에서 명시적으로 전달하지 않은 경우에만 자동 주입
|
||||
$context['user_id'] ??= Auth::id();
|
||||
$context['ip_address'] ??= Request::ip();
|
||||
$context['user_agent'] ??= Request::userAgent();
|
||||
|
||||
return $record->with(context: $context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\ActivityLog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* 모델 변경 감지 유틸리티.
|
||||
*
|
||||
* 모델의 $activityLogFields 메타데이터와 스냅샷을 비교하여
|
||||
* 구조화된 변경 이력(changes JSON)을 생성합니다.
|
||||
*/
|
||||
class ChangeDetector
|
||||
{
|
||||
/**
|
||||
* 모델의 현재 상태와 스냅샷을 비교하여 변경 사항을 감지합니다.
|
||||
*
|
||||
* @param Model $model 현재 모델 상태
|
||||
* @param array|null $snapshot 변경 전 스냅샷 (toArray() 결과)
|
||||
* @return array|null 변경 사항 배열 또는 변경 없으면 null
|
||||
*/
|
||||
public static function detect(Model $model, ?array $snapshot): ?array
|
||||
{
|
||||
if ($snapshot === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$fields = static::getActivityLogFields($model);
|
||||
if (empty($fields)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$changes = [];
|
||||
|
||||
foreach ($fields as $field => $meta) {
|
||||
$old = $snapshot[$field] ?? null;
|
||||
$new = $model->getAttribute($field);
|
||||
|
||||
// Enum 객체를 값으로 변환
|
||||
if ($old instanceof \BackedEnum) {
|
||||
$old = $old->value;
|
||||
}
|
||||
if ($new instanceof \BackedEnum) {
|
||||
$new = $new->value;
|
||||
}
|
||||
|
||||
if ($old !== $new) {
|
||||
$change = [
|
||||
'field' => $field,
|
||||
'label_key' => $meta['label_key'],
|
||||
'old' => $old,
|
||||
'new' => $new,
|
||||
'type' => $meta['type'] ?? 'text',
|
||||
];
|
||||
|
||||
// enum 타입이면 라벨 키 추가
|
||||
if (($meta['type'] ?? 'text') === 'enum' && isset($meta['enum'])) {
|
||||
$enumClass = $meta['enum'];
|
||||
$change['old_label_key'] = $old !== null ? $enumClass::tryFrom($old)?->labelKey() : null;
|
||||
$change['new_label_key'] = $new !== null ? $enumClass::tryFrom($new)?->labelKey() : null;
|
||||
}
|
||||
|
||||
$changes[] = $change;
|
||||
}
|
||||
}
|
||||
|
||||
return ! empty($changes) ? $changes : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모델의 $activityLogFields 메타데이터를 반환합니다.
|
||||
*
|
||||
* @param Model $model 대상 모델
|
||||
* @return array 필드 메타데이터 배열
|
||||
*/
|
||||
private static function getActivityLogFields(Model $model): array
|
||||
{
|
||||
if (property_exists($model, 'activityLogFields')) {
|
||||
return $model::$activityLogFields;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\ActivityLog\Traits;
|
||||
|
||||
use App\Enums\ActivityLogType;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 활동 로그 기록 및 로그 타입 자동 결정 트레이트
|
||||
*
|
||||
* Service 훅이 관리자/사용자/시스템 등 다양한 컨텍스트에서 호출될 수 있으므로
|
||||
* 요청 경로를 기반으로 log_type을 동적으로 결정합니다.
|
||||
*
|
||||
* - /api/admin/* 경로 → ActivityLogType::Admin
|
||||
* - 그 외 HTTP 요청 → ActivityLogType::User
|
||||
* - CLI/스케줄러(request 없음) → ActivityLogType::System
|
||||
*/
|
||||
trait ResolvesActivityLogType
|
||||
{
|
||||
/**
|
||||
* 요청 경로를 기반으로 로그 타입을 결정합니다.
|
||||
*
|
||||
* @return ActivityLogType 결정된 로그 타입
|
||||
*/
|
||||
protected function resolveLogType(): ActivityLogType
|
||||
{
|
||||
$request = request();
|
||||
|
||||
if ($request && $request->path() !== '/') {
|
||||
return $request->is('api/admin/*')
|
||||
? ActivityLogType::Admin
|
||||
: ActivityLogType::User;
|
||||
}
|
||||
|
||||
return ActivityLogType::System;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활동 로그를 기록합니다.
|
||||
*
|
||||
* context에 log_type이 명시되지 않으면 resolveLogType()으로 자동 결정합니다.
|
||||
*
|
||||
* @param string $action 액션명 (예: 'user.create')
|
||||
* @param array $context Monolog context 배열
|
||||
*/
|
||||
protected function logActivity(string $action, array $context): void
|
||||
{
|
||||
$context['log_type'] ??= $this->resolveLogType();
|
||||
|
||||
try {
|
||||
Log::channel('activity')->info($action, $context);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Failed to record activity log', [
|
||||
'action' => $action,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Casts;
|
||||
|
||||
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Unicode 이스케이프 없이 JSON을 저장하는 커스텀 캐스트
|
||||
*
|
||||
* Laravel 기본 'array' 캐스트는 json_encode()로 한글을 \uXXXX 이스케이프합니다.
|
||||
* 이 캐스트는 JSON_UNESCAPED_UNICODE 플래그를 사용하여 실제 UTF-8 문자로 저장합니다.
|
||||
*
|
||||
* FULLTEXT 인덱스(ngram)가 한글 토큰을 올바르게 생성하려면
|
||||
* 실제 UTF-8 문자가 저장되어야 합니다.
|
||||
*/
|
||||
class AsUnicodeJson implements CastsAttributes
|
||||
{
|
||||
/**
|
||||
* 데이터베이스에서 값을 읽을 때 변환합니다.
|
||||
*
|
||||
* @param Model $model 모델 인스턴스
|
||||
* @param string $key 속성명
|
||||
* @param mixed $value 원본 값
|
||||
* @param array<string, mixed> $attributes 전체 속성
|
||||
* @return array|null
|
||||
*/
|
||||
public function get(Model $model, string $key, mixed $value, array $attributes): ?array
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return json_decode($value, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터베이스에 값을 저장할 때 변환합니다.
|
||||
*
|
||||
* JSON_UNESCAPED_UNICODE 플래그를 사용하여 한글 등 멀티바이트 문자를
|
||||
* \uXXXX 이스케이프 없이 실제 UTF-8로 저장합니다.
|
||||
*
|
||||
* @param Model $model 모델 인스턴스
|
||||
* @param string $key 속성명
|
||||
* @param mixed $value 저장할 값
|
||||
* @param array<string, mixed> $attributes 전체 속성
|
||||
* @return string|null
|
||||
*/
|
||||
public function set(Model $model, string $key, mixed $value, array $attributes): ?string
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* 레이아웃 파일에 permissions 필드를 일괄 추가하는 커맨드
|
||||
*
|
||||
* 관리자 레이아웃에 접근 제어를 위한 permissions 필드를 추가합니다.
|
||||
*/
|
||||
class AddLayoutPermissionsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* 커맨드 시그니처
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'layout:add-permissions
|
||||
{--dry-run : 실제 파일 수정 없이 시뮬레이션만 수행}
|
||||
{--layout= : 특정 레이아웃만 처리 (레이아웃 이름)}
|
||||
{--force : 이미 permissions가 있는 경우에도 덮어쓰기}';
|
||||
|
||||
/**
|
||||
* 커맨드 설명
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '레이아웃 파일에 permissions 필드를 일괄 추가합니다';
|
||||
|
||||
/**
|
||||
* 레이아웃별 권한 매핑
|
||||
*
|
||||
* @var array<string, array<string>>
|
||||
*/
|
||||
protected array $permissionMappings = [
|
||||
// sirsoft-admin_basic 템플릿
|
||||
'admin_dashboard' => ['core.dashboard.read'],
|
||||
'admin_user_list' => ['core.users.read'],
|
||||
'admin_user_form' => ['core.users.read'],
|
||||
'admin_user_detail' => ['core.users.read'],
|
||||
'admin_role_list' => ['core.permissions.read'],
|
||||
'admin_role_form' => ['core.permissions.read'],
|
||||
'admin_menu_list' => ['core.menus.read'],
|
||||
'admin_schedule_list' => ['core.schedules.read'],
|
||||
'admin_module_list' => ['core.modules.read'],
|
||||
'admin_plugin_list' => ['core.plugins.read'],
|
||||
'admin_template_list' => ['core.templates.read'],
|
||||
'admin_template_layout_edit' => ['core.templates.read'],
|
||||
'admin_settings' => ['core.settings.read'],
|
||||
|
||||
// sirsoft-ecommerce 모듈
|
||||
'admin_ecommerce_product_list' => ['sirsoft-ecommerce.products.read'],
|
||||
'admin_ecommerce_product_form' => ['sirsoft-ecommerce.products.read'],
|
||||
'admin_ecommerce_brand_index' => ['sirsoft-ecommerce.brands.read'],
|
||||
'admin_ecommerce_category_index' => ['sirsoft-ecommerce.categories.read'],
|
||||
'admin_ecommerce_order_index' => ['sirsoft-ecommerce.orders.read'],
|
||||
'admin_ecommerce_order_list' => ['sirsoft-ecommerce.orders.read'],
|
||||
'admin_ecommerce_order_detail' => ['sirsoft-ecommerce.orders.read'],
|
||||
'admin_ecommerce_settings' => ['sirsoft-ecommerce.settings.read'],
|
||||
'admin_ecommerce_order_settings' => ['sirsoft-ecommerce.settings.read'],
|
||||
'admin_ecommerce_mileage_deposit_settings' => ['sirsoft-ecommerce.settings.read'],
|
||||
'admin_ecommerce_promotion_coupon_list' => ['sirsoft-ecommerce.promotion-coupon.read'],
|
||||
'admin_ecommerce_promotion_coupon_form' => ['sirsoft-ecommerce.promotion-coupon.read'],
|
||||
'admin_ecommerce_promotion_coupon_create' => ['sirsoft-ecommerce.promotion-coupon.read'],
|
||||
'admin_ecommerce_product_notice_index' => ['sirsoft-ecommerce.product-notice-templates.read'],
|
||||
|
||||
// sirsoft-board 모듈
|
||||
'admin_board_index' => ['sirsoft-board.boards.read'],
|
||||
'admin_board_form' => ['sirsoft-board.boards.read'],
|
||||
'admin_board_posts_index' => ['sirsoft-board.boards.read'],
|
||||
'admin_board_post_form' => ['sirsoft-board.boards.read'],
|
||||
'admin_board_post_detail' => ['sirsoft-board.boards.read'],
|
||||
'admin_board_reports_index' => ['sirsoft-board.reports.view'],
|
||||
'admin_board_reports_detail' => ['sirsoft-board.reports.view'],
|
||||
|
||||
// sirsoft-sample 모듈
|
||||
'admin_sample_index' => ['sirsoft-sample.items.view'],
|
||||
'admin_sample_edit' => ['sirsoft-sample.items.view'],
|
||||
|
||||
// sirsoft-daum_postcode 플러그인
|
||||
'plugin_settings' => ['core.plugins.update'],
|
||||
];
|
||||
|
||||
/**
|
||||
* 공개 레이아웃 목록 (권한 추가 제외)
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $publicLayouts = [
|
||||
// Base 레이아웃
|
||||
'_admin_base',
|
||||
'_user_base',
|
||||
|
||||
// 인증 페이지
|
||||
'admin_login',
|
||||
'login',
|
||||
'register',
|
||||
'forgot_password',
|
||||
'reset_password',
|
||||
|
||||
// 에러 페이지
|
||||
'403',
|
||||
'404',
|
||||
'500',
|
||||
'503',
|
||||
|
||||
// 테스트용
|
||||
'template_partial_test',
|
||||
'module_partial_test',
|
||||
];
|
||||
|
||||
/**
|
||||
* 처리 통계
|
||||
*
|
||||
* @var array<string, int>
|
||||
*/
|
||||
protected array $stats = [
|
||||
'scanned' => 0,
|
||||
'updated' => 0,
|
||||
'skipped' => 0,
|
||||
'errors' => 0,
|
||||
];
|
||||
|
||||
/**
|
||||
* 커맨드 실행
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$isDryRun = $this->option('dry-run');
|
||||
$targetLayout = $this->option('layout');
|
||||
$force = $this->option('force');
|
||||
|
||||
if ($isDryRun) {
|
||||
$this->info('🔍 시뮬레이션 모드로 실행합니다. (실제 파일 수정 없음)');
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
// 템플릿 레이아웃 처리
|
||||
$this->info('📁 템플릿 레이아웃 스캔 중...');
|
||||
$this->processTemplateLayouts($targetLayout, $isDryRun, $force);
|
||||
|
||||
// 모듈 레이아웃 처리
|
||||
$this->newLine();
|
||||
$this->info('📁 모듈 레이아웃 스캔 중...');
|
||||
$this->processModuleLayouts($targetLayout, $isDryRun, $force);
|
||||
|
||||
// 플러그인 레이아웃 처리
|
||||
$this->newLine();
|
||||
$this->info('📁 플러그인 레이아웃 스캔 중...');
|
||||
$this->processPluginLayouts($targetLayout, $isDryRun, $force);
|
||||
|
||||
// 결과 출력
|
||||
$this->newLine();
|
||||
$this->info('📊 처리 결과:');
|
||||
$this->table(
|
||||
['항목', '개수'],
|
||||
[
|
||||
['스캔된 레이아웃', $this->stats['scanned']],
|
||||
['업데이트됨', $this->stats['updated']],
|
||||
['건너뜀', $this->stats['skipped']],
|
||||
['오류', $this->stats['errors']],
|
||||
]
|
||||
);
|
||||
|
||||
if ($isDryRun && $this->stats['updated'] > 0) {
|
||||
$this->newLine();
|
||||
$this->warn('⚠️ --dry-run 옵션을 제거하면 실제로 파일이 수정됩니다.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 레이아웃 처리
|
||||
*/
|
||||
protected function processTemplateLayouts(?string $targetLayout, bool $isDryRun, bool $force): void
|
||||
{
|
||||
$templatesPath = base_path('templates');
|
||||
|
||||
if (! File::exists($templatesPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (File::directories($templatesPath) as $templateDir) {
|
||||
$layoutsPath = $templateDir . '/layouts';
|
||||
|
||||
if (! File::exists($layoutsPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->processLayoutDirectory($layoutsPath, $targetLayout, $isDryRun, $force);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 레이아웃 처리
|
||||
*/
|
||||
protected function processModuleLayouts(?string $targetLayout, bool $isDryRun, bool $force): void
|
||||
{
|
||||
$modulesPath = base_path('modules');
|
||||
|
||||
if (! File::exists($modulesPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (File::directories($modulesPath) as $moduleDir) {
|
||||
$layoutsPath = $moduleDir . '/resources/layouts';
|
||||
|
||||
if (! File::exists($layoutsPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->processLayoutDirectory($layoutsPath, $targetLayout, $isDryRun, $force);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 레이아웃 처리
|
||||
*/
|
||||
protected function processPluginLayouts(?string $targetLayout, bool $isDryRun, bool $force): void
|
||||
{
|
||||
$pluginsPath = base_path('plugins');
|
||||
|
||||
if (! File::exists($pluginsPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (File::directories($pluginsPath) as $pluginDir) {
|
||||
$layoutsPath = $pluginDir . '/resources/layouts';
|
||||
|
||||
if (! File::exists($layoutsPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->processLayoutDirectory($layoutsPath, $targetLayout, $isDryRun, $force);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 디렉토리 내 JSON 파일 처리
|
||||
*/
|
||||
protected function processLayoutDirectory(string $path, ?string $targetLayout, bool $isDryRun, bool $force): void
|
||||
{
|
||||
// 재귀적으로 모든 JSON 파일 검색
|
||||
$files = File::allFiles($path);
|
||||
|
||||
foreach ($files as $file) {
|
||||
if ($file->getExtension() !== 'json') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// partials 디렉토리는 건너뜀
|
||||
if (str_contains($file->getPathname(), '/partials/') || str_contains($file->getPathname(), '\\partials\\')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->processLayoutFile($file->getPathname(), $targetLayout, $isDryRun, $force);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 개별 레이아웃 파일 처리
|
||||
*/
|
||||
protected function processLayoutFile(string $filePath, ?string $targetLayout, bool $isDryRun, bool $force): void
|
||||
{
|
||||
$this->stats['scanned']++;
|
||||
|
||||
// JSON 파일 로드
|
||||
$content = File::get($filePath);
|
||||
$layout = json_decode($content, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$this->error(" ❌ JSON 파싱 실패: {$filePath}");
|
||||
$this->stats['errors']++;
|
||||
return;
|
||||
}
|
||||
|
||||
$layoutName = $layout['layout_name'] ?? pathinfo($filePath, PATHINFO_FILENAME);
|
||||
|
||||
// 특정 레이아웃만 처리하는 경우
|
||||
if ($targetLayout !== null && $layoutName !== $targetLayout) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 공개 레이아웃인 경우 건너뜀
|
||||
if ($this->isPublicLayout($layoutName)) {
|
||||
$this->line(" ⏭️ 건너뜀 (공개 레이아웃): {$layoutName}");
|
||||
$this->stats['skipped']++;
|
||||
return;
|
||||
}
|
||||
|
||||
// 이미 permissions가 있는 경우 (멱등성 보장)
|
||||
if (isset($layout['permissions']) && ! $force) {
|
||||
$this->line(" ⏭️ 건너뜀 (이미 존재): {$layoutName}");
|
||||
$this->stats['skipped']++;
|
||||
return;
|
||||
}
|
||||
|
||||
// permissions 결정: 매핑이 있으면 해당 권한, 없으면 빈 배열
|
||||
$permissions = $this->permissionMappings[$layoutName] ?? [];
|
||||
|
||||
// 로그 메시지 생성 (빈 배열/권한 있음 구분)
|
||||
$permissionDisplay = empty($permissions) ? '[] (공개)' : json_encode($permissions);
|
||||
|
||||
if ($isDryRun) {
|
||||
$this->info(" ✅ 업데이트 예정: {$layoutName} → {$permissionDisplay}");
|
||||
$this->stats['updated']++;
|
||||
return;
|
||||
}
|
||||
|
||||
// 실제 파일 수정
|
||||
$layout['permissions'] = $permissions;
|
||||
|
||||
// version 다음에 permissions 배치하기 위해 순서 재정렬
|
||||
$orderedLayout = $this->reorderLayoutKeys($layout);
|
||||
|
||||
$newContent = json_encode($orderedLayout, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
File::put($filePath, $newContent . "\n");
|
||||
|
||||
$this->info(" ✅ 업데이트됨: {$layoutName} → {$permissionDisplay}");
|
||||
$this->stats['updated']++;
|
||||
}
|
||||
|
||||
/**
|
||||
* 공개 레이아웃인지 확인
|
||||
*/
|
||||
protected function isPublicLayout(string $layoutName): bool
|
||||
{
|
||||
// 정확한 일치 확인
|
||||
if (in_array($layoutName, $this->publicLayouts, true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// _로 시작하는 베이스 레이아웃
|
||||
if (str_starts_with($layoutName, '_')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// auth/ 경로
|
||||
if (str_starts_with($layoutName, 'auth/') || str_starts_with($layoutName, 'auth_')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// errors/ 경로
|
||||
if (str_starts_with($layoutName, 'errors/') || str_starts_with($layoutName, 'errors_')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 키 순서 재정렬 (permissions를 version 다음에 배치)
|
||||
*/
|
||||
protected function reorderLayoutKeys(array $layout): array
|
||||
{
|
||||
$orderedKeys = [
|
||||
'version',
|
||||
'layout_name',
|
||||
'permissions',
|
||||
'extends',
|
||||
'endpoint',
|
||||
'meta',
|
||||
'state',
|
||||
'init_state',
|
||||
'computed',
|
||||
'data_sources',
|
||||
'defines',
|
||||
'init_actions',
|
||||
'components',
|
||||
'slots',
|
||||
'modals',
|
||||
'scripts',
|
||||
];
|
||||
|
||||
$ordered = [];
|
||||
|
||||
// 정의된 순서대로 키 배치
|
||||
foreach ($orderedKeys as $key) {
|
||||
if (array_key_exists($key, $layout)) {
|
||||
$ordered[$key] = $layout[$key];
|
||||
}
|
||||
}
|
||||
|
||||
// 나머지 키 추가 (정의되지 않은 키)
|
||||
foreach ($layout as $key => $value) {
|
||||
if (! array_key_exists($key, $ordered)) {
|
||||
$ordered[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $ordered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Events\Dashboard\DashboardUpdated;
|
||||
use App\Services\DashboardService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 시스템 리소스 정보를 주기적으로 브로드캐스트하는 커맨드
|
||||
*
|
||||
* 스케줄러를 통해 주기적으로 실행되어 대시보드에 실시간 시스템 리소스 정보를 전달합니다.
|
||||
*/
|
||||
class BroadcastDashboardResources extends Command
|
||||
{
|
||||
/**
|
||||
* 콘솔 명령어 시그니처
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'dashboard:broadcast-resources';
|
||||
|
||||
/**
|
||||
* 콘솔 명령어 설명
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '시스템 리소스 정보를 브로드캐스트합니다';
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @param DashboardService $dashboardService 대시보드 서비스
|
||||
* @return int
|
||||
*/
|
||||
public function handle(DashboardService $dashboardService): int
|
||||
{
|
||||
broadcast(new DashboardUpdated('resources', $dashboardService->getSystemResources()));
|
||||
|
||||
$this->info('시스템 리소스 정보가 브로드캐스트되었습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\LayoutPreviewService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 만료된 레이아웃 미리보기를 정리하는 커맨드
|
||||
*/
|
||||
class CleanupLayoutPreviewsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'layout-previews:cleanup';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '만료된 레이아웃 미리보기 데이터를 삭제합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @param LayoutPreviewService $service 미리보기 서비스
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(LayoutPreviewService $service): int
|
||||
{
|
||||
$deleted = $service->cleanupExpired();
|
||||
|
||||
$this->info("만료된 미리보기 {$deleted}건이 삭제되었습니다.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* JSON 컬럼의 \uXXXX 유니코드 이스케이프를 실제 UTF-8 문자로 변환합니다.
|
||||
*
|
||||
* PHP json_encode() 기본 동작은 멀티바이트 문자를 \uXXXX로 인코딩합니다.
|
||||
* MySQL FULLTEXT(ngram)은 실제 UTF-8 바이트만 토큰화하므로,
|
||||
* 기존 데이터를 JSON_UNESCAPED_UNICODE 형식으로 변환해야 합니다.
|
||||
*
|
||||
* 사용 예:
|
||||
* php artisan json:convert-unicode --dry-run # 변환 대상 건수 확인
|
||||
* php artisan json:convert-unicode # 실제 변환 실행
|
||||
*/
|
||||
class ConvertJsonUnicodeEscapes extends Command
|
||||
{
|
||||
/**
|
||||
* 콘솔 커맨드 시그니처
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'json:convert-unicode
|
||||
{--dry-run : 실제 변환 없이 대상 건수만 표시}
|
||||
{--table= : 특정 테이블만 변환 (예: ecommerce_products)}
|
||||
{--chunk=500 : 청크 크기}';
|
||||
|
||||
/**
|
||||
* 콘솔 커맨드 설명
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'JSON 컬럼의 \\uXXXX 유니코드 이스케이프를 실제 UTF-8 문자로 변환합니다.';
|
||||
|
||||
/**
|
||||
* 변환 대상 테이블 및 컬럼 정의
|
||||
*
|
||||
* @var array<string, string[]>
|
||||
*/
|
||||
private const TARGETS = [
|
||||
'ecommerce_products' => ['name', 'description'],
|
||||
'ecommerce_categories' => ['name', 'description'],
|
||||
'ecommerce_brands' => ['name'],
|
||||
'ecommerce_promotion_coupons' => ['name', 'description'],
|
||||
'ecommerce_product_common_infos' => ['name', 'content'],
|
||||
'boards' => ['name', 'description'],
|
||||
'boards_report_logs' => ['snapshot'],
|
||||
'pages' => ['title', 'content'],
|
||||
];
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = $this->option('dry-run');
|
||||
$targetTable = $this->option('table');
|
||||
$chunkSize = (int) $this->option('chunk');
|
||||
|
||||
if ($dryRun) {
|
||||
$this->components->info('Dry-run 모드: 실제 변환 없이 대상 건수만 표시합니다.');
|
||||
}
|
||||
|
||||
$targets = self::TARGETS;
|
||||
if ($targetTable) {
|
||||
if (! isset($targets[$targetTable])) {
|
||||
$this->components->error("알 수 없는 테이블: {$targetTable}");
|
||||
$this->components->info('사용 가능한 테이블: '.implode(', ', array_keys($targets)));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$targets = [$targetTable => $targets[$targetTable]];
|
||||
}
|
||||
|
||||
$totalConverted = 0;
|
||||
$totalSkipped = 0;
|
||||
|
||||
foreach ($targets as $table => $columns) {
|
||||
$prefix = DB::getTablePrefix();
|
||||
|
||||
if (! $this->tableExists($prefix.$table)) {
|
||||
$this->components->warn("{$table} 테이블이 존재하지 않습니다. 스킵합니다.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($columns as $column) {
|
||||
[$converted, $skipped] = $this->processColumn($table, $column, $chunkSize, $dryRun);
|
||||
$totalConverted += $converted;
|
||||
$totalSkipped += $skipped;
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
if ($dryRun) {
|
||||
$this->components->info("변환 대상: {$totalConverted}건, 스킵(이미 UTF-8): {$totalSkipped}건");
|
||||
} else {
|
||||
$this->components->info("변환 완료: {$totalConverted}건, 스킵(이미 UTF-8): {$totalSkipped}건");
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 테이블 존재 여부를 확인합니다.
|
||||
*
|
||||
* @param string $table 테이블명 (프리픽스 포함)
|
||||
* @return bool 존재 여부
|
||||
*/
|
||||
private function tableExists(string $table): bool
|
||||
{
|
||||
try {
|
||||
DB::select("SELECT 1 FROM `{$table}` LIMIT 1");
|
||||
|
||||
return true;
|
||||
} catch (\Exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 테이블의 특정 컬럼을 변환합니다.
|
||||
*
|
||||
* @param string $table 테이블명
|
||||
* @param string $column 컬럼명
|
||||
* @param int $chunkSize 청크 크기
|
||||
* @param bool $dryRun 드라이런 모드
|
||||
* @return array{int, int} [변환 건수, 스킵 건수]
|
||||
*/
|
||||
private function processColumn(string $table, string $column, int $chunkSize, bool $dryRun): array
|
||||
{
|
||||
$converted = 0;
|
||||
$skipped = 0;
|
||||
|
||||
// \uXXXX 패턴이 포함된 행만 조회 (이미 변환된 행은 스킵)
|
||||
$query = DB::table($table)
|
||||
->whereNotNull($column)
|
||||
->where($column, 'LIKE', '%\\\\u%');
|
||||
|
||||
$total = $query->count();
|
||||
|
||||
if ($total === 0) {
|
||||
$this->components->twoColumnDetail("{$table}.{$column}", '<fg=green>변환 대상 없음</>');
|
||||
|
||||
return [0, 0];
|
||||
}
|
||||
|
||||
$this->components->twoColumnDetail("{$table}.{$column}", "대상 {$total}건 처리 중...");
|
||||
|
||||
DB::table($table)
|
||||
->whereNotNull($column)
|
||||
->where($column, 'LIKE', '%\\\\u%')
|
||||
->orderBy('id')
|
||||
->chunk($chunkSize, function ($rows) use ($table, $column, $dryRun, &$converted, &$skipped) {
|
||||
foreach ($rows as $row) {
|
||||
$original = $row->{$column};
|
||||
$decoded = json_decode($original, true);
|
||||
|
||||
if ($decoded === null) {
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$reencoded = json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
// 변환 전후가 동일하면 스킵
|
||||
if ($reencoded === $original) {
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $dryRun) {
|
||||
DB::table($table)
|
||||
->where('id', $row->id)
|
||||
->update([$column => $reencoded]);
|
||||
}
|
||||
|
||||
$converted++;
|
||||
}
|
||||
});
|
||||
|
||||
$label = $dryRun ? '변환 대상' : '변환 완료';
|
||||
$this->components->twoColumnDetail(
|
||||
" └ {$label}",
|
||||
"<fg=yellow>{$converted}건</> (스킵: {$skipped}건)"
|
||||
);
|
||||
|
||||
return [$converted, $skipped];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* PHPUnit Doc-Comment Annotations를 PHP 8 Attributes로 변환하는 Artisan 커맨드
|
||||
*
|
||||
* @package App\Console\Commands
|
||||
* @author sirsoft
|
||||
*/
|
||||
class ConvertPHPUnitAnnotations extends Command
|
||||
{
|
||||
/**
|
||||
* 커맨드 시그니처
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'phpunit:convert-annotations
|
||||
{--dry-run : 변환 미리보기 (파일 수정 안 함)}
|
||||
{--backup : 변환 전 백업 생성 (.bak 파일)}
|
||||
{--path= : 특정 경로만 변환}
|
||||
{--stats-only : 통계만 출력}
|
||||
{--rollback : 백업에서 복원}';
|
||||
|
||||
/**
|
||||
* 커맨드 설명
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'PHPUnit doc-comment annotations를 PHP 8 attributes로 변환합니다';
|
||||
|
||||
/**
|
||||
* 변환기 인스턴스
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
private $converter;
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
// 스크립트 파일 로드
|
||||
$scriptPath = base_path('scripts/convert-phpunit-annotations.php');
|
||||
if (!file_exists($scriptPath)) {
|
||||
$this->error("스크립트 파일을 찾을 수 없습니다: {$scriptPath}");
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
require_once $scriptPath;
|
||||
|
||||
// 롤백 모드
|
||||
if ($this->option('rollback')) {
|
||||
return $this->handleRollback();
|
||||
}
|
||||
|
||||
// 통계만 확인
|
||||
if ($this->option('stats-only')) {
|
||||
return $this->handleStatsOnly();
|
||||
}
|
||||
|
||||
// 변환 실행
|
||||
return $this->handleConversion();
|
||||
}
|
||||
|
||||
/**
|
||||
* 통계만 확인합니다.
|
||||
*
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
private function handleStatsOnly(): int
|
||||
{
|
||||
$this->info('PHPUnit Annotation 통계 확인 중...');
|
||||
$this->newLine();
|
||||
|
||||
$converter = new \PHPUnitAnnotationConverter(false, false, false);
|
||||
$basePath = base_path();
|
||||
$specificPath = $this->option('path');
|
||||
|
||||
$stats = $converter->getStats($basePath, $specificPath);
|
||||
|
||||
$this->line('PHPUnit Annotation Conversion Statistics');
|
||||
$this->line('=========================================');
|
||||
$this->line("총 테스트 파일: {$stats['total_files']}");
|
||||
$this->line("Annotations이 있는 파일: {$stats['files_with_annotations']}");
|
||||
$this->newLine();
|
||||
|
||||
$this->line('Annotation 분류:');
|
||||
$this->line("- @test: {$stats['test']}");
|
||||
$this->line("- @dataProvider: {$stats['dataProvider']}");
|
||||
$this->line("- @group: {$stats['group']}");
|
||||
$this->line("- @depends: {$stats['depends']}");
|
||||
$this->newLine();
|
||||
|
||||
if (!empty($stats['files'])) {
|
||||
$this->line('파일별 상세:');
|
||||
foreach ($stats['files'] as $fileInfo) {
|
||||
$relativePath = str_replace(base_path() . DIRECTORY_SEPARATOR, '', $fileInfo['path']);
|
||||
$this->line(" {$relativePath}");
|
||||
foreach ($fileInfo['annotations'] as $annotation) {
|
||||
$this->line(" - {$annotation}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 변환을 실행합니다.
|
||||
*
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
private function handleConversion(): int
|
||||
{
|
||||
$dryRun = $this->option('dry-run');
|
||||
$backup = $this->option('backup');
|
||||
$verbose = $this->option('verbose');
|
||||
|
||||
if ($dryRun) {
|
||||
$this->warn('[DRY RUN] 변환 미리보기 모드 - 실제 파일은 수정되지 않습니다');
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
if ($backup && !$dryRun) {
|
||||
$this->info('백업 모드 활성화 - 변환 전 .bak 파일이 생성됩니다');
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
$this->converter = new \PHPUnitAnnotationConverter($dryRun, $backup, $verbose);
|
||||
|
||||
$basePath = base_path();
|
||||
$specificPath = $this->option('path');
|
||||
|
||||
// 파일 스캔
|
||||
$this->info('테스트 파일 스캔 중...');
|
||||
$files = $this->converter->scanTestFiles($basePath, $specificPath);
|
||||
|
||||
if (empty($files)) {
|
||||
$this->warn('변환할 테스트 파일을 찾을 수 없습니다.');
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info('총 ' . count($files) . '개의 테스트 파일을 발견했습니다.');
|
||||
$this->newLine();
|
||||
|
||||
// 프로그레스 바 생성
|
||||
$bar = $this->output->createProgressBar(count($files));
|
||||
$bar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %message%');
|
||||
$bar->setMessage('변환 시작...');
|
||||
|
||||
if (!$verbose) {
|
||||
$bar->start();
|
||||
}
|
||||
|
||||
$convertedCount = 0;
|
||||
|
||||
foreach ($files as $file) {
|
||||
$relativePath = str_replace(base_path() . DIRECTORY_SEPARATOR, '', $file);
|
||||
|
||||
if ($verbose) {
|
||||
$this->line("처리 중: {$relativePath}");
|
||||
} else {
|
||||
$bar->setMessage($relativePath);
|
||||
}
|
||||
|
||||
if ($this->converter->convertFile($file)) {
|
||||
$convertedCount++;
|
||||
}
|
||||
|
||||
if (!$verbose) {
|
||||
$bar->advance();
|
||||
}
|
||||
}
|
||||
|
||||
if (!$verbose) {
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
}
|
||||
|
||||
// 결과 출력
|
||||
$report = $this->converter->generateReport();
|
||||
$this->line($report);
|
||||
|
||||
if ($dryRun) {
|
||||
$this->info('Dry-run 완료 - 실제 파일은 변경되지 않았습니다.');
|
||||
$this->info('실제 변환을 수행하려면 --dry-run 옵션 없이 실행하세요.');
|
||||
} else {
|
||||
$this->info('변환 완료!');
|
||||
if ($backup) {
|
||||
$this->info('.bak 백업 파일이 생성되었습니다.');
|
||||
$this->warn('테스트 실행 후 문제가 없으면 백업 파일을 삭제하세요:');
|
||||
$this->line(' find tests modules plugins -name "*.bak" -delete');
|
||||
}
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 백업에서 복원합니다.
|
||||
*
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
private function handleRollback(): int
|
||||
{
|
||||
$this->warn('백업 복원 기능은 현재 구현되지 않았습니다.');
|
||||
$this->info('수동으로 .bak 파일을 복원하세요:');
|
||||
$this->line(' for file in $(find . -name "*.bak"); do mv "$file" "${file%.bak}"; done');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Core;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
class BuildCoreCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'core:build
|
||||
{--watch : 파일 변경 감시 모드}
|
||||
{--production : 프로덕션 빌드}
|
||||
{--full : 전체 빌드 (npm run build)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '그누보드7 코어 프론트엔드 에셋을 빌드합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$watchMode = $this->option('watch');
|
||||
$productionMode = $this->option('production');
|
||||
$full = $this->option('full');
|
||||
|
||||
try {
|
||||
$projectPath = base_path();
|
||||
$packageJsonPath = $projectPath.'/package.json';
|
||||
|
||||
// package.json 존재 확인
|
||||
if (! file_exists($packageJsonPath)) {
|
||||
$this->error('❌ package.json 파일이 없습니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// node_modules 확인 및 설치
|
||||
if (! is_dir($projectPath.'/node_modules')) {
|
||||
$this->info('📦 의존성 설치 중...');
|
||||
$installResult = $this->runNpmCommand(['npm', 'install'], $projectPath);
|
||||
|
||||
if ($installResult !== Command::SUCCESS) {
|
||||
$this->error('❌ npm install 실패');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
// 빌드 유형 결정: 기본은 템플릿 엔진만 빌드
|
||||
if ($full) {
|
||||
return $this->buildFull($projectPath, $watchMode, $productionMode);
|
||||
}
|
||||
|
||||
return $this->buildEngineOnly($projectPath, $watchMode, $productionMode);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('코어 빌드 실패', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 엔진만 빌드 (build:core)
|
||||
*
|
||||
* @param string $projectPath 프로젝트 경로
|
||||
* @param bool $watchMode 파일 감시 모드
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildEngineOnly(string $projectPath, bool $watchMode, bool $productionMode): int
|
||||
{
|
||||
$buildCommand = ['npm', 'run'];
|
||||
|
||||
if ($watchMode) {
|
||||
// build:core는 watch 모드가 없으므로 dev 사용
|
||||
$buildCommand[] = 'dev';
|
||||
$this->info('👀 파일 감시 모드로 코어 빌드 시작 (템플릿 엔진)');
|
||||
$this->line(' Ctrl+C로 종료할 수 있습니다.');
|
||||
} else {
|
||||
$buildCommand[] = 'build:core';
|
||||
$this->info('🔨 코어 빌드 시작 (템플릿 엔진)'.($productionMode ? ' (프로덕션)' : ''));
|
||||
}
|
||||
|
||||
$result = $this->runNpmCommand($buildCommand, $projectPath, ! $watchMode);
|
||||
|
||||
if ($result === Command::SUCCESS && ! $watchMode) {
|
||||
$this->info('✅ 코어 빌드 완료 (템플릿 엔진)');
|
||||
$this->showEngineBuildResults($projectPath);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 빌드
|
||||
*
|
||||
* @param string $projectPath 프로젝트 경로
|
||||
* @param bool $watchMode 파일 감시 모드
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildFull(string $projectPath, bool $watchMode, bool $productionMode): int
|
||||
{
|
||||
$buildCommand = ['npm', 'run'];
|
||||
|
||||
if ($watchMode) {
|
||||
$buildCommand[] = 'dev';
|
||||
$this->info('👀 파일 감시 모드로 코어 빌드 시작 (전체)');
|
||||
$this->line(' Ctrl+C로 종료할 수 있습니다.');
|
||||
} else {
|
||||
$buildCommand[] = 'build';
|
||||
$this->info('🔨 코어 빌드 시작 (전체)'.($productionMode ? ' (프로덕션)' : ''));
|
||||
}
|
||||
|
||||
$result = $this->runNpmCommand($buildCommand, $projectPath, ! $watchMode);
|
||||
|
||||
if ($result === Command::SUCCESS && ! $watchMode) {
|
||||
$this->info('✅ 코어 빌드 완료 (전체)');
|
||||
$this->showFullBuildResults($projectPath);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 엔진 빌드 결과 출력
|
||||
*
|
||||
* @param string $projectPath 프로젝트 경로
|
||||
*/
|
||||
private function showEngineBuildResults(string $projectPath): void
|
||||
{
|
||||
$corePath = $projectPath.'/public/build/core';
|
||||
|
||||
if (! is_dir($corePath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->line(' 빌드 결과:');
|
||||
|
||||
// template-engine.min.js 확인
|
||||
$engineFile = $corePath.'/template-engine.min.js';
|
||||
if (file_exists($engineFile)) {
|
||||
$fileSize = number_format(filesize($engineFile) / 1024, 2);
|
||||
$this->line(" - template-engine.min.js ({$fileSize} KB)");
|
||||
}
|
||||
|
||||
// lang 파일 확인
|
||||
$langPath = $corePath.'/lang';
|
||||
if (is_dir($langPath)) {
|
||||
$langFiles = glob($langPath.'/*.json');
|
||||
foreach ($langFiles as $langFile) {
|
||||
$fileName = 'lang/'.basename($langFile);
|
||||
$fileSize = number_format(filesize($langFile) / 1024, 2);
|
||||
$this->line(" - {$fileName} ({$fileSize} KB)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 빌드 결과 출력
|
||||
*
|
||||
* @param string $projectPath 프로젝트 경로
|
||||
*/
|
||||
private function showFullBuildResults(string $projectPath): void
|
||||
{
|
||||
$buildPath = $projectPath.'/public/build';
|
||||
|
||||
if (! is_dir($buildPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->line(' 빌드 결과:');
|
||||
|
||||
// manifest.json 확인
|
||||
$manifestPath = $buildPath.'/manifest.json';
|
||||
if (file_exists($manifestPath)) {
|
||||
$manifest = json_decode(file_get_contents($manifestPath), true);
|
||||
if ($manifest) {
|
||||
foreach ($manifest as $source => $info) {
|
||||
if (is_array($info) && isset($info['file'])) {
|
||||
$filePath = $buildPath.'/'.$info['file'];
|
||||
if (file_exists($filePath)) {
|
||||
$fileName = $info['file'];
|
||||
$fileSize = number_format(filesize($filePath) / 1024, 2);
|
||||
$this->line(" - {$fileName} ({$fileSize} KB)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// manifest가 없으면 직접 파일 탐색
|
||||
$this->scanBuildFiles($buildPath, 'assets');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드 파일 스캔 및 출력
|
||||
*
|
||||
* @param string $buildPath 빌드 경로
|
||||
* @param string $subDir 하위 디렉토리
|
||||
*/
|
||||
private function scanBuildFiles(string $buildPath, string $subDir): void
|
||||
{
|
||||
$assetsPath = $buildPath.'/'.$subDir;
|
||||
|
||||
if (! is_dir($assetsPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$files = scandir($assetsPath);
|
||||
foreach ($files as $file) {
|
||||
if ($file === '.' || $file === '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filePath = $assetsPath.'/'.$file;
|
||||
if (is_file($filePath)) {
|
||||
$fileName = $subDir.'/'.$file;
|
||||
$fileSize = number_format(filesize($filePath) / 1024, 2);
|
||||
$this->line(" - {$fileName} ({$fileSize} KB)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* npm 명령 실행
|
||||
*
|
||||
* @param array $command 실행할 명령
|
||||
* @param string $cwd 작업 디렉토리
|
||||
* @param bool $waitForCompletion 완료 대기 여부
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function runNpmCommand(array $command, string $cwd, bool $waitForCompletion = true): int
|
||||
{
|
||||
// Windows 환경에서는 cmd /c 사용
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
$command = array_merge(['cmd', '/c'], $command);
|
||||
}
|
||||
|
||||
$process = new Process($command);
|
||||
$process->setWorkingDirectory($cwd);
|
||||
$process->setTimeout(null); // 타임아웃 없음
|
||||
|
||||
if ($waitForCompletion) {
|
||||
$process->run(function ($type, $buffer) {
|
||||
// 출력 표시
|
||||
if ($type === Process::ERR) {
|
||||
// stderr이지만 npm은 정상 출력도 stderr로 보내므로 그냥 표시
|
||||
$this->output->write($buffer);
|
||||
} else {
|
||||
$this->output->write($buffer);
|
||||
}
|
||||
});
|
||||
|
||||
return $process->isSuccessful() ? Command::SUCCESS : Command::FAILURE;
|
||||
}
|
||||
|
||||
// 감시 모드: 인터럽트까지 실행
|
||||
$process->start(function ($type, $buffer) {
|
||||
$this->output->write($buffer);
|
||||
});
|
||||
|
||||
// 프로세스가 실행 중인 동안 대기
|
||||
while ($process->isRunning()) {
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Core;
|
||||
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class CheckCoreUpdatesCommand extends Command
|
||||
{
|
||||
protected $signature = 'core:check-updates';
|
||||
|
||||
protected $description = '그누보드7 코어의 최신 업데이트를 확인합니다';
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @param CoreUpdateService $service 코어 업데이트 서비스
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(CoreUpdateService $service): int
|
||||
{
|
||||
$this->info('코어 업데이트를 확인 중...');
|
||||
|
||||
$result = $service->checkForUpdates();
|
||||
|
||||
$this->newLine();
|
||||
$this->info("현재 버전: {$result['current_version']}");
|
||||
$this->info("최신 버전: {$result['latest_version']}");
|
||||
|
||||
if (! empty($result['check_failed'])) {
|
||||
$this->newLine();
|
||||
$this->error('업데이트 확인 실패: '.($result['error'] ?? '알 수 없는 오류'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if ($result['update_available']) {
|
||||
$this->newLine();
|
||||
$this->warn('새로운 업데이트가 있습니다!');
|
||||
$this->info('업데이트하려면: php artisan core:update');
|
||||
} else {
|
||||
$this->newLine();
|
||||
$this->info('현재 최신 버전입니다.');
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Core;
|
||||
|
||||
use App\Extension\CoreVersionChecker;
|
||||
use App\Extension\Helpers\CoreBackupHelper;
|
||||
use App\Services\CoreUpdateService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CoreUpdateCommand extends Command
|
||||
{
|
||||
protected $signature = 'core:update
|
||||
{--force : 버전 비교 없이 강제 업데이트}
|
||||
{--no-backup : 백업 생성 건너뛰기}
|
||||
{--no-maintenance : 유지보수 모드 활성화 건너뛰기}
|
||||
{--local : 로컬 코드베이스를 업데이트 소스로 사용 (GitHub 스킵)}
|
||||
{--source= : 수동 업데이트용 소스 디렉토리 경로 (GitHub 다운로드 대신 지정 디렉토리 사용)}';
|
||||
|
||||
protected $description = '그누보드7 코어를 최신 버전으로 업데이트합니다';
|
||||
|
||||
private const TOTAL_STEPS = 11;
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @param CoreUpdateService $service 코어 업데이트 서비스
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(CoreUpdateService $service): int
|
||||
{
|
||||
$backupPath = null;
|
||||
$maintenanceEnabled = false;
|
||||
$fromVersion = CoreVersionChecker::getCoreVersion();
|
||||
$toVersion = $fromVersion;
|
||||
$secret = null;
|
||||
$logEntries = [];
|
||||
|
||||
$log = function (string $message) use (&$logEntries) {
|
||||
$logEntries[] = '['.date('H:i:s').'] '.$message;
|
||||
};
|
||||
|
||||
$sourceDir = $this->option('source');
|
||||
|
||||
try {
|
||||
// ── 시스템 요구사항 검증 (--source / --local 모드에서는 스킵) ──
|
||||
if (! $sourceDir && ! $this->option('local')) {
|
||||
$requirements = $service->checkSystemRequirements();
|
||||
if (! $requirements['valid']) {
|
||||
$this->error(__('settings.core_update.system_requirements_failed'));
|
||||
foreach ($requirements['errors'] as $error) {
|
||||
$this->error(" - {$error}");
|
||||
}
|
||||
$this->newLine();
|
||||
$this->info(__('settings.core_update.manual_update_guide'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$log('사용 가능한 추출 방법: '.implode(', ', $requirements['available_methods']));
|
||||
}
|
||||
|
||||
// --source 옵션 검증
|
||||
if ($sourceDir) {
|
||||
$sourceDir = realpath($sourceDir);
|
||||
if (! $sourceDir || ! is_dir($sourceDir)) {
|
||||
$this->error('지정된 소스 디렉토리가 존재하지 않습니다: '.($this->option('source')));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
$log("수동 업데이트 모드: 소스 디렉토리 = {$sourceDir}");
|
||||
}
|
||||
|
||||
// ── Step 1: 업데이트 확인 (프로그레스바 없이) ──
|
||||
$this->info(__('settings.core_update.step_check').'...');
|
||||
$log('업데이트 확인 시작');
|
||||
|
||||
if ($sourceDir || $this->option('local')) {
|
||||
// --source / --local 모드: GitHub 스킵, 소스의 버전 읽기 또는 시뮬레이션
|
||||
if ($sourceDir) {
|
||||
$sourceConfigPath = $sourceDir.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'app.php';
|
||||
if (file_exists($sourceConfigPath)) {
|
||||
// env() 호출을 우회하여 소스의 default 버전값을 직접 파싱
|
||||
$configContent = file_get_contents($sourceConfigPath);
|
||||
if (preg_match("/['\"]version['\"]\s*=>\s*env\s*\(\s*['\"]APP_VERSION['\"]\s*,\s*['\"]([^'\"]+)['\"]\s*\)/", $configContent, $versionMatch)) {
|
||||
$toVersion = $versionMatch[1];
|
||||
} else {
|
||||
$sourceConfig = include $sourceConfigPath;
|
||||
$toVersion = $sourceConfig['version'] ?? $fromVersion;
|
||||
}
|
||||
}
|
||||
$log("수동 업데이트 모드: {$fromVersion} → {$toVersion}");
|
||||
} else {
|
||||
$parts = explode('.', $fromVersion);
|
||||
$parts[count($parts) - 1] = (int) end($parts) + 1;
|
||||
$toVersion = implode('.', $parts);
|
||||
$log("로컬 모드: {$fromVersion} → {$toVersion} 시뮬레이션");
|
||||
}
|
||||
} else {
|
||||
$updateInfo = $service->checkForUpdates();
|
||||
$toVersion = $updateInfo['latest_version'];
|
||||
|
||||
if (! empty($updateInfo['check_failed'])) {
|
||||
$this->error('업데이트 확인 실패: '.($updateInfo['error'] ?? __('settings.core_update.unknown_error')));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if (! $updateInfo['update_available'] && ! $this->option('force')) {
|
||||
$this->info("현재 최신 버전입니다: {$fromVersion}");
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
// 사용자 확인
|
||||
$this->newLine();
|
||||
$this->info("현재 버전: {$fromVersion}");
|
||||
$this->info("업데이트 버전: {$toVersion}");
|
||||
$this->newLine();
|
||||
|
||||
if (! $this->confirm('코어를 업데이트하시겠습니까?')) {
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// Step 2~10 프로그레스바 (9단계)
|
||||
$remainingSteps = self::TOTAL_STEPS - 1;
|
||||
$bar = $this->output->createProgressBar($remainingSteps);
|
||||
$bar->setFormat(' %current%/%max% [%bar%] %message%');
|
||||
$bar->start();
|
||||
|
||||
$onProgress = function (?string $step, ?string $detail) use ($bar) {
|
||||
if ($detail) {
|
||||
$bar->setMessage($detail);
|
||||
}
|
||||
$bar->display();
|
||||
};
|
||||
|
||||
// ── Step 2: _pending 경로 검증 ──
|
||||
$bar->setMessage(__('settings.core_update.step_validate_pending'));
|
||||
$bar->advance();
|
||||
$log('_pending 경로 검증');
|
||||
|
||||
$validation = $service->validatePendingPath();
|
||||
if (! $validation['valid']) {
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
$this->error('_pending 디렉토리 문제:');
|
||||
foreach ($validation['errors'] as $error) {
|
||||
$this->error(" - {$error}");
|
||||
}
|
||||
$this->info("경로: {$validation['path']}");
|
||||
$this->info("소유자: {$validation['owner']}, 그룹: {$validation['group']}, 퍼미션: {$validation['permissions']}");
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// ── Step 3: Maintenance 모드 ──
|
||||
$bar->setMessage(__('settings.core_update.step_maintenance'));
|
||||
$bar->advance();
|
||||
|
||||
if (! $this->option('no-maintenance')) {
|
||||
$secret = $service->enableMaintenanceMode();
|
||||
$maintenanceEnabled = true;
|
||||
$log("유지보수 모드 활성화 (secret: {$secret})");
|
||||
}
|
||||
|
||||
// ── Step 4: 다운로드 ──
|
||||
if ($sourceDir) {
|
||||
$bar->setMessage('소스 디렉토리 검증 중...');
|
||||
} elseif ($this->option('local')) {
|
||||
$bar->setMessage('로컬 소스 복제 중...');
|
||||
} else {
|
||||
$bar->setMessage(__('settings.core_update.step_download'));
|
||||
}
|
||||
$bar->advance();
|
||||
|
||||
if ($sourceDir) {
|
||||
$log('수동 업데이트: 소스 디렉토리 검증');
|
||||
$service->validatePendingUpdate($sourceDir);
|
||||
|
||||
// 원본 소스를 _pending으로 복제 (원본 보호)
|
||||
$pendingPath = $service->copySourceToPending($sourceDir, $onProgress);
|
||||
$log("소스 디렉토리를 _pending으로 복제 완료: {$pendingPath}");
|
||||
} elseif ($this->option('local')) {
|
||||
$log('로컬 소스 복제 시작');
|
||||
$pendingPath = $service->prepareLocalSource($onProgress);
|
||||
$log('로컬 소스 복제 완료');
|
||||
} else {
|
||||
$log("버전 {$toVersion} 다운로드 시작");
|
||||
$pendingPath = $service->downloadUpdate($toVersion, $onProgress);
|
||||
$log('다운로드 및 검증 완료');
|
||||
}
|
||||
|
||||
// ── Step 5: 백업 ──
|
||||
$bar->setMessage(__('settings.core_update.step_backup'));
|
||||
$bar->advance();
|
||||
|
||||
if (! $this->option('no-backup')) {
|
||||
$backupPath = $service->createBackup($onProgress);
|
||||
$log("백업 생성 완료: {$backupPath}");
|
||||
}
|
||||
|
||||
// ── Step 6: _pending에서 Composer Install ──
|
||||
$composerSkipped = $service->isComposerUnchangedForCore($pendingPath);
|
||||
|
||||
if ($composerSkipped) {
|
||||
$bar->setMessage('Composer 의존성 변경 없음 — 스킵');
|
||||
$bar->advance();
|
||||
$log('composer.json/lock 변경 없음, composer install 스킵');
|
||||
} else {
|
||||
$bar->setMessage(__('settings.core_update.step_composer'));
|
||||
$bar->advance();
|
||||
$log('_pending에서 composer install 시작');
|
||||
|
||||
$service->runComposerInstallInPending($pendingPath, $onProgress);
|
||||
$log('_pending에서 composer install 완료');
|
||||
}
|
||||
|
||||
// ── Step 7: 파일 적용 ──
|
||||
$bar->setMessage(__('settings.core_update.step_apply'));
|
||||
$bar->advance();
|
||||
$log('코어 파일 덮어쓰기 시작');
|
||||
|
||||
$service->applyUpdate($pendingPath, $onProgress);
|
||||
$log('코어 파일 덮어쓰기 완료');
|
||||
|
||||
// ── Step 8: vendor 디렉토리 복사 (_pending → 운영) ──
|
||||
if ($composerSkipped) {
|
||||
$bar->setMessage('vendor 복사 스킵');
|
||||
$bar->advance();
|
||||
$log('composer 스킵 → vendor 디렉토리 복사 불필요');
|
||||
} else {
|
||||
$bar->setMessage(__('settings.core_update.step_composer_prod'));
|
||||
$bar->advance();
|
||||
$log('vendor 디렉토리 복사 시작');
|
||||
|
||||
$service->copyVendorFromPending($pendingPath, $onProgress);
|
||||
$log('vendor 디렉토리 복사 완료');
|
||||
}
|
||||
|
||||
// ── Step 9: Migration + 역할/메뉴 동기화 ──
|
||||
$bar->setMessage(__('settings.core_update.step_migration'));
|
||||
$bar->advance();
|
||||
$log('마이그레이션, 역할/메뉴/메일템플릿 동기화 실행');
|
||||
|
||||
$service->runMigrations();
|
||||
$service->syncCoreRolesAndPermissions();
|
||||
$service->syncCoreMenus();
|
||||
$service->syncCoreMailTemplates();
|
||||
$log('마이그레이션, 역할/메뉴/메일템플릿 동기화 완료');
|
||||
|
||||
// ── Step 10: Upgrade Steps ──
|
||||
$bar->setMessage(__('settings.core_update.step_upgrade'));
|
||||
$bar->advance();
|
||||
$log('업그레이드 스텝 실행');
|
||||
|
||||
$service->runUpgradeSteps($fromVersion, $toVersion, function (string $version) use ($bar, $log) {
|
||||
$bar->setMessage(__('settings.core_update.step_upgrade')." ({$version})");
|
||||
$bar->display();
|
||||
$log("업그레이드 스텝 실행: {$version}");
|
||||
});
|
||||
$log('업그레이드 스텝 완료');
|
||||
|
||||
// ── Step 11: Cleanup ──
|
||||
$bar->setMessage(__('settings.core_update.step_cleanup'));
|
||||
$bar->advance();
|
||||
|
||||
$service->updateVersionInEnv($toVersion);
|
||||
$service->clearAllCaches();
|
||||
|
||||
$service->cleanupPending($pendingPath);
|
||||
|
||||
if ($backupPath) {
|
||||
CoreBackupHelper::deleteBackup($backupPath);
|
||||
}
|
||||
|
||||
if ($maintenanceEnabled) {
|
||||
$service->disableMaintenanceMode();
|
||||
$maintenanceEnabled = false;
|
||||
}
|
||||
|
||||
$log('정리 완료');
|
||||
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
// 설치 로그 저장
|
||||
$this->saveUpdateLog($logEntries, $fromVersion, $toVersion, true);
|
||||
|
||||
$this->info("그누보드7 코어가 {$toVersion} 버전으로 업데이트되었습니다!");
|
||||
$this->newLine();
|
||||
$this->warn('_bundled 확장이 업데이트되었습니다. 활성 확장에 반영하려면 다음 커맨드를 실행하세요:');
|
||||
$this->line(' php artisan module:update <identifier> --force');
|
||||
$this->line(' php artisan plugin:update <identifier> --force');
|
||||
$this->line(' php artisan template:update <identifier> --force');
|
||||
|
||||
return Command::SUCCESS;
|
||||
|
||||
} catch (\Throwable $e) {
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
$log("오류 발생: {$e->getMessage()}");
|
||||
|
||||
// 롤백
|
||||
$restoreSuccess = false;
|
||||
$failedTargets = [];
|
||||
|
||||
if ($backupPath) {
|
||||
$this->warn('백업에서 복원 중...');
|
||||
$log('백업 복원 시작');
|
||||
|
||||
try {
|
||||
$failedTargets = $service->restoreFromBackup($backupPath, $onProgress);
|
||||
|
||||
if (empty($failedTargets)) {
|
||||
$log('백업 복원 완료');
|
||||
$this->info('백업에서 복원되었습니다.');
|
||||
$restoreSuccess = true;
|
||||
} else {
|
||||
$log('백업 부분 복원 완료 (실패: '.implode(', ', $failedTargets).')');
|
||||
$this->warn('백업에서 부분 복원되었습니다.');
|
||||
$this->error('복원 실패 항목: '.implode(', ', $failedTargets));
|
||||
}
|
||||
} catch (\Throwable $restoreError) {
|
||||
$log("백업 복원 실패: {$restoreError->getMessage()}");
|
||||
$this->error("백업 복원 실패: {$restoreError->getMessage()}");
|
||||
}
|
||||
}
|
||||
|
||||
// _pending 정리 (실패 시에도)
|
||||
if (! empty($pendingPath)) {
|
||||
$service->cleanupPending($pendingPath);
|
||||
}
|
||||
|
||||
// 실패 리포트
|
||||
$reportPath = $service->generateFailureReport($e, $fromVersion, $toVersion);
|
||||
|
||||
// 설치 로그 저장
|
||||
$this->saveUpdateLog($logEntries, $fromVersion, $toVersion, false);
|
||||
|
||||
$this->error("코어 업데이트 실패: {$e->getMessage()}");
|
||||
$this->info("실패 리포트: {$reportPath}");
|
||||
|
||||
if ($maintenanceEnabled) {
|
||||
$this->newLine();
|
||||
|
||||
if ($restoreSuccess) {
|
||||
// 완전 복원 성공 → 자동 유지보수 해제
|
||||
try {
|
||||
$service->disableMaintenanceMode();
|
||||
$maintenanceEnabled = false;
|
||||
$this->info('복원 완료: 유지보수 모드가 해제되었습니다.');
|
||||
} catch (\Throwable) {
|
||||
$this->warn('유지보수 모드 해제 실패. 수동으로 해제하세요: php artisan up');
|
||||
}
|
||||
} else {
|
||||
// 복원 실패 또는 부분 복원 → 수동 복구 안내
|
||||
$this->warn('유지보수 모드가 유지됩니다.');
|
||||
|
||||
if (! empty($failedTargets) || ! $backupPath) {
|
||||
$this->newLine();
|
||||
$this->error('수동 복구가 필요합니다:');
|
||||
if ($backupPath) {
|
||||
$this->line(" 1. 백업에서 수동 복원: cp -r {$backupPath}/* ".base_path().'/');
|
||||
}
|
||||
$this->line(' '.($backupPath ? '2' : '1').'. Composer 재설치: composer install --no-dev --optimize-autoloader');
|
||||
$this->line(' '.($backupPath ? '3' : '2').'. 유지보수 해제: php artisan up');
|
||||
} else {
|
||||
$this->info('이전 버전으로 사이트를 운영하려면: php artisan up');
|
||||
}
|
||||
|
||||
if ($secret) {
|
||||
$this->info("관리자 접근: {$secret}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 업데이트 로그를 파일로 저장합니다.
|
||||
*
|
||||
* @param array $entries 로그 엔트리 목록
|
||||
* @param string $fromVersion 시작 버전
|
||||
* @param string $toVersion 종료 버전
|
||||
* @param bool $success 성공 여부
|
||||
*/
|
||||
private function saveUpdateLog(array $entries, string $fromVersion, string $toVersion, bool $success): void
|
||||
{
|
||||
$timestamp = date('Ymd_His');
|
||||
$status = $success ? 'success' : 'failed';
|
||||
$logPath = storage_path("logs/core_update_{$status}_{$timestamp}.log");
|
||||
|
||||
$header = implode("\n", [
|
||||
'=== 그누보드7 코어 업데이트 로그 ===',
|
||||
'상태: '.($success ? '성공' : '실패'),
|
||||
'날짜: '.date('Y-m-d H:i:s'),
|
||||
"시작 버전: {$fromVersion}",
|
||||
"대상 버전: {$toVersion}",
|
||||
'',
|
||||
'=== 실행 로그 ===',
|
||||
]);
|
||||
|
||||
$content = $header."\n".implode("\n", $entries)."\n";
|
||||
|
||||
file_put_contents($logPath, $content);
|
||||
|
||||
Log::info("코어 업데이트 로그 저장: {$logPath}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Extension;
|
||||
|
||||
use App\Extension\CoreVersionChecker;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 확장 버전 검증 캐시 삭제 커맨드
|
||||
*
|
||||
* 확장(모듈, 플러그인, 템플릿)의 코어 버전 호환성 검증 캐시를 삭제합니다.
|
||||
* 코어 버전 업데이트 후 또는 수동으로 버전 검증을 다시 수행해야 할 때 사용합니다.
|
||||
*/
|
||||
class ClearVersionCacheCommand extends Command
|
||||
{
|
||||
/**
|
||||
* 커맨드 시그니처
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'extension:clear-version-cache';
|
||||
|
||||
/**
|
||||
* 커맨드 설명
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '확장 버전 검증 캐시를 삭제합니다';
|
||||
|
||||
/**
|
||||
* 커맨드 실행
|
||||
*
|
||||
* @return int 실행 결과 코드
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
CoreVersionChecker::clearCache();
|
||||
|
||||
$this->info(__('extensions.commands.clear_cache_success'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Extension;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class ComposerInstallAllCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'extension:composer-install
|
||||
{--no-dev : dev 의존성 제외}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모든 모듈과 플러그인의 Composer 의존성을 설치합니다';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$noDev = $this->option('no-dev');
|
||||
$noDevOption = $noDev ? ' --no-dev' : '';
|
||||
|
||||
$this->info('📦 모든 확장의 Composer 의존성 설치 시작');
|
||||
$this->line('');
|
||||
|
||||
// 모듈 Composer 설치
|
||||
$this->info('=== 모듈 ===');
|
||||
$moduleResult = $this->call('module:composer-install', [
|
||||
'--all' => true,
|
||||
'--no-dev' => $noDev,
|
||||
]);
|
||||
$this->line('');
|
||||
|
||||
// 플러그인 Composer 설치
|
||||
$this->info('=== 플러그인 ===');
|
||||
$pluginResult = $this->call('plugin:composer-install', [
|
||||
'--all' => true,
|
||||
'--no-dev' => $noDev,
|
||||
]);
|
||||
$this->line('');
|
||||
|
||||
if ($moduleResult === Command::SUCCESS && $pluginResult === Command::SUCCESS) {
|
||||
$this->info('✅ 모든 확장의 Composer 의존성 설치 완료');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->warn('⚠️ 일부 확장의 Composer 의존성 설치에 실패했습니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Extension;
|
||||
|
||||
use App\Extension\ExtensionManager;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class UpdateAutoloadCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'extension:update-autoload';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '모듈과 플러그인의 오토로드 캐시 파일을 생성합니다 (bootstrap/cache/autoload-extensions.php)';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ExtensionManager $extensionManager): int
|
||||
{
|
||||
$this->info('확장 오토로드 파일을 생성합니다...');
|
||||
|
||||
try {
|
||||
$extensionManager->generateAutoloadFile();
|
||||
|
||||
$this->info('오토로드 파일이 성공적으로 생성되었습니다.');
|
||||
$this->line(' → bootstrap/cache/autoload-extensions.php');
|
||||
|
||||
return Command::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('오토로드 파일 생성 중 오류가 발생했습니다: '.$e->getMessage());
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Extension\Traits\ValidatesLayoutFiles;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* 레이아웃 테스트 fixtures 생성 커맨드
|
||||
*
|
||||
* 레이아웃 JSON 파일을 로드하고 partial을 병합하여
|
||||
* 테스트용 fixture 파일로 저장합니다.
|
||||
*/
|
||||
class GenerateLayoutTestFixture extends Command
|
||||
{
|
||||
use ValidatesLayoutFiles;
|
||||
|
||||
/**
|
||||
* 커맨드 시그니처
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'layout:generate-fixture
|
||||
{layout : 레이아웃 파일 경로 (modules/sirsoft-ecommerce/resources/layouts/admin/admin_ecommerce_promotion_coupon_list.json)}
|
||||
{--output= : 출력 파일명 (기본: 레이아웃 이름)}
|
||||
{--dir= : 출력 디렉토리 (기본: resources/js/core/template-engine/__tests__/fixtures)}';
|
||||
|
||||
/**
|
||||
* 커맨드 설명
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '레이아웃 JSON을 partial 병합하여 테스트 fixture로 저장합니다';
|
||||
|
||||
/**
|
||||
* 커맨드 실행
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$layoutPath = $this->argument('layout');
|
||||
|
||||
// 절대 경로로 변환
|
||||
if (! str_starts_with($layoutPath, '/') && ! preg_match('/^[A-Z]:/', $layoutPath)) {
|
||||
$layoutPath = base_path($layoutPath);
|
||||
}
|
||||
|
||||
// 파일 존재 확인
|
||||
if (! File::exists($layoutPath)) {
|
||||
$this->error("레이아웃 파일을 찾을 수 없습니다: {$layoutPath}");
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info("레이아웃 로드 중: {$layoutPath}");
|
||||
|
||||
// JSON 로드
|
||||
$jsonContent = File::get($layoutPath);
|
||||
$layoutData = json_decode($jsonContent, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$this->error('JSON 파싱 실패: ' . json_last_error_msg());
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// Partial 병합
|
||||
$basePath = dirname($layoutPath);
|
||||
$dataSources = $layoutData['data_sources'] ?? [];
|
||||
|
||||
try {
|
||||
$mergedLayout = $this->resolveAllPartials($layoutData, $basePath, 0, $dataSources);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('Partial 병합 실패: ' . $e->getMessage());
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// 출력 디렉토리 결정
|
||||
$outputDir = $this->option('dir')
|
||||
?: base_path('resources/js/core/template-engine/__tests__/fixtures');
|
||||
|
||||
// 디렉토리 생성
|
||||
if (! File::exists($outputDir)) {
|
||||
File::makeDirectory($outputDir, 0755, true);
|
||||
$this->info("디렉토리 생성: {$outputDir}");
|
||||
}
|
||||
|
||||
// 출력 파일명 결정
|
||||
$outputName = $this->option('output')
|
||||
?: ($mergedLayout['layout_name'] ?? pathinfo($layoutPath, PATHINFO_FILENAME));
|
||||
|
||||
$outputPath = $outputDir . '/' . $outputName . '.json';
|
||||
|
||||
// JSON 저장
|
||||
$jsonOutput = json_encode($mergedLayout, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
||||
File::put($outputPath, $jsonOutput);
|
||||
|
||||
$this->info("Fixture 생성 완료: {$outputPath}");
|
||||
$this->info("파일 크기: " . number_format(strlen($jsonOutput)) . " bytes");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Contracts\Repositories\ConfigRepositoryInterface;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* 환경설정 설치/초기화 커맨드
|
||||
*
|
||||
* 그누보드7 설치 시 또는 설정 초기화가 필요할 때 사용합니다.
|
||||
* config/settings/defaults.json의 기본값을 storage/app/settings/에 복사합니다.
|
||||
*/
|
||||
class InstallSettingsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'settings:install
|
||||
{--force : 기존 설정 파일을 덮어씁니다}
|
||||
{--merge : 기존 설정과 병합합니다 (새 키만 추가)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = '환경설정 기본값을 설치합니다 (config/settings/defaults.json → storage/app/settings/)';
|
||||
|
||||
public function __construct(
|
||||
private ConfigRepositoryInterface $configRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$force = $this->option('force');
|
||||
$merge = $this->option('merge');
|
||||
|
||||
$defaultsPath = config_path('settings/defaults.json');
|
||||
|
||||
// defaults.json 파일 존재 확인
|
||||
if (! File::exists($defaultsPath)) {
|
||||
$this->error("기본 설정 파일을 찾을 수 없습니다: {$defaultsPath}");
|
||||
$this->error('config/settings/defaults.json 파일이 존재하는지 확인하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// defaults.json 로드
|
||||
$content = File::get($defaultsPath);
|
||||
$data = json_decode($content, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$this->error('기본 설정 파일 JSON 파싱 실패: '.json_last_error_msg());
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$defaults = $data['defaults'] ?? [];
|
||||
$categories = $data['_meta']['categories'] ?? [];
|
||||
|
||||
if (empty($defaults)) {
|
||||
$this->error('기본 설정 파일에 defaults 섹션이 없습니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$this->info('환경설정 설치를 시작합니다...');
|
||||
$this->newLine();
|
||||
|
||||
$installedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$mergedCount = 0;
|
||||
|
||||
foreach ($categories as $category) {
|
||||
$categoryDefaults = $defaults[$category] ?? [];
|
||||
|
||||
if (empty($categoryDefaults)) {
|
||||
$this->warn(" [{$category}] 기본값이 없습니다. 건너뜁니다.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$settingsPath = storage_path("app/settings/{$category}.json");
|
||||
$exists = File::exists($settingsPath);
|
||||
|
||||
if ($exists && ! $force && ! $merge) {
|
||||
$this->line(" <comment>[{$category}]</comment> 이미 존재합니다. 건너뜁니다. (--force 또는 --merge 옵션 사용)");
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($exists && $merge) {
|
||||
// 병합 모드: 기존 설정과 병합 (기존 값 유지, 새 키만 추가)
|
||||
$existingSettings = $this->configRepository->getCategory($category);
|
||||
$mergedSettings = array_merge($categoryDefaults, $existingSettings);
|
||||
|
||||
if ($this->configRepository->saveCategory($category, $mergedSettings)) {
|
||||
$newKeysCount = count(array_diff_key($categoryDefaults, $existingSettings));
|
||||
$this->info(" <info>[{$category}]</info> 병합 완료 ({$newKeysCount}개 새 키 추가)");
|
||||
$mergedCount++;
|
||||
} else {
|
||||
$this->error(" [{$category}] 병합 실패");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 새로 설치 또는 덮어쓰기
|
||||
if ($this->configRepository->saveCategory($category, $categoryDefaults)) {
|
||||
$action = $exists ? '덮어씀' : '설치됨';
|
||||
$this->info(" <info>[{$category}]</info> {$action}");
|
||||
$installedCount++;
|
||||
} else {
|
||||
$this->error(" [{$category}] 설치 실패");
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info('환경설정 설치 완료!');
|
||||
$this->line(" - 설치됨: {$installedCount}개");
|
||||
$this->line(" - 병합됨: {$mergedCount}개");
|
||||
$this->line(" - 건너뜀: {$skippedCount}개");
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\SystemConfig;
|
||||
use App\Repositories\JsonConfigRepository;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 기존 DB 설정을 JSON 파일로 마이그레이션하는 커맨드
|
||||
*/
|
||||
class MigrateSettingsToJsonCommand extends Command
|
||||
{
|
||||
/**
|
||||
* 커맨드 시그니처
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'settings:migrate-to-json
|
||||
{--force : 기존 JSON 파일이 있어도 덮어쓰기}';
|
||||
|
||||
/**
|
||||
* 커맨드 설명
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'DB의 system_configs 테이블 데이터를 JSON 파일로 마이그레이션합니다.';
|
||||
|
||||
/**
|
||||
* 설정 키와 카테고리 매핑
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private array $categoryMap = [
|
||||
// general
|
||||
'site_name' => 'general',
|
||||
'site_url' => 'general',
|
||||
'site_description' => 'general',
|
||||
'admin_email' => 'general',
|
||||
'timezone' => 'general',
|
||||
'language' => 'general',
|
||||
'currency' => 'general',
|
||||
'maintenance_mode' => 'general',
|
||||
'description' => 'general',
|
||||
'keywords' => 'general',
|
||||
|
||||
// security
|
||||
'force_https' => 'security',
|
||||
'login_attempt_enabled' => 'security',
|
||||
'auth_token_lifetime' => 'security',
|
||||
'max_login_attempts' => 'security',
|
||||
'login_lockout_time' => 'security',
|
||||
'two_factor_auth' => 'security',
|
||||
'password_min_length' => 'security',
|
||||
'require_password_special_char' => 'security',
|
||||
|
||||
// mail
|
||||
'mailer' => 'mail',
|
||||
'mail_host' => 'mail',
|
||||
'mail_port' => 'mail',
|
||||
'mail_username' => 'mail',
|
||||
'mail_password' => 'mail',
|
||||
'mail_encryption' => 'mail',
|
||||
'mail_from_address' => 'mail',
|
||||
'mail_from_name' => 'mail',
|
||||
|
||||
// upload
|
||||
'max_file_size' => 'upload',
|
||||
'allowed_extensions' => 'upload',
|
||||
'image_max_width' => 'upload',
|
||||
'image_max_height' => 'upload',
|
||||
'image_quality' => 'upload',
|
||||
|
||||
// seo
|
||||
'meta_title_suffix' => 'seo',
|
||||
'meta_description' => 'seo',
|
||||
'meta_keywords' => 'seo',
|
||||
'google_analytics_id' => 'seo',
|
||||
'google_site_verification' => 'seo',
|
||||
'naver_site_verification' => 'seo',
|
||||
|
||||
// cache
|
||||
'cache_enabled' => 'cache',
|
||||
'layout_cache_enabled' => 'cache',
|
||||
'layout_cache_ttl' => 'cache',
|
||||
'stats_cache_enabled' => 'cache',
|
||||
'stats_cache_ttl' => 'cache',
|
||||
'seo_cache_enabled' => 'cache',
|
||||
'seo_cache_ttl' => 'cache',
|
||||
|
||||
// debug
|
||||
'debug_mode' => 'debug',
|
||||
'sql_query_log' => 'debug',
|
||||
'log_level' => 'debug',
|
||||
];
|
||||
|
||||
/**
|
||||
* 키 이름 변환 매핑 (DB 키 -> JSON 키)
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private array $keyMapping = [
|
||||
'mail_host' => 'host',
|
||||
'mail_port' => 'port',
|
||||
'mail_username' => 'username',
|
||||
'mail_password' => 'password',
|
||||
'mail_encryption' => 'encryption',
|
||||
'mail_from_address' => 'from_address',
|
||||
'mail_from_name' => 'from_name',
|
||||
'cache_enabled' => 'enabled',
|
||||
'layout_cache_enabled' => 'layout_enabled',
|
||||
'layout_cache_ttl' => 'layout_ttl',
|
||||
'stats_cache_enabled' => 'stats_enabled',
|
||||
'stats_cache_ttl' => 'stats_ttl',
|
||||
'seo_cache_enabled' => 'seo_enabled',
|
||||
'seo_cache_ttl' => 'seo_ttl',
|
||||
'debug_mode' => 'mode',
|
||||
];
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* DI 컨테이너 바인딩 시점 문제로 직접 인스턴스화합니다.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$this->info('설정 마이그레이션을 시작합니다...');
|
||||
|
||||
// system_configs 테이블 존재 확인
|
||||
if (! Schema::hasTable('system_configs')) {
|
||||
$this->warn('system_configs 테이블이 존재하지 않습니다. 기본값으로 초기화합니다.');
|
||||
|
||||
$configRepository = new JsonConfigRepository();
|
||||
$configRepository->initialize();
|
||||
|
||||
$this->info('기본 설정 파일이 생성되었습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// JsonConfigRepository 직접 인스턴스화 (DI 컨테이너 바인딩 전 실행 가능)
|
||||
$configRepository = new JsonConfigRepository();
|
||||
|
||||
// 기존 JSON 파일 존재 확인
|
||||
if (file_exists(storage_path('app/settings/general.json')) && ! $this->option('force')) {
|
||||
if (! $this->confirm('기존 JSON 설정 파일이 존재합니다. 덮어쓰시겠습니까?')) {
|
||||
$this->info('마이그레이션이 취소되었습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
// 기존 설정 조회
|
||||
$configs = SystemConfig::all();
|
||||
|
||||
if ($configs->isEmpty()) {
|
||||
$this->warn('마이그레이션할 설정이 없습니다. 기본값으로 초기화합니다.');
|
||||
$configRepository->initialize();
|
||||
$this->info('기본 설정 파일이 생성되었습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info("총 {$configs->count()}개의 설정을 발견했습니다.");
|
||||
|
||||
// 카테고리별로 그룹화
|
||||
$grouped = [];
|
||||
foreach ($configs as $config) {
|
||||
$category = $this->categoryMap[$config->key] ?? 'general';
|
||||
$jsonKey = $this->keyMapping[$config->key] ?? $config->key;
|
||||
$grouped[$category][$jsonKey] = $this->parseValue($config->value, $config->type);
|
||||
}
|
||||
|
||||
// JSON 파일로 저장
|
||||
$defaults = $configRepository->getDefaults();
|
||||
|
||||
foreach ($defaults as $category => $defaultSettings) {
|
||||
$categorySettings = array_merge(
|
||||
$defaultSettings,
|
||||
$grouped[$category] ?? []
|
||||
);
|
||||
|
||||
$configRepository->saveCategory($category, $categorySettings);
|
||||
$this->info(" ✓ {$category} 카테고리 저장 완료");
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info('마이그레이션이 완료되었습니다!');
|
||||
$this->info('설정 파일 위치: storage/app/settings/');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 값을 원래 타입으로 파싱합니다.
|
||||
*
|
||||
* @param string $value
|
||||
* @param string $type
|
||||
* @return mixed
|
||||
*/
|
||||
private function parseValue(string $value, string $type): mixed
|
||||
{
|
||||
return match ($type) {
|
||||
'boolean' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
|
||||
'integer' => (int) $value,
|
||||
'float' => (float) $value,
|
||||
'json', 'array' => json_decode($value, true) ?: [],
|
||||
default => $value,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ActivateModuleCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:activate {identifier : 활성화할 모듈 식별자} {--force : 의존성 미충족 시 강제 활성화}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈을 활성화합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 모듈 디렉토리 스캔 및 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
// 모듈이 설치되어 있는지 확인
|
||||
$moduleRecord = $this->moduleRepository->findByIdentifier($identifier);
|
||||
if (! $moduleRecord) {
|
||||
$this->error('❌ '.__('modules.commands.activate.not_installed', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 이미 활성화된 모듈인지 확인
|
||||
if ($moduleRecord->status === ExtensionStatus::Active->value) {
|
||||
$this->warn('⚠️ '.__('modules.commands.activate.already_active', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 모듈 활성화
|
||||
$force = $this->option('force');
|
||||
$result = $this->moduleManager->activateModule($identifier, $force);
|
||||
|
||||
// 경고 응답인 경우 (의존성 미충족)
|
||||
if (isset($result['warning']) && $result['warning'] === true) {
|
||||
$this->warn('⚠️ '.$result['message']);
|
||||
$this->line('');
|
||||
|
||||
if (! empty($result['missing_modules'])) {
|
||||
$this->info('필요한 모듈:');
|
||||
foreach ($result['missing_modules'] as $module) {
|
||||
$statusLabel = $module['status'] === 'not_installed' ? '미설치' : '비활성';
|
||||
$this->line(" - {$module['identifier']} ({$module['name']}) [{$statusLabel}]");
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($result['missing_plugins'])) {
|
||||
$this->info('필요한 플러그인:');
|
||||
foreach ($result['missing_plugins'] as $plugin) {
|
||||
$statusLabel = $plugin['status'] === 'not_installed' ? '미설치' : '비활성';
|
||||
$this->line(" - {$plugin['identifier']} ({$plugin['name']}) [{$statusLabel}]");
|
||||
}
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
$this->info('강제로 활성화하려면 --force 옵션을 사용하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if ($result['success']) {
|
||||
$this->info('✅ '.__('modules.commands.activate.success', ['module' => $identifier]));
|
||||
$this->info(' - '.__('modules.commands.activate.layouts_registered', ['count' => $result['layouts_registered']]));
|
||||
Log::info(__('modules.commands.activate.success', ['module' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 활성화 실패', [
|
||||
'module' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
class BuildModuleCommand extends Command
|
||||
{
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:build
|
||||
{identifier? : 빌드할 모듈 식별자 (생략 시 --all 필요)}
|
||||
{--all : 모든 모듈 빌드}
|
||||
{--watch : 파일 변경 감시 모드}
|
||||
{--production : 프로덕션 빌드}
|
||||
{--active : 활성 디렉토리에서 빌드}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈의 프론트엔드 에셋을 빌드합니다 (기본: _bundled 디렉토리)';
|
||||
|
||||
/**
|
||||
* 모듈 관리자
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$buildAll = $this->option('all');
|
||||
$watchMode = $this->option('watch');
|
||||
$productionMode = $this->option('production');
|
||||
|
||||
if (! $identifier && ! $buildAll) {
|
||||
$this->error('❌ 모듈 식별자를 지정하거나 --all 옵션을 사용하세요.');
|
||||
$this->line('');
|
||||
$this->line('사용법:');
|
||||
$this->line(' php artisan module:build sirsoft-ecommerce');
|
||||
$this->line(' php artisan module:build --all');
|
||||
$this->line(' php artisan module:build sirsoft-ecommerce --watch');
|
||||
$this->line(' php artisan module:build --all --production');
|
||||
$this->line(' php artisan module:build sirsoft-ecommerce --active');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 모듈 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
if ($buildAll) {
|
||||
return $this->buildAllModules($productionMode);
|
||||
}
|
||||
|
||||
return $this->buildModule($identifier, $watchMode, $productionMode);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 빌드 실패', [
|
||||
'module' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드 대상 경로를 결정합니다.
|
||||
*
|
||||
* 기본값: _bundled 디렉토리. --active 옵션 시 활성 디렉토리.
|
||||
* --watch 모드에서는 활성 디렉토리를 사용합니다 (실시간 개발용).
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return array|null ['path' => string, 'source' => 'bundled'|'active'] 또는 null
|
||||
*/
|
||||
private function resolveBuildPath(string $identifier): ?array
|
||||
{
|
||||
$bundledPath = base_path("modules/_bundled/{$identifier}");
|
||||
$activePath = base_path("modules/{$identifier}");
|
||||
|
||||
// --active 명시 → 활성 디렉토리
|
||||
if ($this->option('active')) {
|
||||
return is_dir($activePath)
|
||||
? ['path' => $activePath, 'source' => 'active']
|
||||
: null;
|
||||
}
|
||||
|
||||
// --watch 모드 → 활성 디렉토리 (실시간 개발용)
|
||||
if ($this->option('watch')) {
|
||||
if (is_dir($activePath)) {
|
||||
return ['path' => $activePath, 'source' => 'active'];
|
||||
}
|
||||
}
|
||||
|
||||
// 기본값: _bundled 우선
|
||||
if (is_dir($bundledPath)) {
|
||||
return ['path' => $bundledPath, 'source' => 'bundled'];
|
||||
}
|
||||
|
||||
// _bundled에 없으면 활성 디렉토리 폴백
|
||||
if (is_dir($activePath)) {
|
||||
return ['path' => $activePath, 'source' => 'active'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 모듈 빌드
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param bool $watchMode 파일 감시 모드
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildModule(string $identifier, bool $watchMode, bool $productionMode): int
|
||||
{
|
||||
// 경로 결정
|
||||
$resolved = $this->resolveBuildPath($identifier);
|
||||
if (! $resolved) {
|
||||
$this->error("❌ 모듈을 찾을 수 없습니다: {$identifier}");
|
||||
$this->line(' _bundled 및 활성 디렉토리 모두 존재하지 않습니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$buildPath = $resolved['path'];
|
||||
$source = $resolved['source'];
|
||||
|
||||
// 소스 표시
|
||||
$sourceLabel = $source === 'bundled' ? '_bundled' : '활성';
|
||||
$this->info("📂 빌드 소스: {$sourceLabel} ({$buildPath})");
|
||||
|
||||
// package.json 존재 확인
|
||||
$packageJsonPath = $buildPath.'/package.json';
|
||||
if (! file_exists($packageJsonPath)) {
|
||||
$this->error('❌ package.json 파일이 없습니다: '.$packageJsonPath);
|
||||
$this->line(' 모듈 프론트엔드 구조를 먼저 생성하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 에셋 빌드 가능 여부 확인 (활성 모듈 인스턴스가 있는 경우)
|
||||
$module = $this->moduleManager->getModule($identifier);
|
||||
if ($module && ! $module->canBuild() && ! $module->hasAssets()) {
|
||||
$this->warn('⚠️ 모듈에 빌드할 에셋이 없습니다: '.$identifier);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// node_modules 확인 및 설치
|
||||
if (! is_dir($buildPath.'/node_modules')) {
|
||||
$this->info('📦 의존성 설치 중...');
|
||||
$installResult = $this->runNpmCommand(['npm', 'install'], $buildPath);
|
||||
|
||||
if ($installResult !== Command::SUCCESS) {
|
||||
$this->error('❌ npm install 실패');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
// 빌드 명령 결정
|
||||
$buildCommand = ['npm', 'run'];
|
||||
|
||||
if ($watchMode) {
|
||||
$buildCommand[] = 'dev';
|
||||
$this->info("👀 파일 감시 모드로 빌드 시작: {$identifier}");
|
||||
$this->line(' Ctrl+C로 종료할 수 있습니다.');
|
||||
} else {
|
||||
$buildCommand[] = 'build';
|
||||
$this->info("🔨 빌드 시작: {$identifier}".($productionMode ? ' (프로덕션)' : ''));
|
||||
}
|
||||
|
||||
// 빌드 실행
|
||||
$result = $this->runNpmCommand($buildCommand, $buildPath, ! $watchMode);
|
||||
|
||||
if ($result === Command::SUCCESS && ! $watchMode) {
|
||||
$this->info("✅ 빌드 완료: {$identifier}");
|
||||
|
||||
// 빌드 결과 파일 확인
|
||||
$this->displayBuildResults($buildPath, $identifier);
|
||||
|
||||
// 캐시 버전 증가 (브라우저 캐시 무효화)
|
||||
$this->incrementExtensionCacheVersion();
|
||||
$this->line(' - 캐시 버전 갱신됨');
|
||||
|
||||
// _bundled 빌드 시 활성 반영 안내
|
||||
if ($source === 'bundled') {
|
||||
$this->line('');
|
||||
$this->info("💡 활성 디렉토리에 반영하려면: php artisan module:update {$identifier}");
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드 결과 파일 정보를 출력합니다.
|
||||
*
|
||||
* @param string $buildPath 빌드된 경로
|
||||
* @param string $identifier 모듈 식별자
|
||||
*/
|
||||
private function displayBuildResults(string $buildPath, string $identifier): void
|
||||
{
|
||||
// 활성 모듈 인스턴스가 있으면 getBuiltAssetPaths 활용
|
||||
$module = $this->moduleManager->getModule($identifier);
|
||||
if ($module) {
|
||||
$builtPaths = $module->getBuiltAssetPaths();
|
||||
|
||||
if (! empty($builtPaths['js'])) {
|
||||
$jsPath = $buildPath.'/'.$builtPaths['js'];
|
||||
if (file_exists($jsPath)) {
|
||||
$this->line(' - JS: '.$builtPaths['js'].' ('.number_format(filesize($jsPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($builtPaths['css'])) {
|
||||
$cssPath = $buildPath.'/'.$builtPaths['css'];
|
||||
if (file_exists($cssPath)) {
|
||||
$this->line(' - CSS: '.$builtPaths['css'].' ('.number_format(filesize($cssPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 활성 인스턴스 없으면 manifest에서 직접 확인
|
||||
$manifestPath = $buildPath.'/module.json';
|
||||
if (file_exists($manifestPath)) {
|
||||
$manifest = json_decode(file_get_contents($manifestPath), true);
|
||||
$assets = $manifest['assets'] ?? [];
|
||||
|
||||
if (! empty($assets['js']['output'])) {
|
||||
$jsPath = $buildPath.'/'.$assets['js']['output'];
|
||||
if (file_exists($jsPath)) {
|
||||
$this->line(' - JS: '.$assets['js']['output'].' ('.number_format(filesize($jsPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($assets['css']['output'])) {
|
||||
$cssPath = $buildPath.'/'.$assets['css']['output'];
|
||||
if (file_exists($cssPath)) {
|
||||
$this->line(' - CSS: '.$assets['css']['output'].' ('.number_format(filesize($cssPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 모듈 빌드
|
||||
*
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildAllModules(bool $productionMode): int
|
||||
{
|
||||
$buildTargets = [];
|
||||
|
||||
if ($this->option('active')) {
|
||||
// --active: 활성 디렉토리만 대상
|
||||
$activeModules = $this->moduleManager->getAllModules();
|
||||
foreach ($activeModules as $identifier => $module) {
|
||||
$activePath = base_path("modules/{$identifier}");
|
||||
if (file_exists($activePath.'/package.json')
|
||||
&& ($module->canBuild() || $module->hasAssets())) {
|
||||
$buildTargets[$identifier] = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 기본값: _bundled 디렉토리 스캔
|
||||
$bundledModules = $this->moduleManager->getBundledModules();
|
||||
foreach ($bundledModules as $identifier => $metadata) {
|
||||
$bundledPath = $metadata['source_path'];
|
||||
if (file_exists($bundledPath.'/package.json')) {
|
||||
$assets = $metadata['assets'] ?? [];
|
||||
if (! empty($assets['js']['entry']) || ! empty($assets['css']['entry']) || ! empty($assets)) {
|
||||
$buildTargets[$identifier] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($buildTargets)) {
|
||||
$this->warn('⚠️ 빌드할 모듈이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$sourceLabel = $this->option('active') ? '활성' : '_bundled';
|
||||
$this->info("🔨 모든 모듈 빌드 시작 ({$sourceLabel})".($productionMode ? ' (프로덕션)' : ''));
|
||||
$this->line(' 대상 모듈: '.implode(', ', array_keys($buildTargets)));
|
||||
$this->line('');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($buildTargets as $identifier => $value) {
|
||||
$this->line(" [{$identifier}]");
|
||||
$result = $this->buildModule($identifier, false, $productionMode);
|
||||
|
||||
if ($result === Command::SUCCESS) {
|
||||
$successCount++;
|
||||
} else {
|
||||
$failCount++;
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
$this->info("📊 빌드 결과: 성공 {$successCount}개, 실패 {$failCount}개");
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* npm 명령 실행
|
||||
*
|
||||
* @param array $command 실행할 명령
|
||||
* @param string $cwd 작업 디렉토리
|
||||
* @param bool $waitForCompletion 완료 대기 여부
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function runNpmCommand(array $command, string $cwd, bool $waitForCompletion = true): int
|
||||
{
|
||||
// Windows 환경에서는 cmd /c 사용
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
$command = array_merge(['cmd', '/c'], $command);
|
||||
}
|
||||
|
||||
$process = new Process($command);
|
||||
$process->setWorkingDirectory($cwd);
|
||||
$process->setTimeout(null); // 타임아웃 없음
|
||||
|
||||
if ($waitForCompletion) {
|
||||
$process->run(function ($type, $buffer) {
|
||||
$this->output->write($buffer);
|
||||
});
|
||||
|
||||
return $process->isSuccessful() ? Command::SUCCESS : Command::FAILURE;
|
||||
}
|
||||
|
||||
// 감시 모드: 인터럽트까지 실행
|
||||
$process->start(function ($type, $buffer) {
|
||||
$this->output->write($buffer);
|
||||
});
|
||||
|
||||
// 프로세스가 실행 중인 동안 대기
|
||||
while ($process->isRunning()) {
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CheckModuleUpdatesCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:check-updates {identifier? : 특정 모듈만 확인 (선택)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈 업데이트를 확인합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
if ($identifier) {
|
||||
return $this->checkSingle($identifier);
|
||||
}
|
||||
|
||||
return $this->checkAll();
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 업데이트 확인 실패', [
|
||||
'module' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 모듈 업데이트를 확인합니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
*/
|
||||
private function checkSingle(string $identifier): int
|
||||
{
|
||||
$module = $this->moduleRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $module) {
|
||||
$this->error('❌ '.__('modules.commands.check_updates.not_installed', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$result = $this->moduleManager->checkModuleUpdate($identifier);
|
||||
|
||||
// 단일 체크는 DB 갱신이 안 되므로 커맨드에서 직접 갱신
|
||||
$this->moduleRepository->updateByIdentifier($identifier, [
|
||||
'update_available' => $result['update_available'],
|
||||
'latest_version' => $result['latest_version'],
|
||||
'update_source' => $result['update_source'],
|
||||
]);
|
||||
|
||||
if ($result['update_available']) {
|
||||
$this->info('🔄 '.__('modules.commands.check_updates.single_update_available', [
|
||||
'module' => $identifier,
|
||||
'current' => $result['current_version'],
|
||||
'latest' => $result['latest_version'],
|
||||
'source' => $result['update_source'],
|
||||
]));
|
||||
} else {
|
||||
$this->info('✅ '.__('modules.commands.check_updates.single_up_to_date', [
|
||||
'module' => $identifier,
|
||||
'version' => $result['current_version'],
|
||||
]));
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 설치된 모듈의 업데이트를 확인합니다.
|
||||
*/
|
||||
private function checkAll(): int
|
||||
{
|
||||
$installedModules = $this->moduleManager->getInstalledModulesWithDetails();
|
||||
|
||||
if (empty($installedModules)) {
|
||||
$this->info(__('modules.commands.check_updates.no_installed'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// checkAllModulesForUpdates는 내부에서 DB 갱신 포함
|
||||
$result = $this->moduleManager->checkAllModulesForUpdates();
|
||||
|
||||
$tableData = [];
|
||||
$updateCount = 0;
|
||||
|
||||
foreach ($result['details'] as $detail) {
|
||||
$isUpdate = $detail['update_available'] ?? false;
|
||||
if ($isUpdate) {
|
||||
$updateCount++;
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
$detail['identifier'],
|
||||
$detail['current_version'] ?? '-',
|
||||
$detail['latest_version'] ?? '-',
|
||||
$detail['update_source'] ?? '-',
|
||||
$isUpdate
|
||||
? '🔄 '.__('modules.commands.check_updates.update_available')
|
||||
: '✅ '.__('modules.commands.check_updates.up_to_date'),
|
||||
];
|
||||
}
|
||||
|
||||
$headers = [
|
||||
__('modules.commands.check_updates.headers.identifier'),
|
||||
__('modules.commands.check_updates.headers.current_version'),
|
||||
__('modules.commands.check_updates.headers.latest_version'),
|
||||
__('modules.commands.check_updates.headers.source'),
|
||||
__('modules.commands.check_updates.headers.status'),
|
||||
];
|
||||
|
||||
$this->table($headers, $tableData);
|
||||
$this->newLine();
|
||||
$this->info(__('modules.commands.check_updates.summary', [
|
||||
'total' => count($result['details']),
|
||||
'updates' => $updateCount,
|
||||
]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ClearModuleCacheCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:cache-clear
|
||||
{identifier? : 특정 모듈의 캐시만 삭제 (생략 시 모든 모듈)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈 캐시를 삭제합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 모듈 디렉토리 스캔 및 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
$clearedCount = 0;
|
||||
|
||||
if ($identifier) {
|
||||
// 특정 모듈 캐시 삭제
|
||||
$this->info(__('modules.commands.cache_clear.clearing_single', ['module' => $identifier]));
|
||||
|
||||
// 모듈이 존재하는지 확인
|
||||
$module = $this->moduleManager->getModule($identifier);
|
||||
if (! $module) {
|
||||
$this->error('❌ '.__('modules.not_found', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$clearedCount = $this->clearModuleCache($identifier);
|
||||
|
||||
$this->info('✅ '.__('modules.commands.cache_clear.success_single', [
|
||||
'module' => $identifier,
|
||||
'count' => $clearedCount,
|
||||
]));
|
||||
} else {
|
||||
// 모든 모듈 캐시 삭제
|
||||
$this->info(__('modules.commands.cache_clear.clearing_all'));
|
||||
|
||||
// 전체 모듈 캐시 키 삭제
|
||||
$cacheKeys = [
|
||||
'modules.all',
|
||||
'modules.active',
|
||||
'modules.installed',
|
||||
];
|
||||
|
||||
foreach ($cacheKeys as $key) {
|
||||
if (Cache::forget($key)) {
|
||||
$clearedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// 각 모듈별 캐시 삭제
|
||||
$allModules = $this->moduleManager->getAllModules();
|
||||
foreach ($allModules as $moduleName => $module) {
|
||||
$clearedCount += $this->clearModuleCache($module->getIdentifier());
|
||||
}
|
||||
|
||||
$this->info('✅ '.__('modules.commands.cache_clear.success_all', ['count' => $clearedCount]));
|
||||
}
|
||||
|
||||
Log::info('모듈 캐시 삭제 완료', [
|
||||
'module' => $identifier ?? 'all',
|
||||
'count' => $clearedCount,
|
||||
]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 캐시 삭제 실패', [
|
||||
'module' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 모듈의 캐시를 삭제합니다.
|
||||
*/
|
||||
private function clearModuleCache(string $identifier): int
|
||||
{
|
||||
$clearedCount = 0;
|
||||
|
||||
// 모듈별 캐시 키
|
||||
$cacheKeys = [
|
||||
"module.config.{$identifier}",
|
||||
"module.info.{$identifier}",
|
||||
"module.routes.{$identifier}",
|
||||
"module.permissions.{$identifier}",
|
||||
"module.menus.{$identifier}",
|
||||
];
|
||||
|
||||
foreach ($cacheKeys as $key) {
|
||||
if (Cache::forget($key)) {
|
||||
$clearedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return $clearedCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Extension\ExtensionManager;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ComposerInstallModuleCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:composer-install
|
||||
{identifier? : Composer 의존성을 설치할 모듈 식별자 (생략 시 --all 필요)}
|
||||
{--all : 모든 모듈의 Composer 의존성 설치}
|
||||
{--no-dev : dev 의존성 제외}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈의 Composer 의존성을 설치합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ExtensionManager $extensionManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$installAll = $this->option('all');
|
||||
$noDev = $this->option('no-dev');
|
||||
|
||||
if (! $identifier && ! $installAll) {
|
||||
$this->error('❌ 모듈 식별자를 지정하거나 --all 옵션을 사용하세요.');
|
||||
$this->line('');
|
||||
$this->line('사용법:');
|
||||
$this->line(' php artisan module:composer-install sirsoft-ecommerce');
|
||||
$this->line(' php artisan module:composer-install --all');
|
||||
$this->line(' php artisan module:composer-install --all --no-dev');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
if ($installAll) {
|
||||
return $this->installAllModules($noDev);
|
||||
}
|
||||
|
||||
return $this->installModule($identifier, $noDev);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 Composer 의존성 설치 실패', [
|
||||
'module' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 모듈의 Composer 의존성 설치
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param bool $noDev dev 의존성 제외 여부
|
||||
* @return int 커맨드 결과 코드
|
||||
*/
|
||||
private function installModule(string $identifier, bool $noDev): int
|
||||
{
|
||||
$module = $this->moduleManager->getModule($identifier);
|
||||
|
||||
if (! $module) {
|
||||
$this->error('❌ '.__('modules.errors.not_found', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if (! $this->extensionManager->hasComposerDependencies('modules', $identifier)) {
|
||||
$this->info('ℹ️ '.__('modules.composer_install.no_dependencies', ['module' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$deps = $this->extensionManager->getComposerDependencies('modules', $identifier);
|
||||
$this->info('📦 '.__('modules.composer_install.start', ['module' => $identifier]));
|
||||
$this->line(' '.implode(', ', array_keys($deps)));
|
||||
|
||||
$result = $this->extensionManager->runComposerInstall('modules', $identifier, $noDev, $this);
|
||||
|
||||
if ($result) {
|
||||
$this->info('✅ '.__('modules.composer_install.success', ['module' => $identifier]));
|
||||
|
||||
// 오토로드 갱신
|
||||
$this->extensionManager->updateComposerAutoload();
|
||||
$this->line(' 오토로드 캐시 갱신 완료');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->error('❌ '.__('modules.composer_install.failed', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 모듈의 Composer 의존성 설치
|
||||
*
|
||||
* @param bool $noDev dev 의존성 제외 여부
|
||||
* @return int 커맨드 결과 코드
|
||||
*/
|
||||
private function installAllModules(bool $noDev): int
|
||||
{
|
||||
$modules = $this->moduleManager->getAllModules();
|
||||
|
||||
if (empty($modules)) {
|
||||
$this->warn('⚠️ 설치된 모듈이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 중복 패키지 감지
|
||||
$duplicates = $this->extensionManager->detectDuplicatePackages();
|
||||
if (! empty($duplicates)) {
|
||||
$this->warn('⚠️ 중복 패키지 감지:');
|
||||
foreach ($duplicates as $package => $users) {
|
||||
$this->warn(" - {$package}: ".implode(', ', $users));
|
||||
}
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
$this->info('📦 모든 모듈의 Composer 의존성 설치 시작');
|
||||
|
||||
$successCount = 0;
|
||||
$skipCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($modules as $identifier => $module) {
|
||||
if (! $this->extensionManager->hasComposerDependencies('modules', $identifier)) {
|
||||
$skipCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->line(" [{$identifier}]");
|
||||
$result = $this->extensionManager->runComposerInstall('modules', $identifier, $noDev, $this);
|
||||
|
||||
if ($result) {
|
||||
$successCount++;
|
||||
$this->info(" ✅ 완료: {$identifier}");
|
||||
} else {
|
||||
$failCount++;
|
||||
$this->error(" ❌ 실패: {$identifier}");
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
// 오토로드 갱신
|
||||
$this->extensionManager->updateComposerAutoload();
|
||||
|
||||
$this->info(__('modules.composer_install.summary', [
|
||||
'success' => $successCount,
|
||||
'skip' => $skipCount,
|
||||
'fail' => $failCount,
|
||||
]));
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class DeactivateModuleCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:deactivate {identifier : 비활성화할 모듈 식별자} {--force : 의존 템플릿이 있어도 강제 비활성화}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈을 비활성화합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 모듈 디렉토리 스캔 및 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
// 모듈이 설치되어 있는지 확인
|
||||
$moduleRecord = $this->moduleRepository->findByIdentifier($identifier);
|
||||
if (! $moduleRecord) {
|
||||
$this->error('❌ '.__('modules.commands.deactivate.not_installed', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 모듈이 활성화되어 있는지 확인
|
||||
if ($moduleRecord->status !== ExtensionStatus::Active->value) {
|
||||
$this->warn('⚠️ '.__('modules.commands.deactivate.not_active', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 모듈 비활성화
|
||||
$force = $this->option('force');
|
||||
$result = $this->moduleManager->deactivateModule($identifier, $force);
|
||||
|
||||
// 경고 응답인 경우 (의존 템플릿 존재)
|
||||
if (isset($result['warning']) && $result['warning'] === true) {
|
||||
$this->warn('⚠️ '.$result['message']);
|
||||
$this->line('');
|
||||
$this->info('의존하는 템플릿 목록:');
|
||||
foreach ($result['dependent_templates'] as $template) {
|
||||
$this->line(" - {$template['identifier']} ({$template['name']})");
|
||||
}
|
||||
$this->line('');
|
||||
$this->info('강제로 비활성화하려면 --force 옵션을 사용하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if ($result['success']) {
|
||||
$this->info('✅ '.__('modules.commands.deactivate.success', ['module' => $identifier]));
|
||||
$this->info(' - '.__('modules.commands.deactivate.layouts_deleted', ['count' => $result['layouts_deleted']]));
|
||||
$this->warn('⚠️ '.__('modules.commands.deactivate.warning'));
|
||||
Log::info(__('modules.commands.deactivate.success', ['module' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 비활성화 실패', [
|
||||
'module' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Models\Menu;
|
||||
use App\Models\Permission;
|
||||
use App\Rules\ValidExtensionIdentifier;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class InstallModuleCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:install {identifier : 설치할 모듈 식별자}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈을 설치합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
// 식별자 형식 검증
|
||||
$validator = Validator::make(
|
||||
['identifier' => $identifier],
|
||||
['identifier' => [new ValidExtensionIdentifier]]
|
||||
);
|
||||
|
||||
if ($validator->fails()) {
|
||||
$this->error('❌ '.$validator->errors()->first('identifier'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 모듈 디렉토리 스캔 및 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
// 이미 설치된 모듈인지 확인
|
||||
$existingModule = $this->moduleRepository->findByIdentifier($identifier);
|
||||
if ($existingModule) {
|
||||
$this->warn('⚠️ '.__('modules.commands.install.already_installed', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 모듈 설치
|
||||
$onProgress = $this->createProgressCallback(ModuleManager::INSTALL_STEPS);
|
||||
try {
|
||||
$result = $this->moduleManager->installModule($identifier, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
// 설치된 모듈 정보 조회
|
||||
$module = $this->moduleRepository->findByIdentifier($identifier);
|
||||
|
||||
// 모듈 인스턴스에서 생성된 role 개수 조회
|
||||
$moduleInstance = $this->moduleManager->getModule($identifier);
|
||||
$rolesCount = 0;
|
||||
if ($moduleInstance && method_exists($moduleInstance, 'getRoles')) {
|
||||
$rolesCount = count($moduleInstance->getRoles());
|
||||
}
|
||||
|
||||
// 권한 및 메뉴 개수 조회
|
||||
$permissionsCount = Permission::byExtension(ExtensionOwnerType::Module, $identifier)->count();
|
||||
$menusCount = Menu::byExtension(ExtensionOwnerType::Module, $identifier)->count();
|
||||
|
||||
// 성공 메시지
|
||||
$this->info('✅ '.__('modules.commands.install.success', ['module' => $identifier]));
|
||||
$this->info(' - '.__('modules.commands.install.vendor', ['vendor' => $module->vendor]));
|
||||
$this->info(' - '.__('modules.commands.install.version', ['version' => $module->version]));
|
||||
$this->info(' - '.__('modules.commands.install.roles_created', ['count' => $rolesCount]));
|
||||
$this->info(' - '.__('modules.commands.install.permissions_created', ['count' => $permissionsCount]));
|
||||
$this->info(' - '.__('modules.commands.install.menus_created', ['count' => $menusCount]));
|
||||
|
||||
Log::info(__('modules.commands.install.success', ['module' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 설치 실패', [
|
||||
'module' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class ListModuleCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:list
|
||||
{--status= : 상태로 필터 (installed, uninstalled, active, inactive)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈 목록을 조회합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
// 모듈 디렉토리 스캔 및 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
$statusFilter = $this->option('status');
|
||||
|
||||
// 상태 필터 검증
|
||||
if ($statusFilter && ! in_array($statusFilter, ['installed', 'uninstalled', 'active', 'inactive'])) {
|
||||
$this->error('❌ '.__('modules.commands.list.invalid_status'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 설치된 모듈 정보
|
||||
$installedModules = $this->moduleManager->getInstalledModulesWithDetails();
|
||||
|
||||
// 미설치 모듈 정보
|
||||
$uninstalledModules = $this->moduleManager->getUninstalledModules();
|
||||
|
||||
// 테이블 데이터 준비
|
||||
$tableData = [];
|
||||
|
||||
// 설치된 모듈 추가
|
||||
foreach ($installedModules as $identifier => $module) {
|
||||
// 상태 필터
|
||||
if ($statusFilter) {
|
||||
if ($statusFilter === 'uninstalled') {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'active' && $module['status'] !== ExtensionStatus::Active->value) {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'inactive' && $module['status'] !== ExtensionStatus::Inactive->value) {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'installed' && ! in_array($module['status'], [ExtensionStatus::Active->value, ExtensionStatus::Inactive->value])) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
'identifier' => $identifier,
|
||||
'name' => $module['name'],
|
||||
'vendor' => $module['vendor'],
|
||||
'version' => $module['version'],
|
||||
'status' => $this->formatStatus($module['status']),
|
||||
];
|
||||
}
|
||||
|
||||
// 미설치 모듈 추가
|
||||
if (! $statusFilter || $statusFilter === 'uninstalled') {
|
||||
foreach ($uninstalledModules as $identifier => $module) {
|
||||
// 상태 필터 (uninstalled 또는 필터 없음)
|
||||
if ($statusFilter && $statusFilter !== 'uninstalled') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
'identifier' => $identifier,
|
||||
'name' => $module['name'],
|
||||
'vendor' => $module['vendor'],
|
||||
'version' => $module['version'],
|
||||
'status' => $this->formatStatus('uninstalled'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 모듈이 없는 경우
|
||||
if (empty($tableData)) {
|
||||
$this->info(__('modules.commands.list.no_modules'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 테이블 헤더
|
||||
$headers = [
|
||||
__('modules.commands.list.headers.identifier'),
|
||||
__('modules.commands.list.headers.name'),
|
||||
__('modules.commands.list.headers.vendor'),
|
||||
__('modules.commands.list.headers.version'),
|
||||
__('modules.commands.list.headers.status'),
|
||||
];
|
||||
|
||||
// 테이블 출력
|
||||
$this->table($headers, $tableData);
|
||||
|
||||
// 요약 정보
|
||||
$totalCount = count($tableData);
|
||||
$activeCount = count(array_filter($tableData, fn ($m) => str_contains($m['status'], __('modules.commands.list.status.active'))));
|
||||
$installedCount = count(array_filter($tableData, fn ($m) => ! str_contains($m['status'], __('modules.commands.list.status.uninstalled'))));
|
||||
|
||||
$this->newLine();
|
||||
$this->info(__('modules.commands.list.summary', [
|
||||
'total' => $totalCount,
|
||||
'installed' => $installedCount,
|
||||
'active' => $activeCount,
|
||||
]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상태 포맷팅
|
||||
*/
|
||||
private function formatStatus(string $status): string
|
||||
{
|
||||
return match ($status) {
|
||||
ExtensionStatus::Active->value => '✅ '.__('modules.commands.list.status.active'),
|
||||
ExtensionStatus::Inactive->value => '⏸️ '.__('modules.commands.list.status.inactive'),
|
||||
'uninstalled' => '📦 '.__('modules.commands.list.status.uninstalled'),
|
||||
default => $status,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Models\Module;
|
||||
use App\Services\ModuleService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 모듈 레이아웃 갱신 커맨드
|
||||
*
|
||||
* 레이아웃 JSON 파일만 수정된 경우, 빌드 없이 레이아웃만 갱신합니다.
|
||||
*/
|
||||
class RefreshModuleLayoutCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:refresh-layout
|
||||
{identifier? : 특정 모듈의 식별자 (생략 시 모든 활성 모듈)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈 레이아웃을 갱신합니다 (빌드 없이 JSON만 DB에 동기화)';
|
||||
|
||||
public function __construct(
|
||||
private ModuleService $moduleService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
if ($identifier) {
|
||||
return $this->refreshSingle($identifier);
|
||||
}
|
||||
|
||||
return $this->refreshAll();
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 레이아웃 갱신 실패', [
|
||||
'module' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 모듈의 레이아웃을 갱신합니다.
|
||||
*/
|
||||
private function refreshSingle(string $identifier): int
|
||||
{
|
||||
$this->info("모듈 '{$identifier}' 레이아웃 갱신 중...");
|
||||
|
||||
$result = $this->moduleService->refreshModuleLayouts($identifier);
|
||||
|
||||
if ($result) {
|
||||
$this->info("✅ 모듈 '{$identifier}' 레이아웃 갱신 완료");
|
||||
Log::info('모듈 레이아웃 갱신 완료', ['module' => $identifier]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->error("❌ 모듈 '{$identifier}' 레이아웃 갱신 실패");
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 모듈의 레이아웃을 갱신합니다.
|
||||
*/
|
||||
private function refreshAll(): int
|
||||
{
|
||||
$modules = Module::where('status', 'active')->pluck('identifier')->toArray();
|
||||
|
||||
if (empty($modules)) {
|
||||
$this->line('활성화된 모듈이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info('모든 활성 모듈 레이아웃 갱신 중...');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($modules as $moduleIdentifier) {
|
||||
$this->line(" {$moduleIdentifier} 갱신 중...");
|
||||
|
||||
try {
|
||||
$result = $this->moduleService->refreshModuleLayouts($moduleIdentifier);
|
||||
|
||||
if ($result) {
|
||||
$this->info(" ✅ {$moduleIdentifier} 완료");
|
||||
$successCount++;
|
||||
} else {
|
||||
$this->warn(" ⚠️ {$moduleIdentifier} 실패");
|
||||
$failCount++;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$this->warn(" ⚠️ {$moduleIdentifier}: ".$e->getMessage());
|
||||
$failCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info("✅ 총 {$successCount}개 성공, {$failCount}개 실패");
|
||||
|
||||
Log::info('모듈 레이아웃 일괄 갱신 완료', [
|
||||
'success' => $successCount,
|
||||
'failed' => $failCount,
|
||||
]);
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\ExtensionManager;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class SeedModuleCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:seed
|
||||
{identifier? : 시더를 실행할 모듈 식별자 (생략 시 모든 활성 모듈)}
|
||||
{--class= : 실행할 특정 시더 클래스명}
|
||||
{--count=* : 시더에 전달할 카운트 옵션 (형식: key=value, 예: --count=products=1000)}
|
||||
{--sample : 샘플 데이터 시더도 함께 실행}
|
||||
{--force : 프로덕션 환경에서도 강제 실행}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈의 데이터베이스 시더를 실행합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$seederClass = $this->option('class');
|
||||
$force = $this->option('force');
|
||||
|
||||
// 프로덕션 환경 확인
|
||||
if (app()->environment('production') && ! $force) {
|
||||
$this->error('❌ 프로덕션 환경에서는 --force 옵션이 필요합니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 모듈 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
if ($identifier) {
|
||||
return $this->seedModule($identifier, $seederClass);
|
||||
}
|
||||
|
||||
return $this->seedAllActiveModules($seederClass);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 시더 실행 실패', [
|
||||
'module' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 모듈 시더 실행
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param string|null $seederClass 특정 시더 클래스명
|
||||
* @return int 명령 실행 결과
|
||||
*/
|
||||
private function seedModule(string $identifier, ?string $seederClass): int
|
||||
{
|
||||
// 모듈 존재 여부 확인
|
||||
$module = $this->moduleManager->getModule($identifier);
|
||||
|
||||
if (! $module) {
|
||||
$this->error('❌ '.__('modules.errors.not_found', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 활성화 상태 확인
|
||||
$moduleRecord = $this->moduleRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $moduleRecord || $moduleRecord->status !== ExtensionStatus::Active->value) {
|
||||
$this->error('❌ 모듈이 활성화되어 있지 않습니다: '.$identifier);
|
||||
$this->line(' 먼저 php artisan module:activate '.$identifier.' 명령을 실행하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 시더 경로 확인
|
||||
$modulePath = base_path("modules/{$identifier}");
|
||||
$seederPath = $modulePath.'/database/seeders';
|
||||
|
||||
if (! is_dir($seederPath)) {
|
||||
$this->warn('⚠️ 모듈에 시더 디렉토리가 없습니다: '.$identifier);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 시더 클래스 결정
|
||||
$seederClassName = $this->resolveSeederClass($identifier, $seederClass);
|
||||
|
||||
if (! class_exists($seederClassName)) {
|
||||
$this->error('❌ 시더 클래스를 찾을 수 없습니다: '.$seederClassName);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$this->info("🌱 시더 실행 시작: {$identifier}");
|
||||
$this->line(' 클래스: '.$seederClassName);
|
||||
$this->line('');
|
||||
|
||||
// 시더 실행
|
||||
$seeder = app($seederClassName);
|
||||
$seeder->setCommand($this);
|
||||
|
||||
// --sample 옵션 전파
|
||||
if (method_exists($seeder, 'setIncludeSample')) {
|
||||
$seeder->setIncludeSample((bool) $this->option('sample'));
|
||||
}
|
||||
|
||||
// --count 옵션 전파
|
||||
$counts = $this->parseCountOptions();
|
||||
if (! empty($counts) && method_exists($seeder, 'setSeederCounts')) {
|
||||
$seeder->setSeederCounts($counts);
|
||||
}
|
||||
|
||||
$seeder->run();
|
||||
|
||||
$this->line('');
|
||||
$this->info("✅ 시더 실행 완료: {$identifier}");
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 모듈 시더 실행
|
||||
*
|
||||
* @param string|null $seederClass 특정 시더 클래스명
|
||||
* @return int 명령 실행 결과
|
||||
*/
|
||||
private function seedAllActiveModules(?string $seederClass): int
|
||||
{
|
||||
$activeModules = $this->moduleManager->getActiveModules();
|
||||
|
||||
if (empty($activeModules)) {
|
||||
$this->warn('⚠️ 활성화된 모듈이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 시더가 있는 모듈만 필터링
|
||||
$seedableModules = [];
|
||||
|
||||
foreach ($activeModules as $identifier => $module) {
|
||||
$seederPath = base_path("modules/{$identifier}/database/seeders");
|
||||
$seederClassName = $this->resolveSeederClass($identifier, $seederClass);
|
||||
|
||||
if (is_dir($seederPath) && class_exists($seederClassName)) {
|
||||
$seedableModules[$identifier] = $module;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($seedableModules)) {
|
||||
$this->warn('⚠️ 시더가 있는 활성 모듈이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info('🌱 모든 활성 모듈 시더 실행 시작');
|
||||
$this->line(' 대상 모듈: '.implode(', ', array_keys($seedableModules)));
|
||||
$this->line('');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($seedableModules as $identifier => $module) {
|
||||
$this->line("━━━ [{$identifier}] ━━━");
|
||||
$result = $this->seedModule($identifier, $seederClass);
|
||||
|
||||
if ($result === Command::SUCCESS) {
|
||||
$successCount++;
|
||||
} else {
|
||||
$failCount++;
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
$this->info("📊 시더 실행 결과: 성공 {$successCount}개, 실패 {$failCount}개");
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* --count 옵션을 파싱하여 연관 배열로 반환합니다.
|
||||
*
|
||||
* 입력: ['products=1000', 'orders=500']
|
||||
* 출력: ['products' => 1000, 'orders' => 500]
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function parseCountOptions(): array
|
||||
{
|
||||
$countOptions = $this->option('count');
|
||||
$counts = [];
|
||||
|
||||
foreach ($countOptions as $option) {
|
||||
if (str_contains($option, '=')) {
|
||||
[$key, $value] = explode('=', $option, 2);
|
||||
$key = trim($key);
|
||||
if ($key !== '') {
|
||||
$counts[$key] = (int) trim($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 시더 클래스명 해석
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param string|null $seederClass 사용자 지정 시더 클래스명
|
||||
* @return string 완전한 시더 클래스명
|
||||
*/
|
||||
private function resolveSeederClass(string $identifier, ?string $seederClass): string
|
||||
{
|
||||
$namespace = ExtensionManager::moduleIdentifierToNamespace($identifier);
|
||||
|
||||
if ($seederClass) {
|
||||
// 사용자가 지정한 클래스명 사용
|
||||
if (str_contains($seederClass, '\\')) {
|
||||
return $seederClass;
|
||||
}
|
||||
|
||||
return $namespace.'Database\\Seeders\\'.$seederClass;
|
||||
}
|
||||
|
||||
// 기본 DatabaseSeeder 사용
|
||||
return $namespace.'Database\\Seeders\\DatabaseSeeder';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Models\Menu;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class UninstallModuleCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:uninstall
|
||||
{identifier : 제거할 모듈 식별자}
|
||||
{--force : 확인 없이 삭제}
|
||||
{--delete-data : 모듈 데이터(테이블, 환경설정) 함께 삭제}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈을 제거합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 모듈 디렉토리 스캔 및 로드
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
// 모듈이 설치되어 있는지 확인
|
||||
$moduleRecord = $this->moduleRepository->findByIdentifier($identifier);
|
||||
if (! $moduleRecord) {
|
||||
$this->error('❌ '.__('modules.commands.uninstall.not_installed', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 모듈 인스턴스에서 role 개수 조회
|
||||
$moduleInstance = $this->moduleManager->getModule($identifier);
|
||||
$rolesCount = 0;
|
||||
if ($moduleInstance && method_exists($moduleInstance, 'getRoles')) {
|
||||
$rolesCount = count($moduleInstance->getRoles());
|
||||
}
|
||||
|
||||
// 권한, 메뉴, 레이아웃 개수 조회
|
||||
$permissionsCount = Permission::byExtension(ExtensionOwnerType::Module, $identifier)->count();
|
||||
$menusCount = Menu::byExtension(ExtensionOwnerType::Module, $identifier)->count();
|
||||
$layoutsCount = $this->moduleManager->getModuleLayoutsCount($identifier);
|
||||
|
||||
// 확인 프롬프트 (--force 옵션이 없는 경우)
|
||||
if (! $this->option('force')) {
|
||||
$this->warn(__('modules.commands.uninstall.confirm_prompt', ['module' => $identifier]));
|
||||
$this->line(__('modules.commands.uninstall.confirm_details.roles', ['count' => $rolesCount]));
|
||||
$this->line(__('modules.commands.uninstall.confirm_details.permissions', ['count' => $permissionsCount]));
|
||||
$this->line(__('modules.commands.uninstall.confirm_details.menus', ['count' => $menusCount]));
|
||||
$this->line(__('modules.commands.uninstall.confirm_details.layouts', ['count' => $layoutsCount]));
|
||||
$this->line(__('modules.commands.uninstall.confirm_details.data'));
|
||||
if ($this->option('delete-data')) {
|
||||
$this->warn('⚠️ --delete-data: 마이그레이션 롤백 및 환경설정 파일이 함께 삭제됩니다.');
|
||||
}
|
||||
$this->newLine();
|
||||
|
||||
if (! $this->confirm(__('modules.commands.uninstall.confirm_question'), false)) {
|
||||
$this->info(__('modules.commands.uninstall.aborted'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
// 모듈 제거
|
||||
$deleteData = $this->option('delete-data');
|
||||
$onProgress = $this->createProgressCallback(ModuleManager::UNINSTALL_STEPS);
|
||||
try {
|
||||
$result = $this->moduleManager->uninstallModule($identifier, $deleteData, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
$this->info('✅ '.__('modules.commands.uninstall.success', ['module' => $identifier]));
|
||||
$this->info(' - '.__('modules.commands.uninstall.roles_deleted', ['count' => $rolesCount]));
|
||||
$this->info(' - '.__('modules.commands.uninstall.permissions_deleted', ['count' => $permissionsCount]));
|
||||
$this->info(' - '.__('modules.commands.uninstall.menus_deleted', ['count' => $menusCount]));
|
||||
$this->info(' - '.__('modules.commands.uninstall.layouts_deleted', ['count' => $layoutsCount]));
|
||||
Log::info(__('modules.commands.uninstall.success', ['module' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('모듈 제거 실패', [
|
||||
'module' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Module;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Extension\ModuleManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class UpdateModuleCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'module:update
|
||||
{identifier : 업데이트할 모듈 식별자}
|
||||
{--force : 버전 비교 없이 강제 업데이트}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '모듈을 최신 버전으로 업데이트합니다';
|
||||
|
||||
/**
|
||||
* 모듈 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private ModuleManager $moduleManager,
|
||||
private ModuleRepositoryInterface $moduleRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$force = $this->option('force');
|
||||
|
||||
try {
|
||||
$this->moduleManager->loadModules();
|
||||
|
||||
// 모듈 존재 확인
|
||||
$module = $this->moduleRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $module) {
|
||||
$this->error('❌ '.__('modules.commands.update.not_installed', ['module' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 업데이트 확인
|
||||
$checkResult = $this->moduleManager->checkModuleUpdate($identifier);
|
||||
|
||||
if (! $checkResult['update_available'] && ! $force) {
|
||||
$this->info('✅ '.__('modules.commands.update.no_update', ['module' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 업데이트 정보 표시
|
||||
$this->info(__('modules.commands.update.current_version', ['version' => $checkResult['current_version']]));
|
||||
|
||||
if ($force && ! $checkResult['update_available']) {
|
||||
$this->warn('⚠️ '.__('modules.commands.update.force_mode'));
|
||||
} else {
|
||||
$this->info(__('modules.commands.update.latest_version', ['version' => $checkResult['latest_version']]));
|
||||
$this->info(__('modules.commands.update.update_source', ['source' => $checkResult['update_source']]));
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// 확인 프롬프트 (--force 시 건너뜀)
|
||||
if (! $force && ! $this->confirm(__('modules.commands.update.confirm_question'), false)) {
|
||||
$this->info(__('modules.commands.update.aborted'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 업데이트 실행
|
||||
$onProgress = $this->createProgressCallback(ModuleManager::UPDATE_STEPS);
|
||||
try {
|
||||
$updateResult = $this->moduleManager->updateModule($identifier, $force, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($updateResult['success']) {
|
||||
$this->newLine();
|
||||
$this->info('✅ '.__('modules.commands.update.success', ['module' => $identifier]));
|
||||
$this->info(' '.__('modules.commands.update.version_change', [
|
||||
'from' => $updateResult['from_version'],
|
||||
'to' => $updateResult['to_version'],
|
||||
]));
|
||||
|
||||
Log::info('모듈 업데이트 완료', [
|
||||
'module' => $identifier,
|
||||
'from' => $updateResult['from_version'],
|
||||
'to' => $updateResult['to_version'],
|
||||
]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
$this->warn('💡 '.__('modules.commands.update.backup_restored'));
|
||||
|
||||
Log::error('모듈 업데이트 실패', [
|
||||
'module' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ActivatePluginCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:activate {identifier : 활성화할 플러그인 식별자} {--force : 의존성 미충족 시 강제 활성화}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인을 활성화합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 플러그인 디렉토리 스캔 및 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
// 플러그인이 설치되어 있는지 확인
|
||||
$pluginRecord = $this->pluginRepository->findByIdentifier($identifier);
|
||||
if (! $pluginRecord) {
|
||||
$this->error('❌ '.__('plugins.commands.activate.not_installed', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 이미 활성화된 플러그인인지 확인
|
||||
if ($pluginRecord->status === ExtensionStatus::Active->value) {
|
||||
$this->warn('⚠️ '.__('plugins.commands.activate.already_active', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 플러그인 활성화
|
||||
$force = $this->option('force');
|
||||
$result = $this->pluginManager->activatePlugin($identifier, $force);
|
||||
|
||||
// 경고 응답인 경우 (의존성 미충족)
|
||||
if (isset($result['warning']) && $result['warning'] === true) {
|
||||
$this->warn('⚠️ '.$result['message']);
|
||||
$this->line('');
|
||||
|
||||
if (! empty($result['missing_modules'])) {
|
||||
$this->info('필요한 모듈:');
|
||||
foreach ($result['missing_modules'] as $module) {
|
||||
$statusLabel = $module['status'] === 'not_installed' ? '미설치' : '비활성';
|
||||
$this->line(" - {$module['identifier']} ({$module['name']}) [{$statusLabel}]");
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($result['missing_plugins'])) {
|
||||
$this->info('필요한 플러그인:');
|
||||
foreach ($result['missing_plugins'] as $plugin) {
|
||||
$statusLabel = $plugin['status'] === 'not_installed' ? '미설치' : '비활성';
|
||||
$this->line(" - {$plugin['identifier']} ({$plugin['name']}) [{$statusLabel}]");
|
||||
}
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
$this->info('강제로 활성화하려면 --force 옵션을 사용하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if ($result['success']) {
|
||||
$this->info('✅ '.__('plugins.commands.activate.success', ['plugin' => $identifier]));
|
||||
$this->info(' - '.__('plugins.commands.activate.layouts_registered', ['count' => $result['layouts_registered']]));
|
||||
Log::info(__('plugins.commands.activate.success', ['plugin' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 활성화 실패', [
|
||||
'plugin' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
class BuildPluginCommand extends Command
|
||||
{
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:build
|
||||
{identifier? : 빌드할 플러그인 식별자 (생략 시 --all 필요)}
|
||||
{--all : 모든 플러그인 빌드}
|
||||
{--watch : 파일 변경 감시 모드}
|
||||
{--production : 프로덕션 빌드}
|
||||
{--active : 활성 디렉토리에서 빌드}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인의 프론트엔드 에셋을 빌드합니다 (기본: _bundled 디렉토리)';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$buildAll = $this->option('all');
|
||||
$watchMode = $this->option('watch');
|
||||
$productionMode = $this->option('production');
|
||||
|
||||
if (! $identifier && ! $buildAll) {
|
||||
$this->error('❌ 플러그인 식별자를 지정하거나 --all 옵션을 사용하세요.');
|
||||
$this->line('');
|
||||
$this->line('사용법:');
|
||||
$this->line(' php artisan plugin:build sirsoft-payment');
|
||||
$this->line(' php artisan plugin:build --all');
|
||||
$this->line(' php artisan plugin:build sirsoft-payment --watch');
|
||||
$this->line(' php artisan plugin:build --all --production');
|
||||
$this->line(' php artisan plugin:build sirsoft-payment --active');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 플러그인 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
if ($buildAll) {
|
||||
return $this->buildAllPlugins($productionMode);
|
||||
}
|
||||
|
||||
return $this->buildPlugin($identifier, $watchMode, $productionMode);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 빌드 실패', [
|
||||
'plugin' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드 대상 경로를 결정합니다.
|
||||
*
|
||||
* 기본값: _bundled 디렉토리. --active 옵션 시 활성 디렉토리.
|
||||
* --watch 모드에서는 활성 디렉토리를 사용합니다 (실시간 개발용).
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return array|null ['path' => string, 'source' => 'bundled'|'active'] 또는 null
|
||||
*/
|
||||
private function resolveBuildPath(string $identifier): ?array
|
||||
{
|
||||
$bundledPath = base_path("plugins/_bundled/{$identifier}");
|
||||
$activePath = base_path("plugins/{$identifier}");
|
||||
|
||||
// --active 명시 → 활성 디렉토리
|
||||
if ($this->option('active')) {
|
||||
return is_dir($activePath)
|
||||
? ['path' => $activePath, 'source' => 'active']
|
||||
: null;
|
||||
}
|
||||
|
||||
// --watch 모드 → 활성 디렉토리 (실시간 개발용)
|
||||
if ($this->option('watch')) {
|
||||
if (is_dir($activePath)) {
|
||||
return ['path' => $activePath, 'source' => 'active'];
|
||||
}
|
||||
}
|
||||
|
||||
// 기본값: _bundled 우선
|
||||
if (is_dir($bundledPath)) {
|
||||
return ['path' => $bundledPath, 'source' => 'bundled'];
|
||||
}
|
||||
|
||||
// _bundled에 없으면 활성 디렉토리 폴백
|
||||
if (is_dir($activePath)) {
|
||||
return ['path' => $activePath, 'source' => 'active'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 플러그인 빌드
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param bool $watchMode 파일 감시 모드
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildPlugin(string $identifier, bool $watchMode, bool $productionMode): int
|
||||
{
|
||||
// 경로 결정
|
||||
$resolved = $this->resolveBuildPath($identifier);
|
||||
if (! $resolved) {
|
||||
$this->error("❌ 플러그인을 찾을 수 없습니다: {$identifier}");
|
||||
$this->line(' _bundled 및 활성 디렉토리 모두 존재하지 않습니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$buildPath = $resolved['path'];
|
||||
$source = $resolved['source'];
|
||||
|
||||
// 소스 표시
|
||||
$sourceLabel = $source === 'bundled' ? '_bundled' : '활성';
|
||||
$this->info("📂 빌드 소스: {$sourceLabel} ({$buildPath})");
|
||||
|
||||
// package.json 존재 확인
|
||||
$packageJsonPath = $buildPath.'/package.json';
|
||||
if (! file_exists($packageJsonPath)) {
|
||||
$this->error('❌ package.json 파일이 없습니다: '.$packageJsonPath);
|
||||
$this->line(' 플러그인 프론트엔드 구조를 먼저 생성하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 에셋 빌드 가능 여부 확인 (활성 플러그인 인스턴스가 있는 경우)
|
||||
$plugin = $this->pluginManager->getPlugin($identifier);
|
||||
if ($plugin && ! $plugin->canBuild() && ! $plugin->hasAssets()) {
|
||||
$this->warn('⚠️ 플러그인에 빌드할 에셋이 없습니다: '.$identifier);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// node_modules 확인 및 설치
|
||||
if (! is_dir($buildPath.'/node_modules')) {
|
||||
$this->info('📦 의존성 설치 중...');
|
||||
$installResult = $this->runNpmCommand(['npm', 'install'], $buildPath);
|
||||
|
||||
if ($installResult !== Command::SUCCESS) {
|
||||
$this->error('❌ npm install 실패');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
// 빌드 명령 결정
|
||||
$buildCommand = ['npm', 'run'];
|
||||
|
||||
if ($watchMode) {
|
||||
$buildCommand[] = 'dev';
|
||||
$this->info("👀 파일 감시 모드로 빌드 시작: {$identifier}");
|
||||
$this->line(' Ctrl+C로 종료할 수 있습니다.');
|
||||
} else {
|
||||
$buildCommand[] = 'build';
|
||||
$this->info("🔨 빌드 시작: {$identifier}".($productionMode ? ' (프로덕션)' : ''));
|
||||
}
|
||||
|
||||
// 빌드 실행
|
||||
$result = $this->runNpmCommand($buildCommand, $buildPath, ! $watchMode);
|
||||
|
||||
if ($result === Command::SUCCESS && ! $watchMode) {
|
||||
$this->info("✅ 빌드 완료: {$identifier}");
|
||||
|
||||
// 빌드 결과 파일 확인
|
||||
$this->displayBuildResults($buildPath, $identifier);
|
||||
|
||||
// 캐시 버전 증가 (브라우저 캐시 무효화)
|
||||
$this->incrementExtensionCacheVersion();
|
||||
$this->line(' - 캐시 버전 갱신됨');
|
||||
|
||||
// _bundled 빌드 시 활성 반영 안내
|
||||
if ($source === 'bundled') {
|
||||
$this->line('');
|
||||
$this->info("💡 활성 디렉토리에 반영하려면: php artisan plugin:update {$identifier}");
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드 결과 파일 정보를 출력합니다.
|
||||
*
|
||||
* @param string $buildPath 빌드된 경로
|
||||
* @param string $identifier 플러그인 식별자
|
||||
*/
|
||||
private function displayBuildResults(string $buildPath, string $identifier): void
|
||||
{
|
||||
// 활성 플러그인 인스턴스가 있으면 getBuiltAssetPaths 활용
|
||||
$plugin = $this->pluginManager->getPlugin($identifier);
|
||||
if ($plugin) {
|
||||
$builtPaths = $plugin->getBuiltAssetPaths();
|
||||
|
||||
if (! empty($builtPaths['js'])) {
|
||||
$jsPath = $buildPath.'/'.$builtPaths['js'];
|
||||
if (file_exists($jsPath)) {
|
||||
$this->line(' - JS: '.$builtPaths['js'].' ('.number_format(filesize($jsPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($builtPaths['css'])) {
|
||||
$cssPath = $buildPath.'/'.$builtPaths['css'];
|
||||
if (file_exists($cssPath)) {
|
||||
$this->line(' - CSS: '.$builtPaths['css'].' ('.number_format(filesize($cssPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 활성 인스턴스 없으면 manifest에서 직접 확인
|
||||
$manifestPath = $buildPath.'/plugin.json';
|
||||
if (file_exists($manifestPath)) {
|
||||
$manifest = json_decode(file_get_contents($manifestPath), true);
|
||||
$assets = $manifest['assets'] ?? [];
|
||||
|
||||
if (! empty($assets['js']['output'])) {
|
||||
$jsPath = $buildPath.'/'.$assets['js']['output'];
|
||||
if (file_exists($jsPath)) {
|
||||
$this->line(' - JS: '.$assets['js']['output'].' ('.number_format(filesize($jsPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($assets['css']['output'])) {
|
||||
$cssPath = $buildPath.'/'.$assets['css']['output'];
|
||||
if (file_exists($cssPath)) {
|
||||
$this->line(' - CSS: '.$assets['css']['output'].' ('.number_format(filesize($cssPath) / 1024, 2).' KB)');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 플러그인 빌드
|
||||
*
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildAllPlugins(bool $productionMode): int
|
||||
{
|
||||
$buildTargets = [];
|
||||
|
||||
if ($this->option('active')) {
|
||||
// --active: 활성 디렉토리만 대상
|
||||
$activePlugins = $this->pluginManager->getAllPlugins();
|
||||
foreach ($activePlugins as $identifier => $plugin) {
|
||||
$activePath = base_path("plugins/{$identifier}");
|
||||
if (file_exists($activePath.'/package.json')
|
||||
&& ($plugin->canBuild() || $plugin->hasAssets())) {
|
||||
$buildTargets[$identifier] = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 기본값: _bundled 디렉토리 스캔
|
||||
$bundledPlugins = $this->pluginManager->getBundledPlugins();
|
||||
foreach ($bundledPlugins as $identifier => $metadata) {
|
||||
$bundledPath = $metadata['source_path'];
|
||||
if (file_exists($bundledPath.'/package.json')) {
|
||||
$assets = $metadata['assets'] ?? [];
|
||||
if (! empty($assets['js']['entry']) || ! empty($assets['css']['entry']) || ! empty($assets)) {
|
||||
$buildTargets[$identifier] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($buildTargets)) {
|
||||
$this->warn('⚠️ 빌드할 플러그인이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$sourceLabel = $this->option('active') ? '활성' : '_bundled';
|
||||
$this->info("🔨 모든 플러그인 빌드 시작 ({$sourceLabel})".($productionMode ? ' (프로덕션)' : ''));
|
||||
$this->line(' 대상 플러그인: '.implode(', ', array_keys($buildTargets)));
|
||||
$this->line('');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($buildTargets as $identifier => $value) {
|
||||
$this->line(" [{$identifier}]");
|
||||
$result = $this->buildPlugin($identifier, false, $productionMode);
|
||||
|
||||
if ($result === Command::SUCCESS) {
|
||||
$successCount++;
|
||||
} else {
|
||||
$failCount++;
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
$this->info("📊 빌드 결과: 성공 {$successCount}개, 실패 {$failCount}개");
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* npm 명령 실행
|
||||
*
|
||||
* @param array $command 실행할 명령
|
||||
* @param string $cwd 작업 디렉토리
|
||||
* @param bool $waitForCompletion 완료 대기 여부
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function runNpmCommand(array $command, string $cwd, bool $waitForCompletion = true): int
|
||||
{
|
||||
// Windows 환경에서는 cmd /c 사용
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
$command = array_merge(['cmd', '/c'], $command);
|
||||
}
|
||||
|
||||
$process = new Process($command);
|
||||
$process->setWorkingDirectory($cwd);
|
||||
$process->setTimeout(null); // 타임아웃 없음
|
||||
|
||||
if ($waitForCompletion) {
|
||||
$process->run(function ($type, $buffer) {
|
||||
$this->output->write($buffer);
|
||||
});
|
||||
|
||||
return $process->isSuccessful() ? Command::SUCCESS : Command::FAILURE;
|
||||
}
|
||||
|
||||
// 감시 모드: 인터럽트까지 실행
|
||||
$process->start(function ($type, $buffer) {
|
||||
$this->output->write($buffer);
|
||||
});
|
||||
|
||||
// 프로세스가 실행 중인 동안 대기
|
||||
while ($process->isRunning()) {
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CheckPluginUpdatesCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:check-updates {identifier? : 특정 플러그인만 확인 (선택)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인 업데이트를 확인합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
if ($identifier) {
|
||||
return $this->checkSingle($identifier);
|
||||
}
|
||||
|
||||
return $this->checkAll();
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 업데이트 확인 실패', [
|
||||
'plugin' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 플러그인 업데이트를 확인합니다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
*/
|
||||
private function checkSingle(string $identifier): int
|
||||
{
|
||||
$plugin = $this->pluginRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $plugin) {
|
||||
$this->error('❌ '.__('plugins.commands.check_updates.not_installed', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$result = $this->pluginManager->checkPluginUpdate($identifier);
|
||||
|
||||
// 단일 체크는 DB 갱신이 안 되므로 커맨드에서 직접 갱신
|
||||
$this->pluginRepository->updateByIdentifier($identifier, [
|
||||
'update_available' => $result['update_available'],
|
||||
'latest_version' => $result['latest_version'],
|
||||
'update_source' => $result['update_source'],
|
||||
]);
|
||||
|
||||
if ($result['update_available']) {
|
||||
$this->info('🔄 '.__('plugins.commands.check_updates.single_update_available', [
|
||||
'plugin' => $identifier,
|
||||
'current' => $result['current_version'],
|
||||
'latest' => $result['latest_version'],
|
||||
'source' => $result['update_source'],
|
||||
]));
|
||||
} else {
|
||||
$this->info('✅ '.__('plugins.commands.check_updates.single_up_to_date', [
|
||||
'plugin' => $identifier,
|
||||
'version' => $result['current_version'],
|
||||
]));
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 설치된 플러그인의 업데이트를 확인합니다.
|
||||
*/
|
||||
private function checkAll(): int
|
||||
{
|
||||
$installedPlugins = $this->pluginManager->getInstalledPluginsWithDetails();
|
||||
|
||||
if (empty($installedPlugins)) {
|
||||
$this->info(__('plugins.commands.check_updates.no_installed'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// checkAllPluginsForUpdates는 내부에서 DB 갱신 포함
|
||||
$result = $this->pluginManager->checkAllPluginsForUpdates();
|
||||
|
||||
$tableData = [];
|
||||
$updateCount = 0;
|
||||
|
||||
foreach ($result['details'] as $detail) {
|
||||
$isUpdate = $detail['update_available'] ?? false;
|
||||
if ($isUpdate) {
|
||||
$updateCount++;
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
$detail['identifier'],
|
||||
$detail['current_version'] ?? '-',
|
||||
$detail['latest_version'] ?? '-',
|
||||
$detail['update_source'] ?? '-',
|
||||
$isUpdate
|
||||
? '🔄 '.__('plugins.commands.check_updates.update_available')
|
||||
: '✅ '.__('plugins.commands.check_updates.up_to_date'),
|
||||
];
|
||||
}
|
||||
|
||||
$headers = [
|
||||
__('plugins.commands.check_updates.headers.identifier'),
|
||||
__('plugins.commands.check_updates.headers.current_version'),
|
||||
__('plugins.commands.check_updates.headers.latest_version'),
|
||||
__('plugins.commands.check_updates.headers.source'),
|
||||
__('plugins.commands.check_updates.headers.status'),
|
||||
];
|
||||
|
||||
$this->table($headers, $tableData);
|
||||
$this->newLine();
|
||||
$this->info(__('plugins.commands.check_updates.summary', [
|
||||
'total' => count($result['details']),
|
||||
'updates' => $updateCount,
|
||||
]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ClearPluginCacheCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:cache-clear
|
||||
{identifier? : 특정 플러그인의 캐시만 삭제 (생략 시 모든 플러그인)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인 캐시를 삭제합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 플러그인 디렉토리 스캔 및 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
$clearedCount = 0;
|
||||
|
||||
if ($identifier) {
|
||||
// 특정 플러그인 캐시 삭제
|
||||
$this->info(__('plugins.commands.cache_clear.clearing_single', ['plugin' => $identifier]));
|
||||
|
||||
// 플러그인이 존재하는지 확인
|
||||
$plugin = $this->pluginManager->getPlugin($identifier);
|
||||
if (! $plugin) {
|
||||
$this->error('❌ '.__('plugins.not_found', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$clearedCount = $this->clearPluginCache($identifier);
|
||||
|
||||
$this->info('✅ '.__('plugins.commands.cache_clear.success_single', [
|
||||
'plugin' => $identifier,
|
||||
'count' => $clearedCount,
|
||||
]));
|
||||
} else {
|
||||
// 모든 플러그인 캐시 삭제
|
||||
$this->info(__('plugins.commands.cache_clear.clearing_all'));
|
||||
|
||||
// 전체 플러그인 캐시 키 삭제
|
||||
$cacheKeys = [
|
||||
'plugins.all',
|
||||
'plugins.active',
|
||||
'plugins.installed',
|
||||
];
|
||||
|
||||
foreach ($cacheKeys as $key) {
|
||||
if (Cache::forget($key)) {
|
||||
$clearedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// 각 플러그인별 캐시 삭제
|
||||
$allPlugins = $this->pluginManager->getAllPlugins();
|
||||
foreach ($allPlugins as $pluginName => $plugin) {
|
||||
$clearedCount += $this->clearPluginCache($plugin->getIdentifier());
|
||||
}
|
||||
|
||||
$this->info('✅ '.__('plugins.commands.cache_clear.success_all', ['count' => $clearedCount]));
|
||||
}
|
||||
|
||||
Log::info('플러그인 캐시 삭제 완료', [
|
||||
'plugin' => $identifier ?? 'all',
|
||||
'count' => $clearedCount,
|
||||
]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 캐시 삭제 실패', [
|
||||
'plugin' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 플러그인의 캐시를 삭제합니다.
|
||||
*/
|
||||
private function clearPluginCache(string $identifier): int
|
||||
{
|
||||
$clearedCount = 0;
|
||||
|
||||
// 플러그인별 캐시 키 (메뉴 캐시 없음)
|
||||
$cacheKeys = [
|
||||
"plugin.config.{$identifier}",
|
||||
"plugin.info.{$identifier}",
|
||||
"plugin.routes.{$identifier}",
|
||||
"plugin.permissions.{$identifier}",
|
||||
];
|
||||
|
||||
foreach ($cacheKeys as $key) {
|
||||
if (Cache::forget($key)) {
|
||||
$clearedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return $clearedCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Extension\ExtensionManager;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ComposerInstallPluginCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:composer-install
|
||||
{identifier? : Composer 의존성을 설치할 플러그인 식별자 (생략 시 --all 필요)}
|
||||
{--all : 모든 플러그인의 Composer 의존성 설치}
|
||||
{--no-dev : dev 의존성 제외}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인의 Composer 의존성을 설치합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private ExtensionManager $extensionManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$installAll = $this->option('all');
|
||||
$noDev = $this->option('no-dev');
|
||||
|
||||
if (! $identifier && ! $installAll) {
|
||||
$this->error('❌ 플러그인 식별자를 지정하거나 --all 옵션을 사용하세요.');
|
||||
$this->line('');
|
||||
$this->line('사용법:');
|
||||
$this->line(' php artisan plugin:composer-install sirsoft-payment');
|
||||
$this->line(' php artisan plugin:composer-install --all');
|
||||
$this->line(' php artisan plugin:composer-install --all --no-dev');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
if ($installAll) {
|
||||
return $this->installAllPlugins($noDev);
|
||||
}
|
||||
|
||||
return $this->installPlugin($identifier, $noDev);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 Composer 의존성 설치 실패', [
|
||||
'plugin' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 플러그인의 Composer 의존성 설치
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param bool $noDev dev 의존성 제외 여부
|
||||
* @return int 커맨드 결과 코드
|
||||
*/
|
||||
private function installPlugin(string $identifier, bool $noDev): int
|
||||
{
|
||||
$plugin = $this->pluginManager->getPlugin($identifier);
|
||||
|
||||
if (! $plugin) {
|
||||
$this->error('❌ '.__('plugins.errors.not_found', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if (! $this->extensionManager->hasComposerDependencies('plugins', $identifier)) {
|
||||
$this->info('ℹ️ '.__('plugins.composer_install.no_dependencies', ['plugin' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$deps = $this->extensionManager->getComposerDependencies('plugins', $identifier);
|
||||
$this->info('📦 '.__('plugins.composer_install.start', ['plugin' => $identifier]));
|
||||
$this->line(' '.implode(', ', array_keys($deps)));
|
||||
|
||||
$result = $this->extensionManager->runComposerInstall('plugins', $identifier, $noDev, $this);
|
||||
|
||||
if ($result) {
|
||||
$this->info('✅ '.__('plugins.composer_install.success', ['plugin' => $identifier]));
|
||||
|
||||
// 오토로드 갱신
|
||||
$this->extensionManager->updateComposerAutoload();
|
||||
$this->line(' 오토로드 캐시 갱신 완료');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->error('❌ '.__('plugins.composer_install.failed', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 플러그인의 Composer 의존성 설치
|
||||
*
|
||||
* @param bool $noDev dev 의존성 제외 여부
|
||||
* @return int 커맨드 결과 코드
|
||||
*/
|
||||
private function installAllPlugins(bool $noDev): int
|
||||
{
|
||||
$plugins = $this->pluginManager->getAllPlugins();
|
||||
|
||||
if (empty($plugins)) {
|
||||
$this->warn('⚠️ 설치된 플러그인이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 중복 패키지 감지
|
||||
$duplicates = $this->extensionManager->detectDuplicatePackages();
|
||||
if (! empty($duplicates)) {
|
||||
$this->warn('⚠️ 중복 패키지 감지:');
|
||||
foreach ($duplicates as $package => $users) {
|
||||
$this->warn(" - {$package}: ".implode(', ', $users));
|
||||
}
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
$this->info('📦 모든 플러그인의 Composer 의존성 설치 시작');
|
||||
|
||||
$successCount = 0;
|
||||
$skipCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($plugins as $identifier => $plugin) {
|
||||
if (! $this->extensionManager->hasComposerDependencies('plugins', $identifier)) {
|
||||
$skipCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->line(" [{$identifier}]");
|
||||
$result = $this->extensionManager->runComposerInstall('plugins', $identifier, $noDev, $this);
|
||||
|
||||
if ($result) {
|
||||
$successCount++;
|
||||
$this->info(" ✅ 완료: {$identifier}");
|
||||
} else {
|
||||
$failCount++;
|
||||
$this->error(" ❌ 실패: {$identifier}");
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
// 오토로드 갱신
|
||||
$this->extensionManager->updateComposerAutoload();
|
||||
|
||||
$this->info(__('plugins.composer_install.summary', [
|
||||
'success' => $successCount,
|
||||
'skip' => $skipCount,
|
||||
'fail' => $failCount,
|
||||
]));
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class DeactivatePluginCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:deactivate {identifier : 비활성화할 플러그인 식별자} {--force : 의존 확장이 있어도 강제 비활성화}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인을 비활성화합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 플러그인 디렉토리 스캔 및 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
// 플러그인이 설치되어 있는지 확인
|
||||
$pluginRecord = $this->pluginRepository->findByIdentifier($identifier);
|
||||
if (! $pluginRecord) {
|
||||
$this->error('❌ '.__('plugins.commands.deactivate.not_installed', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 플러그인이 활성화되어 있는지 확인
|
||||
if ($pluginRecord->status !== ExtensionStatus::Active->value) {
|
||||
$this->warn('⚠️ '.__('plugins.commands.deactivate.not_active', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 플러그인 비활성화
|
||||
$force = $this->option('force');
|
||||
$result = $this->pluginManager->deactivatePlugin($identifier, $force);
|
||||
|
||||
// 경고 응답인 경우 (의존 확장 존재)
|
||||
if (isset($result['warning']) && $result['warning'] === true) {
|
||||
$this->warn('⚠️ '.$result['message']);
|
||||
$this->line('');
|
||||
|
||||
// 의존하는 템플릿 목록
|
||||
if (! empty($result['dependent_templates'])) {
|
||||
$this->info('의존하는 템플릿 목록:');
|
||||
foreach ($result['dependent_templates'] as $template) {
|
||||
$this->line(" - {$template['identifier']} ({$template['name']})");
|
||||
}
|
||||
}
|
||||
|
||||
// 의존하는 모듈 목록
|
||||
if (! empty($result['dependent_modules'])) {
|
||||
$this->info('의존하는 모듈 목록:');
|
||||
foreach ($result['dependent_modules'] as $module) {
|
||||
$this->line(" - {$module['identifier']} ({$module['name']})");
|
||||
}
|
||||
}
|
||||
|
||||
// 의존하는 플러그인 목록
|
||||
if (! empty($result['dependent_plugins'])) {
|
||||
$this->info('의존하는 플러그인 목록:');
|
||||
foreach ($result['dependent_plugins'] as $plugin) {
|
||||
$this->line(" - {$plugin['identifier']} ({$plugin['name']})");
|
||||
}
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
$this->info('강제로 비활성화하려면 --force 옵션을 사용하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if ($result['success']) {
|
||||
$this->info('✅ '.__('plugins.commands.deactivate.success', ['plugin' => $identifier]));
|
||||
$this->info(' - '.__('plugins.commands.deactivate.layouts_deleted', ['count' => $result['layouts_deleted']]));
|
||||
$this->warn('⚠️ '.__('plugins.commands.deactivate.warning'));
|
||||
Log::info(__('plugins.commands.deactivate.success', ['plugin' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 비활성화 실패', [
|
||||
'plugin' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Permission;
|
||||
use App\Rules\ValidExtensionIdentifier;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class InstallPluginCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:install {identifier : 설치할 플러그인 식별자}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인을 설치합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
// 식별자 형식 검증
|
||||
$validator = Validator::make(
|
||||
['identifier' => $identifier],
|
||||
['identifier' => [new ValidExtensionIdentifier]]
|
||||
);
|
||||
|
||||
if ($validator->fails()) {
|
||||
$this->error('❌ '.$validator->errors()->first('identifier'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 플러그인 디렉토리 스캔 및 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
// 이미 설치된 플러그인인지 확인
|
||||
$existingPlugin = $this->pluginRepository->findByIdentifier($identifier);
|
||||
if ($existingPlugin) {
|
||||
$this->warn('⚠️ '.__('plugins.commands.install.already_installed', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 플러그인 설치
|
||||
$onProgress = $this->createProgressCallback(PluginManager::INSTALL_STEPS);
|
||||
try {
|
||||
$result = $this->pluginManager->installPlugin($identifier, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
// 설치된 플러그인 정보 조회
|
||||
$plugin = $this->pluginRepository->findByIdentifier($identifier);
|
||||
|
||||
// 플러그인 인스턴스에서 생성된 role 개수 조회
|
||||
$pluginInstance = $this->pluginManager->getPlugin($identifier);
|
||||
$rolesCount = 0;
|
||||
if ($pluginInstance && method_exists($pluginInstance, 'getRoles')) {
|
||||
$rolesCount = count($pluginInstance->getRoles());
|
||||
}
|
||||
|
||||
// 권한 개수 조회
|
||||
$permissionsCount = Permission::byExtension(ExtensionOwnerType::Plugin, $identifier)->count();
|
||||
|
||||
// 성공 메시지
|
||||
$this->info('✅ '.__('plugins.commands.install.success', ['plugin' => $identifier]));
|
||||
$this->info(' - '.__('plugins.commands.install.vendor', ['vendor' => $plugin->vendor]));
|
||||
$this->info(' - '.__('plugins.commands.install.version', ['version' => $plugin->version]));
|
||||
$this->info(' - '.__('plugins.commands.install.roles_created', ['count' => $rolesCount]));
|
||||
$this->info(' - '.__('plugins.commands.install.permissions_created', ['count' => $permissionsCount]));
|
||||
|
||||
Log::info(__('plugins.commands.install.success', ['plugin' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 설치 실패', [
|
||||
'plugin' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class ListPluginCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:list
|
||||
{--status= : 상태로 필터 (installed, uninstalled, active, inactive)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인 목록을 조회합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
// 플러그인 디렉토리 스캔 및 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
$statusFilter = $this->option('status');
|
||||
|
||||
// 상태 필터 검증
|
||||
if ($statusFilter && ! in_array($statusFilter, ['installed', 'uninstalled', 'active', 'inactive'])) {
|
||||
$this->error('❌ '.__('plugins.commands.list.invalid_status'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 설치된 플러그인 정보
|
||||
$installedPlugins = $this->pluginManager->getInstalledPluginsWithDetails();
|
||||
|
||||
// 미설치 플러그인 정보
|
||||
$uninstalledPlugins = $this->pluginManager->getUninstalledPlugins();
|
||||
|
||||
// 테이블 데이터 준비
|
||||
$tableData = [];
|
||||
|
||||
// 설치된 플러그인 추가
|
||||
foreach ($installedPlugins as $identifier => $plugin) {
|
||||
// 상태 필터
|
||||
if ($statusFilter) {
|
||||
if ($statusFilter === 'uninstalled') {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'active' && $plugin['status'] !== ExtensionStatus::Active->value) {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'inactive' && $plugin['status'] !== ExtensionStatus::Inactive->value) {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'installed' && ! in_array($plugin['status'], [ExtensionStatus::Active->value, ExtensionStatus::Inactive->value])) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
'identifier' => $identifier,
|
||||
'name' => $plugin['name'],
|
||||
'vendor' => $plugin['vendor'],
|
||||
'version' => $plugin['version'],
|
||||
'status' => $this->formatStatus($plugin['status']),
|
||||
];
|
||||
}
|
||||
|
||||
// 미설치 플러그인 추가
|
||||
if (! $statusFilter || $statusFilter === 'uninstalled') {
|
||||
foreach ($uninstalledPlugins as $identifier => $plugin) {
|
||||
// 상태 필터 (uninstalled 또는 필터 없음)
|
||||
if ($statusFilter && $statusFilter !== 'uninstalled') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
'identifier' => $identifier,
|
||||
'name' => $plugin['name'],
|
||||
'vendor' => $plugin['vendor'],
|
||||
'version' => $plugin['version'],
|
||||
'status' => $this->formatStatus('uninstalled'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 플러그인이 없는 경우
|
||||
if (empty($tableData)) {
|
||||
$this->info(__('plugins.commands.list.no_plugins'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 테이블 헤더
|
||||
$headers = [
|
||||
__('plugins.commands.list.headers.identifier'),
|
||||
__('plugins.commands.list.headers.name'),
|
||||
__('plugins.commands.list.headers.vendor'),
|
||||
__('plugins.commands.list.headers.version'),
|
||||
__('plugins.commands.list.headers.status'),
|
||||
];
|
||||
|
||||
// 테이블 출력
|
||||
$this->table($headers, $tableData);
|
||||
|
||||
// 요약 정보
|
||||
$totalCount = count($tableData);
|
||||
$activeCount = count(array_filter($tableData, fn ($p) => str_contains($p['status'], __('plugins.commands.list.status.active'))));
|
||||
$installedCount = count(array_filter($tableData, fn ($p) => ! str_contains($p['status'], __('plugins.commands.list.status.uninstalled'))));
|
||||
|
||||
$this->newLine();
|
||||
$this->info(__('plugins.commands.list.summary', [
|
||||
'total' => $totalCount,
|
||||
'installed' => $installedCount,
|
||||
'active' => $activeCount,
|
||||
]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상태 포맷팅
|
||||
*/
|
||||
private function formatStatus(string $status): string
|
||||
{
|
||||
return match ($status) {
|
||||
ExtensionStatus::Active->value => '✅ '.__('plugins.commands.list.status.active'),
|
||||
ExtensionStatus::Inactive->value => '⏸️ '.__('plugins.commands.list.status.inactive'),
|
||||
'uninstalled' => '📦 '.__('plugins.commands.list.status.uninstalled'),
|
||||
default => $status,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Models\Plugin;
|
||||
use App\Services\PluginService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 플러그인 레이아웃 갱신 커맨드
|
||||
*
|
||||
* 레이아웃 JSON 파일만 수정된 경우, 빌드 없이 레이아웃만 갱신합니다.
|
||||
*/
|
||||
class RefreshPluginLayoutCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:refresh-layout
|
||||
{identifier? : 특정 플러그인의 식별자 (생략 시 모든 활성 플러그인)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인 레이아웃을 갱신합니다 (빌드 없이 JSON만 DB에 동기화)';
|
||||
|
||||
public function __construct(
|
||||
private PluginService $pluginService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
if ($identifier) {
|
||||
return $this->refreshSingle($identifier);
|
||||
}
|
||||
|
||||
return $this->refreshAll();
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 레이아웃 갱신 실패', [
|
||||
'plugin' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 플러그인의 레이아웃을 갱신합니다.
|
||||
*/
|
||||
private function refreshSingle(string $identifier): int
|
||||
{
|
||||
$this->info("플러그인 '{$identifier}' 레이아웃 갱신 중...");
|
||||
|
||||
$result = $this->pluginService->refreshPluginLayouts($identifier);
|
||||
|
||||
if ($result['success'] ?? false) {
|
||||
$this->info("✅ 플러그인 '{$identifier}' 레이아웃 갱신 완료");
|
||||
$this->line(" 생성: {$result['created']}, 수정: {$result['updated']}, 삭제: {$result['deleted']}");
|
||||
Log::info('플러그인 레이아웃 갱신 완료', [
|
||||
'plugin' => $identifier,
|
||||
'stats' => $result,
|
||||
]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->error("❌ 플러그인 '{$identifier}' 레이아웃 갱신 실패");
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 플러그인의 레이아웃을 갱신합니다.
|
||||
*/
|
||||
private function refreshAll(): int
|
||||
{
|
||||
$plugins = Plugin::where('status', 'active')->pluck('identifier')->toArray();
|
||||
|
||||
if (empty($plugins)) {
|
||||
$this->line('활성화된 플러그인이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info('모든 활성 플러그인 레이아웃 갱신 중...');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($plugins as $pluginIdentifier) {
|
||||
$this->line(" {$pluginIdentifier} 갱신 중...");
|
||||
|
||||
try {
|
||||
$result = $this->pluginService->refreshPluginLayouts($pluginIdentifier);
|
||||
|
||||
if ($result['success'] ?? false) {
|
||||
$this->info(" ✅ {$pluginIdentifier} 완료");
|
||||
$successCount++;
|
||||
} else {
|
||||
$this->warn(" ⚠️ {$pluginIdentifier} 실패");
|
||||
$failCount++;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$this->warn(" ⚠️ {$pluginIdentifier}: ".$e->getMessage());
|
||||
$failCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info("✅ 총 {$successCount}개 성공, {$failCount}개 실패");
|
||||
|
||||
Log::info('플러그인 레이아웃 일괄 갱신 완료', [
|
||||
'success' => $successCount,
|
||||
'failed' => $failCount,
|
||||
]);
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\ExtensionManager;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class SeedPluginCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:seed
|
||||
{identifier? : 시더를 실행할 플러그인 식별자 (생략 시 모든 활성 플러그인)}
|
||||
{--class= : 실행할 특정 시더 클래스명}
|
||||
{--count=* : 시더에 전달할 카운트 옵션 (형식: key=value, 예: --count=products=1000)}
|
||||
{--sample : 샘플 데이터 시더도 함께 실행}
|
||||
{--force : 프로덕션 환경에서도 강제 실행}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인의 데이터베이스 시더를 실행합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$seederClass = $this->option('class');
|
||||
$force = $this->option('force');
|
||||
|
||||
// 프로덕션 환경 확인
|
||||
if (app()->environment('production') && ! $force) {
|
||||
$this->error('❌ 프로덕션 환경에서는 --force 옵션이 필요합니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 플러그인 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
if ($identifier) {
|
||||
return $this->seedPlugin($identifier, $seederClass);
|
||||
}
|
||||
|
||||
return $this->seedAllActivePlugins($seederClass);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 시더 실행 실패', [
|
||||
'plugin' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 플러그인 시더 실행
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param string|null $seederClass 특정 시더 클래스명
|
||||
* @return int 명령 실행 결과
|
||||
*/
|
||||
private function seedPlugin(string $identifier, ?string $seederClass): int
|
||||
{
|
||||
// 플러그인 존재 여부 확인
|
||||
$plugin = $this->pluginManager->getPlugin($identifier);
|
||||
|
||||
if (! $plugin) {
|
||||
$this->error('❌ '.__('plugins.not_found', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 활성화 상태 확인
|
||||
$pluginRecord = $this->pluginRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $pluginRecord || $pluginRecord->status !== ExtensionStatus::Active->value) {
|
||||
$this->error('❌ 플러그인이 활성화되어 있지 않습니다: '.$identifier);
|
||||
$this->line(' 먼저 php artisan plugin:activate '.$identifier.' 명령을 실행하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 시더 경로 확인
|
||||
$pluginPath = base_path("plugins/{$identifier}");
|
||||
$seederPath = $pluginPath.'/database/seeders';
|
||||
|
||||
if (! is_dir($seederPath)) {
|
||||
$this->warn('⚠️ 플러그인에 시더 디렉토리가 없습니다: '.$identifier);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 시더 클래스 결정
|
||||
$seederClassName = $this->resolveSeederClass($identifier, $seederClass);
|
||||
|
||||
if (! class_exists($seederClassName)) {
|
||||
$this->error('❌ 시더 클래스를 찾을 수 없습니다: '.$seederClassName);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$this->info("🌱 시더 실행 시작: {$identifier}");
|
||||
$this->line(' 클래스: '.$seederClassName);
|
||||
$this->line('');
|
||||
|
||||
// 시더 실행
|
||||
$seeder = app($seederClassName);
|
||||
$seeder->setCommand($this);
|
||||
|
||||
// --sample 옵션 전파
|
||||
if (method_exists($seeder, 'setIncludeSample')) {
|
||||
$seeder->setIncludeSample((bool) $this->option('sample'));
|
||||
}
|
||||
|
||||
// --count 옵션 전파
|
||||
$counts = $this->parseCountOptions();
|
||||
if (! empty($counts) && method_exists($seeder, 'setSeederCounts')) {
|
||||
$seeder->setSeederCounts($counts);
|
||||
}
|
||||
|
||||
$seeder->run();
|
||||
|
||||
$this->line('');
|
||||
$this->info("✅ 시더 실행 완료: {$identifier}");
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 플러그인 시더 실행
|
||||
*
|
||||
* @param string|null $seederClass 특정 시더 클래스명
|
||||
* @return int 명령 실행 결과
|
||||
*/
|
||||
private function seedAllActivePlugins(?string $seederClass): int
|
||||
{
|
||||
$activePlugins = $this->pluginManager->getActivePlugins();
|
||||
|
||||
if (empty($activePlugins)) {
|
||||
$this->warn('⚠️ 활성화된 플러그인이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 시더가 있는 플러그인만 필터링
|
||||
$seedablePlugins = [];
|
||||
|
||||
foreach ($activePlugins as $identifier => $plugin) {
|
||||
$seederPath = base_path("plugins/{$identifier}/database/seeders");
|
||||
$seederClassName = $this->resolveSeederClass($identifier, $seederClass);
|
||||
|
||||
if (is_dir($seederPath) && class_exists($seederClassName)) {
|
||||
$seedablePlugins[$identifier] = $plugin;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($seedablePlugins)) {
|
||||
$this->warn('⚠️ 시더가 있는 활성 플러그인이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info('🌱 모든 활성 플러그인 시더 실행 시작');
|
||||
$this->line(' 대상 플러그인: '.implode(', ', array_keys($seedablePlugins)));
|
||||
$this->line('');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($seedablePlugins as $identifier => $plugin) {
|
||||
$this->line("━━━ [{$identifier}] ━━━");
|
||||
$result = $this->seedPlugin($identifier, $seederClass);
|
||||
|
||||
if ($result === Command::SUCCESS) {
|
||||
$successCount++;
|
||||
} else {
|
||||
$failCount++;
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
$this->info("📊 시더 실행 결과: 성공 {$successCount}개, 실패 {$failCount}개");
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* --count 옵션을 파싱하여 연관 배열로 반환합니다.
|
||||
*
|
||||
* 입력: ['products=1000', 'orders=500']
|
||||
* 출력: ['products' => 1000, 'orders' => 500]
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function parseCountOptions(): array
|
||||
{
|
||||
$countOptions = $this->option('count');
|
||||
$counts = [];
|
||||
|
||||
foreach ($countOptions as $option) {
|
||||
if (str_contains($option, '=')) {
|
||||
[$key, $value] = explode('=', $option, 2);
|
||||
$key = trim($key);
|
||||
if ($key !== '') {
|
||||
$counts[$key] = (int) trim($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 시더 클래스명 해석
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param string|null $seederClass 사용자 지정 시더 클래스명
|
||||
* @return string 완전한 시더 클래스명
|
||||
*/
|
||||
private function resolveSeederClass(string $identifier, ?string $seederClass): string
|
||||
{
|
||||
$namespace = ExtensionManager::pluginIdentifierToNamespace($identifier);
|
||||
|
||||
if ($seederClass) {
|
||||
// 사용자가 지정한 클래스명 사용
|
||||
if (str_contains($seederClass, '\\')) {
|
||||
return $seederClass;
|
||||
}
|
||||
|
||||
return $namespace.'Database\\Seeders\\'.$seederClass;
|
||||
}
|
||||
|
||||
// 기본 DatabaseSeeder 사용
|
||||
return $namespace.'Database\\Seeders\\DatabaseSeeder';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class UninstallPluginCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:uninstall
|
||||
{identifier : 제거할 플러그인 식별자}
|
||||
{--force : 확인 없이 삭제}
|
||||
{--delete-data : 플러그인 데이터(테이블, 환경설정) 함께 삭제}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인을 제거합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 플러그인 디렉토리 스캔 및 로드
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
// 플러그인이 설치되어 있는지 확인
|
||||
$pluginRecord = $this->pluginRepository->findByIdentifier($identifier);
|
||||
if (! $pluginRecord) {
|
||||
$this->error('❌ '.__('plugins.commands.uninstall.not_installed', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 플러그인 인스턴스에서 role 개수 조회
|
||||
$pluginInstance = $this->pluginManager->getPlugin($identifier);
|
||||
$rolesCount = 0;
|
||||
if ($pluginInstance && method_exists($pluginInstance, 'getRoles')) {
|
||||
$rolesCount = count($pluginInstance->getRoles());
|
||||
}
|
||||
|
||||
// 권한, 레이아웃 개수 조회
|
||||
$permissionsCount = Permission::byExtension(ExtensionOwnerType::Plugin, $identifier)->count();
|
||||
$layoutsCount = $this->pluginManager->getPluginLayoutsCount($identifier);
|
||||
|
||||
// 확인 프롬프트 (--force 옵션이 없는 경우)
|
||||
if (! $this->option('force')) {
|
||||
$this->warn(__('plugins.commands.uninstall.confirm_prompt', ['plugin' => $identifier]));
|
||||
$this->line(__('plugins.commands.uninstall.confirm_details.roles', ['count' => $rolesCount]));
|
||||
$this->line(__('plugins.commands.uninstall.confirm_details.permissions', ['count' => $permissionsCount]));
|
||||
$this->line(__('plugins.commands.uninstall.confirm_details.layouts', ['count' => $layoutsCount]));
|
||||
$this->line(__('plugins.commands.uninstall.confirm_details.data'));
|
||||
if ($this->option('delete-data')) {
|
||||
$this->warn('⚠️ --delete-data: 마이그레이션 롤백 및 환경설정 파일이 함께 삭제됩니다.');
|
||||
}
|
||||
$this->newLine();
|
||||
|
||||
if (! $this->confirm(__('plugins.commands.uninstall.confirm_question'), false)) {
|
||||
$this->info(__('plugins.commands.uninstall.aborted'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
// 플러그인 제거
|
||||
$deleteData = $this->option('delete-data');
|
||||
$onProgress = $this->createProgressCallback(PluginManager::UNINSTALL_STEPS);
|
||||
try {
|
||||
$result = $this->pluginManager->uninstallPlugin($identifier, $deleteData, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
$this->info('✅ '.__('plugins.commands.uninstall.success', ['plugin' => $identifier]));
|
||||
$this->info(' - '.__('plugins.commands.uninstall.roles_deleted', ['count' => $rolesCount]));
|
||||
$this->info(' - '.__('plugins.commands.uninstall.permissions_deleted', ['count' => $permissionsCount]));
|
||||
$this->info(' - '.__('plugins.commands.uninstall.layouts_deleted', ['count' => $layoutsCount]));
|
||||
Log::info(__('plugins.commands.uninstall.success', ['plugin' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('플러그인 제거 실패', [
|
||||
'plugin' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Plugin;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use App\Extension\PluginManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class UpdatePluginCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'plugin:update
|
||||
{identifier : 업데이트할 플러그인 식별자}
|
||||
{--force : 버전 비교 없이 강제 업데이트}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '플러그인을 최신 버전으로 업데이트합니다';
|
||||
|
||||
/**
|
||||
* 플러그인 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private PluginManager $pluginManager,
|
||||
private PluginRepositoryInterface $pluginRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$force = $this->option('force');
|
||||
|
||||
try {
|
||||
$this->pluginManager->loadPlugins();
|
||||
|
||||
// 플러그인 존재 확인
|
||||
$plugin = $this->pluginRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $plugin) {
|
||||
$this->error('❌ '.__('plugins.commands.update.not_installed', ['plugin' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 업데이트 확인
|
||||
$checkResult = $this->pluginManager->checkPluginUpdate($identifier);
|
||||
|
||||
if (! $checkResult['update_available'] && ! $force) {
|
||||
$this->info('✅ '.__('plugins.commands.update.no_update', ['plugin' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 업데이트 정보 표시
|
||||
$this->info(__('plugins.commands.update.current_version', ['version' => $checkResult['current_version']]));
|
||||
|
||||
if ($force && ! $checkResult['update_available']) {
|
||||
$this->warn('⚠️ '.__('plugins.commands.update.force_mode'));
|
||||
} else {
|
||||
$this->info(__('plugins.commands.update.latest_version', ['version' => $checkResult['latest_version']]));
|
||||
$this->info(__('plugins.commands.update.update_source', ['source' => $checkResult['update_source']]));
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// 확인 프롬프트 (--force 시 건너뜀)
|
||||
if (! $force && ! $this->confirm(__('plugins.commands.update.confirm_question'), false)) {
|
||||
$this->info(__('plugins.commands.update.aborted'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 업데이트 실행
|
||||
$onProgress = $this->createProgressCallback(PluginManager::UPDATE_STEPS);
|
||||
try {
|
||||
$updateResult = $this->pluginManager->updatePlugin($identifier, $force, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($updateResult['success']) {
|
||||
$this->newLine();
|
||||
$this->info('✅ '.__('plugins.commands.update.success', ['plugin' => $identifier]));
|
||||
$this->info(' '.__('plugins.commands.update.version_change', [
|
||||
'from' => $updateResult['from_version'],
|
||||
'to' => $updateResult['to_version'],
|
||||
]));
|
||||
|
||||
Log::info('플러그인 업데이트 완료', [
|
||||
'plugin' => $identifier,
|
||||
'from' => $updateResult['from_version'],
|
||||
'to' => $updateResult['to_version'],
|
||||
]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
$this->warn('💡 '.__('plugins.commands.update.backup_restored'));
|
||||
|
||||
Log::error('플러그인 업데이트 실패', [
|
||||
'plugin' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Database\Console\Seeds\SeedCommand as BaseSeedCommand;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
|
||||
/**
|
||||
* db:seed 커맨드 확장
|
||||
*
|
||||
* Laravel 기본 db:seed 커맨드에 --count 옵션을 추가하여
|
||||
* 시더에 데이터 개수를 전달할 수 있게 합니다.
|
||||
*
|
||||
* 사용 예시:
|
||||
* php artisan db:seed --class=SomeSeeder --count=items=50000
|
||||
*/
|
||||
class SeedCommand extends BaseSeedCommand
|
||||
{
|
||||
/**
|
||||
* 시더 인스턴스를 컨테이너에서 생성합니다.
|
||||
*
|
||||
* 부모 메서드를 호출한 뒤, --count 옵션이 있으면
|
||||
* 시더에 setSeederCounts()로 전달합니다.
|
||||
*
|
||||
* @return \Illuminate\Database\Seeder
|
||||
*/
|
||||
protected function getSeeder()
|
||||
{
|
||||
$seeder = parent::getSeeder();
|
||||
|
||||
// --sample 옵션 전파
|
||||
if (method_exists($seeder, 'setIncludeSample')) {
|
||||
$seeder->setIncludeSample((bool) $this->option('sample'));
|
||||
}
|
||||
|
||||
// --count 옵션 전파
|
||||
$counts = $this->parseCountOptions();
|
||||
if (! empty($counts) && method_exists($seeder, 'setSeederCounts')) {
|
||||
$seeder->setSeederCounts($counts);
|
||||
}
|
||||
|
||||
return $seeder;
|
||||
}
|
||||
|
||||
/**
|
||||
* --count 옵션을 파싱하여 연관 배열로 반환합니다.
|
||||
*
|
||||
* 입력: ['products=1000', 'orders=500']
|
||||
* 출력: ['products' => 1000, 'orders' => 500]
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function parseCountOptions(): array
|
||||
{
|
||||
$countOptions = $this->option('count');
|
||||
$counts = [];
|
||||
|
||||
foreach ($countOptions as $option) {
|
||||
if (str_contains($option, '=')) {
|
||||
[$key, $value] = explode('=', $option, 2);
|
||||
$key = trim($key);
|
||||
if ($key !== '') {
|
||||
$counts[$key] = (int) trim($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 콘솔 커맨드 옵션을 정의합니다.
|
||||
*
|
||||
* 부모 옵션에 --count 옵션을 추가합니다.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getOptions()
|
||||
{
|
||||
return array_merge(parent::getOptions(), [
|
||||
['count', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, '시더에 전달할 카운트 옵션 (형식: key=value, 예: --count=products=1000)', []],
|
||||
['sample', null, InputOption::VALUE_NONE, '샘플 데이터 시더도 함께 실행'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* SEO 캐시 삭제 Artisan 커맨드
|
||||
*
|
||||
* 전체 또는 특정 레이아웃의 SEO 캐시를 삭제합니다.
|
||||
*/
|
||||
class SeoCacheClearCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @var string 커맨드 시그니처
|
||||
*/
|
||||
protected $signature = 'seo:clear {--layout= : 특정 레이아웃의 캐시만 삭제}';
|
||||
|
||||
/**
|
||||
* @var string 커맨드 설명
|
||||
*/
|
||||
protected $description = 'SEO 캐시 삭제';
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @param SeoCacheManagerInterface $cacheManager SEO 캐시 매니저
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(SeoCacheManagerInterface $cacheManager): int
|
||||
{
|
||||
$layout = $this->option('layout');
|
||||
|
||||
if ($layout) {
|
||||
$count = $cacheManager->invalidateByLayout($layout);
|
||||
$this->info(__('seo.cache_cleared_layout', [
|
||||
'layout' => $layout,
|
||||
'count' => $count,
|
||||
]));
|
||||
} else {
|
||||
$cacheManager->clearAll();
|
||||
$this->info(__('seo.cache_cleared_all'));
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Seo\SeoCacheStatsService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* SEO 캐시 통계 출력 Artisan 커맨드
|
||||
*
|
||||
* 지정된 기간 동안의 캐시 히트/미스 통계를 테이블 형식으로 출력합니다.
|
||||
*/
|
||||
class SeoCacheStatsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @var string 커맨드 시그니처
|
||||
*/
|
||||
protected $signature = 'seo:stats {--days=7 : 통계 기간 (일)}';
|
||||
|
||||
/**
|
||||
* @var string 커맨드 설명
|
||||
*/
|
||||
protected $description = 'SEO 캐시 통계 출력';
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @param SeoCacheStatsService $statsService SEO 캐시 통계 서비스
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(SeoCacheStatsService $statsService): int
|
||||
{
|
||||
$days = (int) $this->option('days');
|
||||
$since = Carbon::now()->subDays($days);
|
||||
|
||||
$this->info(__('seo.stats_period', ['days' => $days]));
|
||||
$this->newLine();
|
||||
|
||||
// 전체 통계
|
||||
$overall = $statsService->getStats($since);
|
||||
$this->info('=== ' . __('seo.stats_overall') . ' ===');
|
||||
$this->table(
|
||||
[__('seo.stats_metric'), __('seo.stats_value')],
|
||||
[
|
||||
[__('seo.stats_total_entries'), $overall['total_entries']],
|
||||
[__('seo.stats_hits'), $overall['hits']],
|
||||
[__('seo.stats_misses'), $overall['misses']],
|
||||
[__('seo.stats_hit_rate'), $overall['hit_rate'] . '%'],
|
||||
[__('seo.stats_avg_response_time'), $overall['avg_response_time_ms'] !== null ? $overall['avg_response_time_ms'] . 'ms' : 'N/A'],
|
||||
]
|
||||
);
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// 레이아웃별 통계
|
||||
$byLayout = $statsService->getStatsByLayout($since);
|
||||
if (! empty($byLayout)) {
|
||||
$this->info('=== ' . __('seo.stats_by_layout') . ' ===');
|
||||
$this->table(
|
||||
[__('seo.stats_layout_name'), __('seo.stats_total'), __('seo.stats_hits'), __('seo.stats_misses'), __('seo.stats_hit_rate'), __('seo.stats_avg_response_time')],
|
||||
array_map(fn ($row) => [
|
||||
$row['layout_name'] ?? 'N/A',
|
||||
$row['total'],
|
||||
$row['hits'],
|
||||
$row['misses'],
|
||||
$row['hit_rate'] . '%',
|
||||
$row['avg_response_time_ms'] !== null ? $row['avg_response_time_ms'] . 'ms' : 'N/A',
|
||||
], $byLayout)
|
||||
);
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// 모듈별 통계
|
||||
$byModule = $statsService->getStatsByModule($since);
|
||||
if (! empty($byModule)) {
|
||||
$this->info('=== ' . __('seo.stats_by_module') . ' ===');
|
||||
$this->table(
|
||||
[__('seo.stats_module_identifier'), __('seo.stats_total'), __('seo.stats_hits'), __('seo.stats_misses'), __('seo.stats_hit_rate'), __('seo.stats_avg_response_time')],
|
||||
array_map(fn ($row) => [
|
||||
$row['module_identifier'] ?? 'N/A',
|
||||
$row['total'],
|
||||
$row['hits'],
|
||||
$row['misses'],
|
||||
$row['hit_rate'] . '%',
|
||||
$row['avg_response_time_ms'] !== null ? $row['avg_response_time_ms'] . 'ms' : 'N/A',
|
||||
], $byModule)
|
||||
);
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* SEO 캐시 워밍업 Artisan 커맨드
|
||||
*
|
||||
* 모든 SEO 레이아웃을 사전 렌더링하여 캐시를 준비합니다.
|
||||
* Phase 5의 SeoDeclarationCollector 구현 후 실제 워밍업 로직이 추가됩니다.
|
||||
*/
|
||||
class SeoCacheWarmupCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @var string 커맨드 시그니처
|
||||
*/
|
||||
protected $signature = 'seo:warmup {--layout= : 특정 레이아웃만 워밍업}';
|
||||
|
||||
/**
|
||||
* @var string 커맨드 설명
|
||||
*/
|
||||
protected $description = 'SEO 캐시 워밍업 - 모든 SEO 레이아웃을 사전 렌더링합니다';
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$layout = $this->option('layout');
|
||||
|
||||
if ($layout) {
|
||||
$this->info(__('seo.warmup_started_layout', ['layout' => $layout]));
|
||||
} else {
|
||||
$this->info(__('seo.warmup_started'));
|
||||
}
|
||||
|
||||
// Phase 5의 SeoDeclarationCollector 구현 후 실제 워밍업 로직 추가 예정
|
||||
$this->info(__('seo.warmup_started'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Jobs\GenerateSitemapJob;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* Sitemap XML 생성 Artisan 커맨드
|
||||
*
|
||||
* 큐를 통한 비동기 실행 또는 --sync 옵션으로 동기 실행을 지원합니다.
|
||||
*/
|
||||
class SeoGenerateSitemapCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @var string 커맨드 시그니처
|
||||
*/
|
||||
protected $signature = 'seo:generate-sitemap {--sync : 동기 실행}';
|
||||
|
||||
/**
|
||||
* @var string 커맨드 설명
|
||||
*/
|
||||
protected $description = 'Sitemap XML을 생성합니다';
|
||||
|
||||
/**
|
||||
* 커맨드를 실행합니다.
|
||||
*
|
||||
* @return int 종료 코드
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
if ($this->option('sync')) {
|
||||
GenerateSitemapJob::dispatchSync();
|
||||
$this->info('Sitemap이 생성되었습니다.');
|
||||
} else {
|
||||
GenerateSitemapJob::dispatch();
|
||||
$this->info('Sitemap 생성이 큐에 디스패치되었습니다.');
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ActivateTemplateCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:activate {identifier : 템플릿 식별자} {--force : 의존성 미충족 시 강제 활성화}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿을 활성화합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager,
|
||||
private TemplateRepositoryInterface $templateRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 템플릿 디렉토리 스캔 및 로드
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
// 템플릿 존재 확인
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $template) {
|
||||
$this->error('❌ '.__('templates.commands.activate.not_installed', ['template' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 기존 활성 템플릿 조회
|
||||
$previousActive = $this->templateRepository->findActiveByType($template->type);
|
||||
|
||||
// 템플릿 활성화
|
||||
$force = $this->option('force');
|
||||
$result = $this->templateManager->activateTemplate($identifier, $force);
|
||||
|
||||
// 경고 응답인 경우 (의존성 미충족)
|
||||
if (isset($result['warning']) && $result['warning'] === true) {
|
||||
$this->warn('⚠️ '.$result['message']);
|
||||
$this->line('');
|
||||
|
||||
if (! empty($result['missing_modules'])) {
|
||||
$this->info('필요한 모듈:');
|
||||
foreach ($result['missing_modules'] as $module) {
|
||||
$statusLabel = $module['status'] === 'not_installed' ? '미설치' : '비활성';
|
||||
$this->line(" - {$module['identifier']} ({$module['name']}) [{$statusLabel}]");
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($result['missing_plugins'])) {
|
||||
$this->info('필요한 플러그인:');
|
||||
foreach ($result['missing_plugins'] as $plugin) {
|
||||
$statusLabel = $plugin['status'] === 'not_installed' ? '미설치' : '비활성';
|
||||
$this->line(" - {$plugin['identifier']} ({$plugin['name']}) [{$statusLabel}]");
|
||||
}
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
$this->info('강제로 활성화하려면 --force 옵션을 사용하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
if ($result['success']) {
|
||||
// 기존 템플릿 비활성화 메시지
|
||||
if ($previousActive && $previousActive->identifier !== $identifier) {
|
||||
$this->warn('ℹ️ '.__('templates.commands.activate.deactivated_previous', [
|
||||
'type' => __('templates.types.'.$template->type),
|
||||
'previous' => $previousActive->identifier,
|
||||
]));
|
||||
}
|
||||
|
||||
// 성공 메시지
|
||||
$this->info('✅ '.__('templates.commands.activate.success', ['template' => $identifier]));
|
||||
|
||||
Log::info(__('templates.commands.activate.success', ['template' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 활성화 실패', [
|
||||
'template' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
class BuildTemplateCommand extends Command
|
||||
{
|
||||
use ClearsTemplateCaches;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:build
|
||||
{identifier? : 빌드할 템플릿 식별자 (생략 시 --all 필요)}
|
||||
{--all : 모든 템플릿 빌드}
|
||||
{--watch : 파일 변경 감시 모드}
|
||||
{--production : 프로덕션 빌드}
|
||||
{--active : 활성 디렉토리에서 빌드}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿의 프론트엔드 에셋을 빌드합니다 (기본: _bundled 디렉토리)';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$buildAll = $this->option('all');
|
||||
$watchMode = $this->option('watch');
|
||||
$productionMode = $this->option('production');
|
||||
|
||||
if (! $identifier && ! $buildAll) {
|
||||
$this->error('❌ 템플릿 식별자를 지정하거나 --all 옵션을 사용하세요.');
|
||||
$this->line('');
|
||||
$this->line('사용법:');
|
||||
$this->line(' php artisan template:build sirsoft-admin_basic');
|
||||
$this->line(' php artisan template:build --all');
|
||||
$this->line(' php artisan template:build sirsoft-admin_basic --watch');
|
||||
$this->line(' php artisan template:build --all --production');
|
||||
$this->line(' php artisan template:build sirsoft-admin_basic --active');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 템플릿 로드
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
if ($buildAll) {
|
||||
return $this->buildAllTemplates($productionMode);
|
||||
}
|
||||
|
||||
return $this->buildTemplate($identifier, $watchMode, $productionMode);
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 빌드 실패', [
|
||||
'template' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 빌드 대상 경로를 결정합니다.
|
||||
*
|
||||
* 기본값: _bundled 디렉토리. --active 옵션 시 활성 디렉토리.
|
||||
* --watch 모드에서는 활성 디렉토리를 사용합니다 (실시간 개발용).
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return array|null ['path' => string, 'source' => 'bundled'|'active'] 또는 null
|
||||
*/
|
||||
private function resolveBuildPath(string $identifier): ?array
|
||||
{
|
||||
$bundledPath = base_path("templates/_bundled/{$identifier}");
|
||||
$activePath = base_path("templates/{$identifier}");
|
||||
|
||||
// --active 명시 → 활성 디렉토리
|
||||
if ($this->option('active')) {
|
||||
return is_dir($activePath)
|
||||
? ['path' => $activePath, 'source' => 'active']
|
||||
: null;
|
||||
}
|
||||
|
||||
// --watch 모드 → 활성 디렉토리 (실시간 개발용)
|
||||
if ($this->option('watch')) {
|
||||
if (is_dir($activePath)) {
|
||||
return ['path' => $activePath, 'source' => 'active'];
|
||||
}
|
||||
}
|
||||
|
||||
// 기본값: _bundled 우선
|
||||
if (is_dir($bundledPath)) {
|
||||
return ['path' => $bundledPath, 'source' => 'bundled'];
|
||||
}
|
||||
|
||||
// _bundled에 없으면 활성 디렉토리 폴백
|
||||
if (is_dir($activePath)) {
|
||||
return ['path' => $activePath, 'source' => 'active'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 템플릿 빌드
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param bool $watchMode 파일 감시 모드
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildTemplate(string $identifier, bool $watchMode, bool $productionMode): int
|
||||
{
|
||||
// 경로 결정
|
||||
$resolved = $this->resolveBuildPath($identifier);
|
||||
if (! $resolved) {
|
||||
$this->error("❌ 템플릿을 찾을 수 없습니다: {$identifier}");
|
||||
$this->line(' _bundled 및 활성 디렉토리 모두 존재하지 않습니다.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$buildPath = $resolved['path'];
|
||||
$source = $resolved['source'];
|
||||
|
||||
// 소스 표시
|
||||
$sourceLabel = $source === 'bundled' ? '_bundled' : '활성';
|
||||
$this->info("📂 빌드 소스: {$sourceLabel} ({$buildPath})");
|
||||
|
||||
// package.json 존재 확인
|
||||
$packageJsonPath = $buildPath.'/package.json';
|
||||
if (! file_exists($packageJsonPath)) {
|
||||
$this->error('❌ package.json 파일이 없습니다: '.$packageJsonPath);
|
||||
$this->line(' 템플릿 프론트엔드 구조를 먼저 생성하세요.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// node_modules 확인 및 설치
|
||||
if (! is_dir($buildPath.'/node_modules')) {
|
||||
$this->info('📦 의존성 설치 중...');
|
||||
$installResult = $this->runNpmCommand(['npm', 'install'], $buildPath);
|
||||
|
||||
if ($installResult !== Command::SUCCESS) {
|
||||
$this->error('❌ npm install 실패');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
// 빌드 명령 결정
|
||||
$buildCommand = ['npm', 'run'];
|
||||
|
||||
if ($watchMode) {
|
||||
$buildCommand[] = 'dev';
|
||||
$this->info("👀 파일 감시 모드로 빌드 시작: {$identifier}");
|
||||
$this->line(' Ctrl+C로 종료할 수 있습니다.');
|
||||
} else {
|
||||
$buildCommand[] = 'build';
|
||||
$this->info("🔨 빌드 시작: {$identifier}".($productionMode ? ' (프로덕션)' : ''));
|
||||
}
|
||||
|
||||
// 빌드 실행
|
||||
$result = $this->runNpmCommand($buildCommand, $buildPath, ! $watchMode);
|
||||
|
||||
if ($result === Command::SUCCESS && ! $watchMode) {
|
||||
$this->info("✅ 빌드 완료: {$identifier}");
|
||||
|
||||
// 빌드 결과 파일 확인
|
||||
$distPath = $buildPath.'/dist';
|
||||
if (is_dir($distPath)) {
|
||||
$this->line(' 빌드 결과:');
|
||||
|
||||
// JS 파일 확인
|
||||
$jsFiles = glob($distPath.'/*.js');
|
||||
foreach ($jsFiles as $jsFile) {
|
||||
$fileName = basename($jsFile);
|
||||
$fileSize = number_format(filesize($jsFile) / 1024, 2);
|
||||
$this->line(" - {$fileName} ({$fileSize} KB)");
|
||||
}
|
||||
|
||||
// CSS 파일 확인
|
||||
$cssFiles = glob($distPath.'/*.css');
|
||||
foreach ($cssFiles as $cssFile) {
|
||||
$fileName = basename($cssFile);
|
||||
$fileSize = number_format(filesize($cssFile) / 1024, 2);
|
||||
$this->line(" - {$fileName} ({$fileSize} KB)");
|
||||
}
|
||||
}
|
||||
|
||||
// 캐시 버전 증가 (브라우저 캐시 무효화)
|
||||
$this->incrementExtensionCacheVersion();
|
||||
$this->line(' - 캐시 버전 갱신됨');
|
||||
|
||||
// _bundled 빌드 시 활성 반영 안내
|
||||
if ($source === 'bundled') {
|
||||
$this->line('');
|
||||
$this->info("💡 활성 디렉토리에 반영하려면: php artisan template:update {$identifier}");
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 템플릿 빌드
|
||||
*
|
||||
* @param bool $productionMode 프로덕션 빌드
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function buildAllTemplates(bool $productionMode): int
|
||||
{
|
||||
$buildTargets = [];
|
||||
|
||||
if ($this->option('active')) {
|
||||
// --active: 활성 디렉토리만 대상
|
||||
$templates = $this->templateManager->getAllTemplates();
|
||||
foreach ($templates as $identifier => $template) {
|
||||
$templatePath = base_path("templates/{$identifier}");
|
||||
if (file_exists($templatePath.'/package.json')) {
|
||||
$buildTargets[$identifier] = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 기본값: _bundled 디렉토리 스캔
|
||||
$bundledTemplates = $this->templateManager->getBundledTemplates();
|
||||
foreach ($bundledTemplates as $identifier => $metadata) {
|
||||
$bundledPath = $metadata['source_path'];
|
||||
if (file_exists($bundledPath.'/package.json')) {
|
||||
$buildTargets[$identifier] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($buildTargets)) {
|
||||
$this->warn('⚠️ 빌드할 템플릿이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$sourceLabel = $this->option('active') ? '활성' : '_bundled';
|
||||
$this->info("🔨 모든 템플릿 빌드 시작 ({$sourceLabel})".($productionMode ? ' (프로덕션)' : ''));
|
||||
$this->line(' 대상 템플릿: '.implode(', ', array_keys($buildTargets)));
|
||||
$this->line('');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($buildTargets as $identifier => $value) {
|
||||
$this->line(" [{$identifier}]");
|
||||
$result = $this->buildTemplate($identifier, false, $productionMode);
|
||||
|
||||
if ($result === Command::SUCCESS) {
|
||||
$successCount++;
|
||||
} else {
|
||||
$failCount++;
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
}
|
||||
|
||||
$this->info("📊 빌드 결과: 성공 {$successCount}개, 실패 {$failCount}개");
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* npm 명령 실행
|
||||
*
|
||||
* @param array $command 실행할 명령
|
||||
* @param string $cwd 작업 디렉토리
|
||||
* @param bool $waitForCompletion 완료 대기 여부
|
||||
* @return int 명령 실행 결과 코드
|
||||
*/
|
||||
private function runNpmCommand(array $command, string $cwd, bool $waitForCompletion = true): int
|
||||
{
|
||||
// Windows 환경에서는 cmd /c 사용
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
$command = array_merge(['cmd', '/c'], $command);
|
||||
}
|
||||
|
||||
$process = new Process($command);
|
||||
$process->setWorkingDirectory($cwd);
|
||||
$process->setTimeout(null); // 타임아웃 없음
|
||||
|
||||
if ($waitForCompletion) {
|
||||
$process->run(function ($type, $buffer) {
|
||||
$this->output->write($buffer);
|
||||
});
|
||||
|
||||
return $process->isSuccessful() ? Command::SUCCESS : Command::FAILURE;
|
||||
}
|
||||
|
||||
// 감시 모드: 인터럽트까지 실행
|
||||
$process->start(function ($type, $buffer) {
|
||||
$this->output->write($buffer);
|
||||
});
|
||||
|
||||
// 프로세스가 실행 중인 동안 대기
|
||||
while ($process->isRunning()) {
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CheckTemplateUpdatesCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:check-updates {identifier? : 특정 템플릿만 확인 (선택)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿 업데이트를 확인합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager,
|
||||
private TemplateRepositoryInterface $templateRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
if ($identifier) {
|
||||
return $this->checkSingle($identifier);
|
||||
}
|
||||
|
||||
return $this->checkAll();
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 업데이트 확인 실패', [
|
||||
'template' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 템플릿 업데이트를 확인합니다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
*/
|
||||
private function checkSingle(string $identifier): int
|
||||
{
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $template) {
|
||||
$this->error('❌ '.__('templates.commands.check_updates.not_installed', ['template' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$result = $this->templateManager->checkTemplateUpdate($identifier);
|
||||
|
||||
// 단일 체크는 DB 갱신이 안 되므로 커맨드에서 직접 갱신
|
||||
$this->templateRepository->updateByIdentifier($identifier, [
|
||||
'update_available' => $result['update_available'],
|
||||
'latest_version' => $result['latest_version'],
|
||||
'update_source' => $result['update_source'],
|
||||
]);
|
||||
|
||||
if ($result['update_available']) {
|
||||
$this->info('🔄 '.__('templates.commands.check_updates.single_update_available', [
|
||||
'template' => $identifier,
|
||||
'current' => $result['current_version'],
|
||||
'latest' => $result['latest_version'],
|
||||
'source' => $result['update_source'],
|
||||
]));
|
||||
} else {
|
||||
$this->info('✅ '.__('templates.commands.check_updates.single_up_to_date', [
|
||||
'template' => $identifier,
|
||||
'version' => $result['current_version'],
|
||||
]));
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 설치된 템플릿의 업데이트를 확인합니다.
|
||||
*/
|
||||
private function checkAll(): int
|
||||
{
|
||||
$installedTemplates = $this->templateManager->getInstalledTemplatesWithDetails();
|
||||
|
||||
if (empty($installedTemplates)) {
|
||||
$this->info(__('templates.commands.check_updates.no_installed'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// checkAllTemplatesForUpdates는 내부에서 DB 갱신 포함
|
||||
$result = $this->templateManager->checkAllTemplatesForUpdates();
|
||||
|
||||
$tableData = [];
|
||||
$updateCount = 0;
|
||||
|
||||
foreach ($result['details'] as $detail) {
|
||||
$isUpdate = $detail['update_available'] ?? false;
|
||||
if ($isUpdate) {
|
||||
$updateCount++;
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
$detail['identifier'],
|
||||
$detail['current_version'] ?? '-',
|
||||
$detail['latest_version'] ?? '-',
|
||||
$detail['update_source'] ?? '-',
|
||||
$isUpdate
|
||||
? '🔄 '.__('templates.commands.check_updates.update_available')
|
||||
: '✅ '.__('templates.commands.check_updates.up_to_date'),
|
||||
];
|
||||
}
|
||||
|
||||
$headers = [
|
||||
__('templates.commands.check_updates.headers.identifier'),
|
||||
__('templates.commands.check_updates.headers.current_version'),
|
||||
__('templates.commands.check_updates.headers.latest_version'),
|
||||
__('templates.commands.check_updates.headers.source'),
|
||||
__('templates.commands.check_updates.headers.status'),
|
||||
];
|
||||
|
||||
$this->table($headers, $tableData);
|
||||
$this->newLine();
|
||||
$this->info(__('templates.commands.check_updates.summary', [
|
||||
'total' => count($result['details']),
|
||||
'updates' => $updateCount,
|
||||
]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Models\Template;
|
||||
use App\Models\TemplateLayout;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ClearTemplateCacheCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:cache-clear
|
||||
{identifier? : 특정 템플릿의 캐시만 삭제 (생략 시 모든 템플릿)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿 관련 캐시를 삭제합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 템플릿 디렉토리 스캔 및 로드
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
if ($identifier) {
|
||||
// 특정 템플릿 캐시만 삭제
|
||||
$this->clearSingleTemplateCache($identifier);
|
||||
} else {
|
||||
// 모든 템플릿 캐시 삭제
|
||||
$this->clearAllTemplateCache();
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 캐시 삭제 실패', [
|
||||
'identifier' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 캐시 삭제
|
||||
*/
|
||||
private function clearSingleTemplateCache(string $identifier): void
|
||||
{
|
||||
// 템플릿 존재 확인
|
||||
$template = $this->templateManager->getTemplate($identifier);
|
||||
if (! $template) {
|
||||
throw new \Exception(__('templates.errors.not_found', ['template' => $identifier]));
|
||||
}
|
||||
|
||||
$this->info(__('templates.commands.cache_clear.clearing_single', ['template' => $identifier]));
|
||||
|
||||
$clearedCount = 0;
|
||||
|
||||
// 1. 레이아웃 캐시 삭제
|
||||
$templateRecord = Template::where('identifier', $identifier)->first();
|
||||
if ($templateRecord) {
|
||||
$layouts = TemplateLayout::where('template_id', $templateRecord->id)->get();
|
||||
foreach ($layouts as $layout) {
|
||||
Cache::forget("layout.{$identifier}.{$layout->name}");
|
||||
$clearedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Routes 캐시 삭제
|
||||
Cache::forget("template.routes.{$identifier}");
|
||||
$clearedCount++;
|
||||
|
||||
// 3. 다국어 파일 캐시 삭제
|
||||
$supportedLocales = config('app.supported_locales', ['ko', 'en']);
|
||||
foreach ($supportedLocales as $locale) {
|
||||
Cache::forget("template.language.{$identifier}.{$locale}");
|
||||
$clearedCount++;
|
||||
}
|
||||
|
||||
// 4. 활성 템플릿 타입 캐시 삭제
|
||||
if ($templateRecord) {
|
||||
Cache::forget("templates.active.{$templateRecord->type}");
|
||||
$clearedCount++;
|
||||
}
|
||||
|
||||
$this->info('✅ '.__('templates.commands.cache_clear.success_single', [
|
||||
'template' => $identifier,
|
||||
'count' => $clearedCount,
|
||||
]));
|
||||
|
||||
Log::info(__('templates.commands.cache_clear.success_single', [
|
||||
'template' => $identifier,
|
||||
'count' => $clearedCount,
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 템플릿 캐시 삭제
|
||||
*/
|
||||
private function clearAllTemplateCache(): void
|
||||
{
|
||||
$this->info(__('templates.commands.cache_clear.clearing_all'));
|
||||
|
||||
$clearedCount = 0;
|
||||
$supportedLocales = config('app.supported_locales', ['ko', 'en']);
|
||||
|
||||
// 모든 설치된 템플릿의 캐시 삭제
|
||||
$templates = Template::all();
|
||||
|
||||
foreach ($templates as $templateRecord) {
|
||||
// 1. 레이아웃 캐시 삭제
|
||||
$layouts = TemplateLayout::where('template_id', $templateRecord->id)->get();
|
||||
foreach ($layouts as $layout) {
|
||||
Cache::forget("layout.{$templateRecord->identifier}.{$layout->name}");
|
||||
$clearedCount++;
|
||||
}
|
||||
|
||||
// 2. Routes 캐시 삭제
|
||||
Cache::forget("template.routes.{$templateRecord->identifier}");
|
||||
$clearedCount++;
|
||||
|
||||
// 3. 다국어 파일 캐시 삭제
|
||||
foreach ($supportedLocales as $locale) {
|
||||
Cache::forget("template.language.{$templateRecord->identifier}.{$locale}");
|
||||
$clearedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 활성 템플릿 타입 캐시 삭제
|
||||
Cache::forget('templates.active.admin');
|
||||
Cache::forget('templates.active.user');
|
||||
$clearedCount += 2;
|
||||
|
||||
$this->info('✅ '.__('templates.commands.cache_clear.success_all', [
|
||||
'count' => $clearedCount,
|
||||
]));
|
||||
|
||||
Log::info(__('templates.commands.cache_clear.success_all', [
|
||||
'count' => $clearedCount,
|
||||
]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class DeactivateTemplateCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:deactivate {identifier : 템플릿 식별자}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿을 비활성화합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager,
|
||||
private TemplateRepositoryInterface $templateRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 템플릿 디렉토리 스캔 및 로드
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
// 템플릿 존재 확인
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $template) {
|
||||
$this->error('❌ '.__('templates.commands.activate.not_installed', ['template' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 템플릿이 활성화되어 있는지 확인
|
||||
if ($template->status !== 'active') {
|
||||
$this->warn('⚠️ '.__('templates.commands.deactivate.not_active', ['template' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 템플릿 비활성화
|
||||
$result = $this->templateManager->deactivateTemplate($identifier);
|
||||
|
||||
if ($result) {
|
||||
// 성공 메시지
|
||||
$this->info('✅ '.__('templates.commands.deactivate.success', ['template' => $identifier]));
|
||||
|
||||
// 경고 메시지
|
||||
$this->warn('⚠️ '.__('templates.commands.deactivate.no_active_warning', [
|
||||
'type' => __('templates.types.'.$template->type),
|
||||
]));
|
||||
|
||||
Log::info(__('templates.commands.deactivate.success', ['template' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 비활성화 실패', [
|
||||
'template' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\TemplateManager;
|
||||
use App\Rules\ValidExtensionIdentifier;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class InstallTemplateCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:install {identifier : 템플릿 식별자 (디렉토리명)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿을 설치합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager,
|
||||
private TemplateRepositoryInterface $templateRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
// 식별자 형식 검증
|
||||
$validator = Validator::make(
|
||||
['identifier' => $identifier],
|
||||
['identifier' => [new ValidExtensionIdentifier]]
|
||||
);
|
||||
|
||||
if ($validator->fails()) {
|
||||
$this->error('❌ '.$validator->errors()->first('identifier'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
// 템플릿 디렉토리 스캔 및 로드
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
// 템플릿 설치
|
||||
$onProgress = $this->createProgressCallback(TemplateManager::INSTALL_STEPS);
|
||||
try {
|
||||
$result = $this->templateManager->installTemplate($identifier, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
// 설치된 템플릿 정보 조회
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
|
||||
// 성공 메시지
|
||||
$this->info('✅ '.__('templates.commands.install.success', ['template' => $identifier]));
|
||||
$this->info(' - '.__('templates.commands.install.type', ['type' => __('templates.types.'.$template->type)]));
|
||||
$this->info(' - '.__('templates.commands.install.version', ['version' => $template->version]));
|
||||
$this->info(' - '.__('templates.commands.install.layouts_created', ['count' => $template->layouts()->count()]));
|
||||
|
||||
Log::info(__('templates.commands.install.success', ['template' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 설치 실패', [
|
||||
'template' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class ListTemplateCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:list
|
||||
{--type= : 템플릿 타입으로 필터 (admin, user)}
|
||||
{--status= : 상태로 필터 (installed, uninstalled, active, inactive)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '설치된 템플릿 목록을 조회합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager,
|
||||
private TemplateRepositoryInterface $templateRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
// 템플릿 디렉토리 스캔 및 로드
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
$typeFilter = $this->option('type');
|
||||
$statusFilter = $this->option('status');
|
||||
|
||||
// 타입 필터 검증
|
||||
if ($typeFilter && ! in_array($typeFilter, ['admin', 'user'])) {
|
||||
$this->error('❌ '.__('templates.commands.list.invalid_type'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 상태 필터 검증
|
||||
if ($statusFilter && ! in_array($statusFilter, ['installed', 'uninstalled', 'active', 'inactive'])) {
|
||||
$this->error('❌ '.__('templates.commands.list.invalid_status'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 설치된 템플릿 정보
|
||||
$installedTemplates = $this->templateManager->getInstalledTemplatesWithDetails();
|
||||
|
||||
// 미설치 템플릿 정보
|
||||
$uninstalledTemplates = $this->templateManager->getUninstalledTemplates();
|
||||
|
||||
// 테이블 데이터 준비
|
||||
$tableData = [];
|
||||
|
||||
// 설치된 템플릿 추가
|
||||
foreach ($installedTemplates as $identifier => $template) {
|
||||
// 타입 필터
|
||||
if ($typeFilter && $template['type'] !== $typeFilter) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 상태 필터
|
||||
if ($statusFilter) {
|
||||
if ($statusFilter === 'uninstalled') {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'active' && $template['status'] !== 'active') {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'inactive' && $template['status'] !== 'inactive') {
|
||||
continue;
|
||||
}
|
||||
if ($statusFilter === 'installed' && ! in_array($template['status'], ['active', 'inactive'])) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
'identifier' => $identifier,
|
||||
'name' => $template['name'],
|
||||
'type' => __('templates.types.'.$template['type']),
|
||||
'version' => $template['version'],
|
||||
'status' => $this->formatStatus($template['status']),
|
||||
];
|
||||
}
|
||||
|
||||
// 미설치 템플릿 추가
|
||||
if (! $statusFilter || $statusFilter === 'uninstalled') {
|
||||
foreach ($uninstalledTemplates as $identifier => $template) {
|
||||
// 타입 필터
|
||||
if ($typeFilter && $template['type'] !== $typeFilter) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 상태 필터 (uninstalled 또는 필터 없음)
|
||||
if ($statusFilter && $statusFilter !== 'uninstalled') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tableData[] = [
|
||||
'identifier' => $identifier,
|
||||
'name' => $template['name'],
|
||||
'type' => __('templates.types.'.$template['type']),
|
||||
'version' => $template['version'],
|
||||
'status' => $this->formatStatus('uninstalled'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 템플릿이 없는 경우
|
||||
if (empty($tableData)) {
|
||||
$this->info(__('templates.commands.list.no_templates'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 테이블 헤더
|
||||
$headers = [
|
||||
__('templates.commands.list.headers.identifier'),
|
||||
__('templates.commands.list.headers.name'),
|
||||
__('templates.commands.list.headers.type'),
|
||||
__('templates.commands.list.headers.version'),
|
||||
__('templates.commands.list.headers.status'),
|
||||
];
|
||||
|
||||
// 테이블 출력
|
||||
$this->table($headers, $tableData);
|
||||
|
||||
// 요약 정보
|
||||
$totalCount = count($tableData);
|
||||
$activeCount = count(array_filter($tableData, fn ($t) => str_contains($t['status'], __('templates.status.active'))));
|
||||
$installedCount = count(array_filter($tableData, fn ($t) => ! str_contains($t['status'], __('templates.commands.list.status.uninstalled'))));
|
||||
|
||||
$this->newLine();
|
||||
$this->info(__('templates.commands.list.summary', [
|
||||
'total' => $totalCount,
|
||||
'installed' => $installedCount,
|
||||
'active' => $activeCount,
|
||||
]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상태 포맷팅
|
||||
*/
|
||||
private function formatStatus(string $status): string
|
||||
{
|
||||
return match ($status) {
|
||||
'active' => '✅ '.__('templates.status.active'),
|
||||
'inactive' => '⏸️ '.__('templates.status.inactive'),
|
||||
'uninstalled' => '📦 '.__('templates.commands.list.status.uninstalled'),
|
||||
default => $status,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Models\Template;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 템플릿 레이아웃 갱신 커맨드
|
||||
*
|
||||
* 레이아웃 JSON 파일만 수정된 경우, 빌드 없이 레이아웃만 갱신합니다.
|
||||
*/
|
||||
class RefreshTemplateLayoutCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:refresh-layout
|
||||
{identifier? : 특정 템플릿의 식별자 (생략 시 모든 활성 템플릿)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿 레이아웃을 갱신합니다 (빌드 없이 JSON만 DB에 동기화)';
|
||||
|
||||
public function __construct(
|
||||
private TemplateService $templateService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
if ($identifier) {
|
||||
return $this->refreshSingle($identifier);
|
||||
}
|
||||
|
||||
return $this->refreshAll();
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 레이아웃 갱신 실패', [
|
||||
'template' => $identifier ?? 'all',
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 레이아웃을 갱신합니다.
|
||||
*/
|
||||
private function refreshSingle(string $identifier): int
|
||||
{
|
||||
$this->info("템플릿 '{$identifier}' 레이아웃 갱신 중...");
|
||||
|
||||
$result = $this->templateService->refreshTemplateLayouts($identifier);
|
||||
|
||||
if ($result) {
|
||||
$this->info("✅ 템플릿 '{$identifier}' 레이아웃 갱신 완료");
|
||||
Log::info('템플릿 레이아웃 갱신 완료', ['template' => $identifier]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->error("❌ 템플릿 '{$identifier}' 레이아웃 갱신 실패");
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 활성 템플릿의 레이아웃을 갱신합니다.
|
||||
*/
|
||||
private function refreshAll(): int
|
||||
{
|
||||
$templates = Template::where('status', 'active')->pluck('identifier')->toArray();
|
||||
|
||||
if (empty($templates)) {
|
||||
$this->line('활성화된 템플릿이 없습니다.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info('모든 활성 템플릿 레이아웃 갱신 중...');
|
||||
|
||||
$successCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
foreach ($templates as $templateIdentifier) {
|
||||
$this->line(" {$templateIdentifier} 갱신 중...");
|
||||
|
||||
try {
|
||||
$result = $this->templateService->refreshTemplateLayouts($templateIdentifier);
|
||||
|
||||
if ($result) {
|
||||
$this->info(" ✅ {$templateIdentifier} 완료");
|
||||
$successCount++;
|
||||
} else {
|
||||
$this->warn(" ⚠️ {$templateIdentifier} 실패");
|
||||
$failCount++;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
$this->warn(" ⚠️ {$templateIdentifier}: ".$e->getMessage());
|
||||
$failCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info("✅ 총 {$successCount}개 성공, {$failCount}개 실패");
|
||||
|
||||
Log::info('템플릿 레이아웃 일괄 갱신 완료', [
|
||||
'success' => $successCount,
|
||||
'failed' => $failCount,
|
||||
]);
|
||||
|
||||
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class UninstallTemplateCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:uninstall {identifier : 템플릿 식별자}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿을 삭제합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager,
|
||||
private TemplateRepositoryInterface $templateRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
|
||||
try {
|
||||
// 템플릿 디렉토리 스캔 및 로드
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
// 템플릿 존재 확인
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $template) {
|
||||
$this->error('❌ '.__('templates.commands.activate.not_installed', ['template' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 삭제 확인 프롬프트
|
||||
$this->warn(__('templates.commands.uninstall.confirm_prompt', ['template' => $identifier]));
|
||||
$this->warn(__('templates.commands.uninstall.confirm_details.layouts', ['count' => $template->layouts()->count()]));
|
||||
$this->warn(__('templates.commands.uninstall.confirm_details.versions'));
|
||||
|
||||
if (! $this->confirm(__('templates.commands.uninstall.confirm_question'), false)) {
|
||||
$this->info(__('templates.commands.uninstall.aborted'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 레이아웃 및 버전 개수 조회
|
||||
$layoutsCount = $template->layouts()->count();
|
||||
|
||||
// 템플릿 삭제
|
||||
$onProgress = $this->createProgressCallback(TemplateManager::UNINSTALL_STEPS);
|
||||
try {
|
||||
$result = $this->templateManager->uninstallTemplate($identifier, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
// 성공 메시지
|
||||
$this->info('✅ '.__('templates.commands.uninstall.success', ['template' => $identifier]));
|
||||
$this->info(' - '.__('templates.commands.uninstall.layouts_deleted', ['count' => $layoutsCount]));
|
||||
|
||||
Log::info(__('templates.commands.uninstall.success', ['template' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
Log::error('템플릿 삭제 실패', [
|
||||
'template' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Template;
|
||||
|
||||
use App\Console\Commands\Traits\HasProgressBar;
|
||||
use App\Contracts\Repositories\TemplateRepositoryInterface;
|
||||
use App\Extension\TemplateManager;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class UpdateTemplateCommand extends Command
|
||||
{
|
||||
use HasProgressBar;
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*/
|
||||
protected $signature = 'template:update
|
||||
{identifier : 업데이트할 템플릿 식별자}
|
||||
{--layout-strategy=overwrite : 레이아웃 전략 (overwrite|keep)}
|
||||
{--force : 버전 비교 없이 강제 업데이트}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*/
|
||||
protected $description = '템플릿을 최신 버전으로 업데이트합니다';
|
||||
|
||||
/**
|
||||
* 템플릿 관리자 및 리포지토리
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateManager $templateManager,
|
||||
private TemplateRepositoryInterface $templateRepository
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$identifier = $this->argument('identifier');
|
||||
$layoutStrategy = $this->option('layout-strategy');
|
||||
$force = $this->option('force');
|
||||
|
||||
// 레이아웃 전략 검증
|
||||
if (! in_array($layoutStrategy, ['overwrite', 'keep'])) {
|
||||
$this->error('❌ '.__('templates.commands.update.invalid_strategy'));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->templateManager->loadTemplates();
|
||||
|
||||
// 템플릿 존재 확인
|
||||
$template = $this->templateRepository->findByIdentifier($identifier);
|
||||
|
||||
if (! $template) {
|
||||
$this->error('❌ '.__('templates.commands.update.not_installed', ['template' => $identifier]));
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// 업데이트 확인
|
||||
$checkResult = $this->templateManager->checkTemplateUpdate($identifier);
|
||||
|
||||
if (! $checkResult['update_available'] && ! $force) {
|
||||
$this->info('✅ '.__('templates.commands.update.no_update', ['template' => $identifier]));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 업데이트 정보 표시
|
||||
$this->info(__('templates.commands.update.current_version', ['version' => $checkResult['current_version']]));
|
||||
|
||||
if ($force && ! $checkResult['update_available']) {
|
||||
$this->warn('⚠️ '.__('templates.commands.update.force_mode'));
|
||||
} else {
|
||||
$this->info(__('templates.commands.update.latest_version', ['version' => $checkResult['latest_version']]));
|
||||
$this->info(__('templates.commands.update.update_source', ['source' => $checkResult['update_source']]));
|
||||
}
|
||||
|
||||
$this->info(__('templates.commands.update.layout_strategy', ['strategy' => $layoutStrategy]));
|
||||
|
||||
// overwrite 전략일 때 수정된 레이아웃 경고
|
||||
if ($layoutStrategy === 'overwrite') {
|
||||
$modifiedResult = $this->templateManager->hasModifiedLayouts($identifier);
|
||||
|
||||
if ($modifiedResult['has_modified_layouts']) {
|
||||
$this->newLine();
|
||||
$this->warn('⚠️ '.__('templates.commands.update.modified_layouts_warning', [
|
||||
'count' => $modifiedResult['modified_count'],
|
||||
]));
|
||||
|
||||
foreach ($modifiedResult['modified_layouts'] as $layout) {
|
||||
$this->warn(__('templates.commands.update.modified_layout_item', [
|
||||
'name' => $layout['name'],
|
||||
'date' => $layout['updated_at'],
|
||||
]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
|
||||
// 확인 프롬프트 (--force 시 건너뜀)
|
||||
if (! $force && ! $this->confirm(__('templates.commands.update.confirm_question'), false)) {
|
||||
$this->info(__('templates.commands.update.aborted'));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 업데이트 실행
|
||||
$onProgress = $this->createProgressCallback(TemplateManager::UPDATE_STEPS);
|
||||
try {
|
||||
$updateResult = $this->templateManager->updateTemplate($identifier, $layoutStrategy, $force, $onProgress);
|
||||
$this->finishProgress();
|
||||
} catch (\Exception $e) {
|
||||
$this->finishProgress();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($updateResult['success']) {
|
||||
$this->newLine();
|
||||
$this->info('✅ '.__('templates.commands.update.success', ['template' => $identifier]));
|
||||
$this->info(' '.__('templates.commands.update.version_change', [
|
||||
'from' => $updateResult['from_version'],
|
||||
'to' => $updateResult['to_version'],
|
||||
]));
|
||||
|
||||
Log::info('템플릿 업데이트 완료', [
|
||||
'template' => $identifier,
|
||||
'from' => $updateResult['from_version'],
|
||||
'to' => $updateResult['to_version'],
|
||||
]);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
} catch (\Exception $e) {
|
||||
$this->error('❌ '.$e->getMessage());
|
||||
$this->warn('💡 '.__('templates.commands.update.backup_restored'));
|
||||
|
||||
Log::error('템플릿 업데이트 실패', [
|
||||
'template' => $identifier,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Traits;
|
||||
|
||||
use Symfony\Component\Console\Helper\ProgressBar;
|
||||
|
||||
/**
|
||||
* 확장 커맨드용 프로그레스바 트레이트.
|
||||
*
|
||||
* 2단계 Closure 콜백 패턴으로 동작:
|
||||
* 1. 단계 전환 ($step 지정): bar advance + 메시지 갱신
|
||||
* 2. 상세 표시 ($step = null): 파일명 전광판 표시
|
||||
*/
|
||||
trait HasProgressBar
|
||||
{
|
||||
protected ?ProgressBar $progressBar = null;
|
||||
|
||||
/**
|
||||
* 프로그레스 콜백을 생성합니다.
|
||||
*
|
||||
* @param int $steps 총 단계 수
|
||||
* @return \Closure 콜백 (?string $step, string $message)
|
||||
*/
|
||||
protected function createProgressCallback(int $steps): \Closure
|
||||
{
|
||||
$this->progressBar = $this->output->createProgressBar($steps);
|
||||
$this->progressBar->setFormat(" %current%/%max% [%bar%] %message%\n %detail%");
|
||||
$this->progressBar->setMessage('시작 중...');
|
||||
$this->progressBar->setMessage('', 'detail');
|
||||
$this->progressBar->start();
|
||||
|
||||
return function (?string $step, string $message): void {
|
||||
if ($step !== null) {
|
||||
// 단계 전환: bar advance + 상세 초기화
|
||||
$this->progressBar->setMessage($message);
|
||||
$this->progressBar->setMessage('', 'detail');
|
||||
$this->progressBar->advance();
|
||||
} else {
|
||||
// 상세 갱신: 현재 파일명 전광판 표시
|
||||
$this->progressBar->setMessage("\u{2192} ".$message, 'detail');
|
||||
$this->progressBar->display();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로그레스바를 완료합니다.
|
||||
*/
|
||||
protected function finishProgress(): void
|
||||
{
|
||||
if ($this->progressBar) {
|
||||
$this->progressBar->setMessage('', 'detail');
|
||||
$this->progressBar->finish();
|
||||
$this->newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface HookListenerInterface
|
||||
{
|
||||
/**
|
||||
* 구독할 훅과 메서드 매핑을 반환합니다.
|
||||
*
|
||||
* @return array [
|
||||
* 'hook.name' => [
|
||||
* 'method' => 'methodName',
|
||||
* 'priority' => 10
|
||||
* ]
|
||||
* ]
|
||||
*/
|
||||
public static function getSubscribedHooks(): array;
|
||||
|
||||
/**
|
||||
* 훅 이벤트를 처리합니다.
|
||||
*
|
||||
* @param mixed ...$args 훅에서 전달된 인수들
|
||||
* @return void
|
||||
*/
|
||||
public function handle(...$args): void;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface HookManagerInterface
|
||||
{
|
||||
/**
|
||||
* Hook 이벤트를 발생시켜 등록된 콜백들을 실행합니다.
|
||||
*
|
||||
* @param string $hookName Hook 이름
|
||||
* @param mixed ...$args Hook에 전달할 인수들
|
||||
* @return void
|
||||
*/
|
||||
public static function doAction(string $hookName, ...$args): void;
|
||||
|
||||
/**
|
||||
* Filter를 적용하여 데이터를 변환합니다.
|
||||
*
|
||||
* @param string $filterName Filter 이름
|
||||
* @param mixed $value 변환할 원본 값
|
||||
* @param mixed ...$args Filter에 전달할 추가 인수들
|
||||
* @return mixed 변환된 값
|
||||
*/
|
||||
public static function applyFilters(string $filterName, $value, ...$args);
|
||||
|
||||
/**
|
||||
* Hook 이벤트에 콜백 함수를 등록합니다.
|
||||
*
|
||||
* @param string $hookName Hook 이름
|
||||
* @param callable $callback 실행할 콜백 함수
|
||||
* @param int $priority 실행 우선순위 (기본값: 10)
|
||||
* @return void
|
||||
*/
|
||||
public static function addAction(string $hookName, callable $callback, int $priority = 10): void;
|
||||
|
||||
/**
|
||||
* Filter에 콜백 함수를 등록합니다.
|
||||
*
|
||||
* @param string $filterName Filter 이름
|
||||
* @param callable $callback 실행할 콜백 함수
|
||||
* @param int $priority 실행 우선순위 (기본값: 10)
|
||||
* @return void
|
||||
*/
|
||||
public static function addFilter(string $filterName, callable $callback, int $priority = 10): void;
|
||||
|
||||
/**
|
||||
* Hook 이벤트에서 콜백 함수를 제거합니다.
|
||||
*
|
||||
* @param string $hookName Hook 이름
|
||||
* @param callable $callback 제거할 콜백 함수
|
||||
* @return void
|
||||
*/
|
||||
public static function removeAction(string $hookName, callable $callback): void;
|
||||
|
||||
/**
|
||||
* Filter에서 콜백 함수를 제거합니다.
|
||||
*
|
||||
* @param string $filterName Filter 이름
|
||||
* @param callable $callback 제거할 콜백 함수
|
||||
* @return void
|
||||
*/
|
||||
public static function removeFilter(string $filterName, callable $callback): void;
|
||||
|
||||
/**
|
||||
* 등록된 모든 Hook 목록을 조회합니다.
|
||||
*
|
||||
* @return array Hook 목록 배열
|
||||
*/
|
||||
public static function getHooks(): array;
|
||||
|
||||
/**
|
||||
* 등록된 모든 Filter 목록을 조회합니다.
|
||||
*
|
||||
* @return array Filter 목록 배열
|
||||
*/
|
||||
public static function getFilters(): array;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface ModuleInterface
|
||||
{
|
||||
/**
|
||||
* 모듈명 반환 (표시용)
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getName(): string|array;
|
||||
|
||||
/**
|
||||
* 모듈의 버전을 반환합니다.
|
||||
*
|
||||
* @return string 모듈 버전
|
||||
*/
|
||||
public function getVersion(): string;
|
||||
|
||||
/**
|
||||
* 모듈 설명 반환
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getDescription(): string|array;
|
||||
|
||||
/**
|
||||
* 모듈을 설치합니다.
|
||||
*
|
||||
* @return bool 설치 성공 여부
|
||||
*/
|
||||
public function install(): bool;
|
||||
|
||||
/**
|
||||
* 모듈을 제거합니다.
|
||||
*
|
||||
* @return bool 제거 성공 여부
|
||||
*/
|
||||
public function uninstall(): bool;
|
||||
|
||||
/**
|
||||
* 모듈이 런타임에 동적으로 생성한 테이블 목록을 반환합니다.
|
||||
*
|
||||
* 모듈 언인스톨 시 $deleteData=true이면 마이그레이션 롤백 전에 호출됩니다.
|
||||
* 반환된 테이블들은 ModuleManager가 일괄 삭제합니다.
|
||||
*
|
||||
* 주의:
|
||||
* - 마이그레이션 롤백 전에 호출되므로 메타 테이블(정적 테이블)이 아직 존재합니다.
|
||||
* - 개별 테이블 삭제 실패 시에도 언인스톨은 계속 진행됩니다.
|
||||
*
|
||||
* @return array<string> 삭제할 테이블명 배열
|
||||
*/
|
||||
public function getDynamicTables(): array;
|
||||
|
||||
/**
|
||||
* 모듈을 활성화합니다.
|
||||
*
|
||||
* @return bool 활성화 성공 여부
|
||||
*/
|
||||
public function activate(): bool;
|
||||
|
||||
/**
|
||||
* 모듈을 비활성화합니다.
|
||||
*
|
||||
* @return bool 비활성화 성공 여부
|
||||
*/
|
||||
public function deactivate(): bool;
|
||||
|
||||
/**
|
||||
* 버전별 업그레이드 스텝을 반환합니다.
|
||||
*
|
||||
* 반환 형식: ['1.1.0' => callable|UpgradeStepInterface, ...]
|
||||
* 시스템이 fromVersion 초과 ~ toVersion 이하의 스텝을 자동 필터링 후 순차 실행합니다.
|
||||
*
|
||||
* @return array<string, callable|\App\Contracts\Extension\UpgradeStepInterface> 버전 => 스텝 매핑
|
||||
*/
|
||||
public function upgrades(): array;
|
||||
|
||||
/**
|
||||
* 모듈이 제공하는 라우트 정보를 반환합니다.
|
||||
*
|
||||
* @return array 라우트 정보 배열
|
||||
*/
|
||||
public function getRoutes(): array;
|
||||
|
||||
/**
|
||||
* 모듈의 마이그레이션 파일 목록을 반환합니다.
|
||||
*
|
||||
* @return array 마이그레이션 파일 경로 배열
|
||||
*/
|
||||
public function getMigrations(): array;
|
||||
|
||||
/**
|
||||
* 모듈의 뷰 파일 목록을 반환합니다.
|
||||
*
|
||||
* @return array 뷰 파일 경로 배열
|
||||
*/
|
||||
public function getViews(): array;
|
||||
|
||||
/**
|
||||
* 모듈의 의존성 정보를 반환합니다.
|
||||
*
|
||||
* @return array 의존성 목록 배열
|
||||
*/
|
||||
public function getDependencies(): array;
|
||||
|
||||
/**
|
||||
* 모듈이 사용하는 권한 목록을 반환합니다.
|
||||
*
|
||||
* @return array 권한 목록 배열
|
||||
*/
|
||||
public function getPermissions(): array;
|
||||
|
||||
/**
|
||||
* 모듈이 정의하는 역할 목록을 반환합니다.
|
||||
*
|
||||
* 역할 배열의 각 항목은 다음 구조를 따라야 합니다:
|
||||
* - identifier: 역할 고유 식별자 (vendor-module.rolename 형식)
|
||||
* - name: 다국어 배열 ['ko' => '역할명', 'en' => 'Role Name']
|
||||
* - description: 다국어 배열 ['ko' => '설명', 'en' => 'Description']
|
||||
*
|
||||
* @return array 역할 정보 배열
|
||||
*/
|
||||
public function getRoles(): array;
|
||||
|
||||
/**
|
||||
* 모듈의 설정 정보를 반환합니다.
|
||||
*
|
||||
* @return array 설정 정보 배열
|
||||
*/
|
||||
public function getConfig(): array;
|
||||
|
||||
/**
|
||||
* 모듈이 추가하는 관리자 메뉴 목록을 반환합니다.
|
||||
*
|
||||
* 메뉴 배열의 각 항목은 다음 구조를 따라야 합니다:
|
||||
* - name: 다국어 배열 ['ko' => '메뉴명', 'en' => 'Menu Name'] 또는 문자열 (역호환성)
|
||||
* - slug: 메뉴 고유 식별자 (string)
|
||||
* - url: 메뉴 URL (string)
|
||||
* - icon: 아이콘 클래스 (string, optional)
|
||||
* - order: 메뉴 순서 (int, optional)
|
||||
* - children: 하위 메뉴 배열 (array, optional) - 동일한 구조를 따름
|
||||
*
|
||||
* @return array 메뉴 정보 배열
|
||||
*/
|
||||
public function getAdminMenus(): array;
|
||||
|
||||
/**
|
||||
* 모듈의 훅 리스너 목록을 반환합니다.
|
||||
*
|
||||
* @return array 훅 리스너 클래스 목록 배열
|
||||
*/
|
||||
public function getHookListeners(): array;
|
||||
|
||||
/**
|
||||
* 모듈의 스케줄 작업 목록을 반환합니다.
|
||||
*
|
||||
* 스케줄 배열의 각 항목은 다음 구조를 따라야 합니다:
|
||||
* - command: Artisan 커맨드 이름
|
||||
* - schedule: 스케줄 주기 ('daily', 'hourly', 'everyMinute', 'weekly' 또는 cron 표현식)
|
||||
* - description: 작업 설명 (선택)
|
||||
* - enabled_config: 설정 키 (선택, 설정에 따라 활성화 여부 결정)
|
||||
*
|
||||
* @return array 스케줄 작업 배열
|
||||
*/
|
||||
public function getSchedules(): array;
|
||||
|
||||
/**
|
||||
* 모듈 설치 시 실행할 시더 클래스 목록을 반환합니다.
|
||||
*
|
||||
* 배열 순서대로 실행됩니다.
|
||||
* 빈 배열 반환 시 database/seeders/ 디렉토리의 모든 시더를 자동 검색합니다. (역호환)
|
||||
*
|
||||
* @return array<class-string<\Illuminate\Database\Seeder>> 시더 클래스명 배열 (FQCN)
|
||||
*/
|
||||
public function getSeeders(): array;
|
||||
|
||||
/**
|
||||
* 모듈의 고유 식별자를 반환합니다 (vendor-module 형식).
|
||||
*
|
||||
* @return string 모듈 식별자
|
||||
*/
|
||||
public function getIdentifier(): string;
|
||||
|
||||
/**
|
||||
* 모듈의 벤더명을 반환합니다.
|
||||
*
|
||||
* @return string 벤더명
|
||||
*/
|
||||
public function getVendor(): string;
|
||||
|
||||
/**
|
||||
* 모듈의 GitHub 저장소 URL을 반환합니다.
|
||||
*
|
||||
* @return string|null GitHub URL 또는 null
|
||||
*/
|
||||
public function getGithubUrl(): ?string;
|
||||
|
||||
/**
|
||||
* 모듈의 라이선스를 반환합니다.
|
||||
*
|
||||
* @return string|null 라이선스 또는 null
|
||||
*/
|
||||
public function getLicense(): ?string;
|
||||
|
||||
/**
|
||||
* 모듈의 메타데이터를 반환합니다.
|
||||
*
|
||||
* @return array 메타데이터 배열
|
||||
*/
|
||||
public function getMetadata(): array;
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 경로를 반환합니다.
|
||||
*
|
||||
* @return string extensions 디렉토리 경로
|
||||
*/
|
||||
public function getExtensionsPath(): string;
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 목록을 반환합니다.
|
||||
*
|
||||
* resources/extensions 디렉토리에서 JSON 파일을 검색합니다.
|
||||
*
|
||||
* @return array<string> JSON 파일 경로 목록
|
||||
*/
|
||||
public function getLayoutExtensions(): array;
|
||||
|
||||
/**
|
||||
* 그누보드7 코어 요구 버전 제약을 반환합니다.
|
||||
*
|
||||
* Semantic Versioning 제약 문자열 반환 (예: ">=1.0.0", "^1.0", "~1.2.0")
|
||||
* null 반환 시 버전 검증을 건너뜁니다 (역호환성 보장).
|
||||
*
|
||||
* @return string|null 버전 제약 문자열 또는 null
|
||||
*/
|
||||
public function getRequiredCoreVersion(): ?string;
|
||||
|
||||
/**
|
||||
* 모듈 설정 기본값 파일(defaults.json) 경로를 반환합니다.
|
||||
*
|
||||
* @return string|null defaults.json 파일의 절대 경로, 없으면 null
|
||||
*/
|
||||
public function getSettingsDefaultsPath(): ?string;
|
||||
|
||||
/**
|
||||
* 모듈에 환경설정이 있는지 확인합니다.
|
||||
*
|
||||
* @return bool 환경설정 존재 여부
|
||||
*/
|
||||
public function hasSettings(): bool;
|
||||
|
||||
/**
|
||||
* 모듈 설정 기본값을 반환합니다.
|
||||
*
|
||||
* @return array 설정 기본값 배열
|
||||
*/
|
||||
public function getConfigValues(): array;
|
||||
|
||||
/**
|
||||
* 모듈 설정 스키마를 반환합니다.
|
||||
*
|
||||
* 민감한 필드(sensitive: true) 정보 등을 포함합니다.
|
||||
*
|
||||
* @return array 설정 스키마 배열
|
||||
*/
|
||||
public function getSettingsSchema(): array;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface ModuleManagerInterface
|
||||
{
|
||||
/**
|
||||
* 모든 모듈을 로드하고 초기화합니다.
|
||||
*/
|
||||
public function loadModules(): void;
|
||||
|
||||
/**
|
||||
* 활성화된 모듈들만 반환합니다.
|
||||
*
|
||||
* @return array 활성화된 모듈 배열
|
||||
*/
|
||||
public function getActiveModules(): array;
|
||||
|
||||
/**
|
||||
* 지정된 모듈을 시스템에 설치합니다.
|
||||
*
|
||||
* @param string $moduleName 설치할 모듈명
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return bool 설치 성공 여부
|
||||
*
|
||||
* @throws \Exception 모듈을 찾을 수 없거나 의존성 문제 시
|
||||
*/
|
||||
public function installModule(string $moduleName, ?\Closure $onProgress = null): bool;
|
||||
|
||||
/**
|
||||
* 지정된 모듈을 활성화합니다.
|
||||
*
|
||||
* @param string $moduleName 활성화할 모듈명
|
||||
* @return array{success: bool, layouts_registered: int} 활성화 결과 및 등록된 레이아웃 개수
|
||||
*/
|
||||
public function activateModule(string $moduleName): array;
|
||||
|
||||
/**
|
||||
* 지정된 모듈을 비활성화합니다.
|
||||
*
|
||||
* @param string $moduleName 비활성화할 모듈명
|
||||
* @param bool $force 의존 템플릿이 있어도 강제 비활성화 여부
|
||||
* @return array{success: bool, layouts_deleted: int, warning?: bool, dependent_templates?: array, message?: string} 비활성화 결과 및 삭제된 레이아웃 개수
|
||||
*/
|
||||
public function deactivateModule(string $moduleName, bool $force = false): array;
|
||||
|
||||
/**
|
||||
* 지정된 모듈을 시스템에서 제거합니다.
|
||||
*
|
||||
* @param string $moduleName 제거할 모듈명
|
||||
* @param bool $deleteData 모듈 데이터(테이블) 삭제 여부
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return bool 제거 성공 여부
|
||||
*
|
||||
* @throws \Exception 모듈을 찾을 수 없을 때
|
||||
*/
|
||||
public function uninstallModule(string $moduleName, bool $deleteData = false, ?\Closure $onProgress = null): bool;
|
||||
|
||||
/**
|
||||
* 지정된 이름의 모듈 인스턴스를 반환합니다.
|
||||
*
|
||||
* @param string $moduleName 모듈명
|
||||
* @return ModuleInterface|null 모듈 인스턴스 또는 null
|
||||
*/
|
||||
public function getModule(string $moduleName): ?ModuleInterface;
|
||||
|
||||
/**
|
||||
* 로드된 모든 모듈 인스턴스들을 반환합니다.
|
||||
*
|
||||
* @return array 모든 모듈 배열
|
||||
*/
|
||||
public function getAllModules(): array;
|
||||
|
||||
/**
|
||||
* 설치되지 않은 모듈들을 반환합니다.
|
||||
*
|
||||
* @return array 미설치 모듈 배열
|
||||
*/
|
||||
public function getUninstalledModules(): array;
|
||||
|
||||
/**
|
||||
* 설치된 모듈 정보를 데이터베이스 레코드와 함께 반환합니다.
|
||||
*
|
||||
* @return array 설치된 모듈 배열
|
||||
*/
|
||||
public function getInstalledModulesWithDetails(): array;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 정보를 반환합니다 (설치 여부와 관계없이).
|
||||
*
|
||||
* @param string $moduleName 모듈명
|
||||
* @return array|null 모듈 정보 배열 또는 null
|
||||
*/
|
||||
public function getModuleInfo(string $moduleName): ?array;
|
||||
|
||||
/**
|
||||
* 모듈의 레이아웃을 파일에서 다시 읽어 DB에 갱신합니다.
|
||||
*
|
||||
* @param string $moduleName 모듈명
|
||||
* @return array{success: bool, layouts_refreshed: int} 갱신 결과 및 갱신된 레이아웃 개수
|
||||
*
|
||||
* @throws \Exception 모듈을 찾을 수 없거나 레이아웃 갱신 실패 시
|
||||
*/
|
||||
public function refreshModuleLayouts(string $moduleName): array;
|
||||
|
||||
/**
|
||||
* 모듈 삭제 시 삭제될 데이터 정보를 반환합니다.
|
||||
*
|
||||
* @param string $moduleName 모듈명
|
||||
* @return array|null 삭제 정보 (테이블 목록, 스토리지 디렉토리 목록, 용량) 또는 null
|
||||
*/
|
||||
public function getModuleUninstallInfo(string $moduleName): ?array;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
/**
|
||||
* 모듈 환경설정 인터페이스
|
||||
*
|
||||
* 모듈별 환경설정 시스템을 구현하기 위한 계약입니다.
|
||||
* 환경설정이 필요한 모듈은 이 인터페이스를 구현해야 합니다.
|
||||
*/
|
||||
interface ModuleSettingsInterface
|
||||
{
|
||||
/**
|
||||
* 모듈 설정 기본값 파일 경로 반환
|
||||
*
|
||||
* @return string|null defaults.json 파일의 절대 경로, 없으면 null
|
||||
*/
|
||||
public function getSettingsDefaultsPath(): ?string;
|
||||
|
||||
/**
|
||||
* 설정값 조회
|
||||
*
|
||||
* @param string $key 설정 키 (예: 'category.field' 또는 'field')
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값
|
||||
*/
|
||||
public function getSetting(string $key, mixed $default = null): mixed;
|
||||
|
||||
/**
|
||||
* 설정값 저장
|
||||
*
|
||||
* @param string $key 설정 키
|
||||
* @param mixed $value 저장할 값
|
||||
* @return bool 성공 여부
|
||||
*/
|
||||
public function setSetting(string $key, mixed $value): bool;
|
||||
|
||||
/**
|
||||
* 전체 설정 조회
|
||||
*
|
||||
* @return array 모든 카테고리의 설정값
|
||||
*/
|
||||
public function getAllSettings(): array;
|
||||
|
||||
/**
|
||||
* 카테고리별 설정 조회
|
||||
*
|
||||
* @param string $category 카테고리명
|
||||
* @return array 카테고리의 설정값
|
||||
*/
|
||||
public function getSettings(string $category): array;
|
||||
|
||||
/**
|
||||
* 설정 저장
|
||||
*
|
||||
* @param array $settings 저장할 설정 배열
|
||||
* @return bool 성공 여부
|
||||
*/
|
||||
public function saveSettings(array $settings): bool;
|
||||
|
||||
/**
|
||||
* 프론트엔드용 설정 조회 (민감정보 제외)
|
||||
*
|
||||
* frontend_schema에 따라 민감하지 않은 설정만 반환합니다.
|
||||
*
|
||||
* @return array 프론트엔드에 노출 가능한 설정값
|
||||
*/
|
||||
public function getFrontendSettings(): array;
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface PluginInterface
|
||||
{
|
||||
/**
|
||||
* 플러그인의 고유 식별자를 반환합니다 (vendor-plugin 형식).
|
||||
*/
|
||||
public function getIdentifier(): string;
|
||||
|
||||
/**
|
||||
* 플러그인의 벤더/개발자명을 반환합니다.
|
||||
*/
|
||||
public function getVendor(): string;
|
||||
|
||||
/**
|
||||
* 플러그인의 이름을 반환합니다.
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getName(): string|array;
|
||||
|
||||
/**
|
||||
* 플러그인의 버전을 반환합니다.
|
||||
*
|
||||
* @return string 플러그인 버전
|
||||
*/
|
||||
public function getVersion(): string;
|
||||
|
||||
/**
|
||||
* 플러그인의 설명을 반환합니다.
|
||||
*
|
||||
* @return string|array 문자열 또는 다국어 배열 ['ko' => '...', 'en' => '...']
|
||||
*/
|
||||
public function getDescription(): string|array;
|
||||
|
||||
/**
|
||||
* 플러그인의 GitHub 저장소 URL을 반환합니다.
|
||||
*/
|
||||
public function getGithubUrl(): ?string;
|
||||
|
||||
/**
|
||||
* 플러그인의 라이선스를 반환합니다.
|
||||
*
|
||||
* @return string|null 라이선스 또는 null
|
||||
*/
|
||||
public function getLicense(): ?string;
|
||||
|
||||
/**
|
||||
* 플러그인의 추가 메타데이터를 반환합니다.
|
||||
*
|
||||
* @return array 메타데이터 배열
|
||||
*/
|
||||
public function getMetadata(): array;
|
||||
|
||||
/**
|
||||
* 플러그인을 설치합니다.
|
||||
*
|
||||
* @return bool 설치 성공 여부
|
||||
*/
|
||||
public function install(): bool;
|
||||
|
||||
/**
|
||||
* 플러그인을 제거합니다.
|
||||
*
|
||||
* @return bool 제거 성공 여부
|
||||
*/
|
||||
public function uninstall(): bool;
|
||||
|
||||
/**
|
||||
* 플러그인이 런타임에 동적으로 생성한 테이블 목록을 반환합니다.
|
||||
*
|
||||
* 플러그인 언인스톨 시 $deleteData=true이면 마이그레이션 롤백 전에 호출됩니다.
|
||||
* 반환된 테이블들은 PluginManager가 일괄 삭제합니다.
|
||||
*
|
||||
* 주의:
|
||||
* - 마이그레이션 롤백 전에 호출되므로 메타 테이블(정적 테이블)이 아직 존재합니다.
|
||||
* - 개별 테이블 삭제 실패 시에도 언인스톨은 계속 진행됩니다.
|
||||
*
|
||||
* @return array<string> 삭제할 테이블명 배열
|
||||
*/
|
||||
public function getDynamicTables(): array;
|
||||
|
||||
/**
|
||||
* 플러그인을 활성화합니다.
|
||||
*
|
||||
* @return bool 활성화 성공 여부
|
||||
*/
|
||||
public function activate(): bool;
|
||||
|
||||
/**
|
||||
* 플러그인을 비활성화합니다.
|
||||
*
|
||||
* @return bool 비활성화 성공 여부
|
||||
*/
|
||||
public function deactivate(): bool;
|
||||
|
||||
/**
|
||||
* 버전별 업그레이드 스텝을 반환합니다.
|
||||
*
|
||||
* 반환 형식: ['1.1.0' => callable|UpgradeStepInterface, ...]
|
||||
* 시스템이 fromVersion 초과 ~ toVersion 이하의 스텝을 자동 필터링 후 순차 실행합니다.
|
||||
*
|
||||
* @return array<string, callable|\App\Contracts\Extension\UpgradeStepInterface> 버전 => 스텝 매핑
|
||||
*/
|
||||
public function upgrades(): array;
|
||||
|
||||
/**
|
||||
* 플러그인이 제공하는 라우트 정보를 반환합니다.
|
||||
*
|
||||
* @return array 라우트 정보 배열
|
||||
*/
|
||||
public function getRoutes(): array;
|
||||
|
||||
/**
|
||||
* 플러그인의 마이그레이션 파일 목록을 반환합니다.
|
||||
*
|
||||
* @return array 마이그레이션 파일 경로 배열
|
||||
*/
|
||||
public function getMigrations(): array;
|
||||
|
||||
/**
|
||||
* 플러그인의 뷰 파일 목록을 반환합니다.
|
||||
*
|
||||
* @return array 뷰 파일 경로 배열
|
||||
*/
|
||||
public function getViews(): array;
|
||||
|
||||
/**
|
||||
* 플러그인의 의존성 정보를 반환합니다.
|
||||
*
|
||||
* @return array 의존성 목록 배열
|
||||
*/
|
||||
public function getDependencies(): array;
|
||||
|
||||
/**
|
||||
* 플러그인이 사용하는 권한 목록을 반환합니다.
|
||||
*
|
||||
* @return array 권한 목록 배열
|
||||
*/
|
||||
public function getPermissions(): array;
|
||||
|
||||
/**
|
||||
* 플러그인의 설정 정보를 반환합니다.
|
||||
*
|
||||
* @return array 설정 정보 배열
|
||||
*/
|
||||
public function getConfig(): array;
|
||||
|
||||
/**
|
||||
* 플러그인이 제공하는 훅 정보를 반환합니다.
|
||||
*
|
||||
* @return array 훅 정보 배열
|
||||
*/
|
||||
public function getHooks(): array;
|
||||
|
||||
/**
|
||||
* 플러그인의 훅 리스너 목록을 반환합니다.
|
||||
*
|
||||
* @return array 훅 리스너 클래스 목록 배열
|
||||
*/
|
||||
public function getHookListeners(): array;
|
||||
|
||||
/**
|
||||
* 플러그인의 스케줄 작업 목록을 반환합니다.
|
||||
*
|
||||
* 스케줄 배열의 각 항목은 다음 구조를 따라야 합니다:
|
||||
* - command: Artisan 커맨드 이름
|
||||
* - schedule: 스케줄 주기 ('daily', 'hourly', 'everyMinute', 'weekly' 또는 cron 표현식)
|
||||
* - description: 작업 설명 (선택)
|
||||
* - enabled_config: 설정 키 (선택, 설정에 따라 활성화 여부 결정)
|
||||
*
|
||||
* @return array 스케줄 작업 배열
|
||||
*/
|
||||
public function getSchedules(): array;
|
||||
|
||||
/**
|
||||
* 플러그인 설치 시 실행할 시더 클래스 목록을 반환합니다.
|
||||
*
|
||||
* 배열 순서대로 실행됩니다.
|
||||
* 빈 배열 반환 시 database/seeders/ 디렉토리의 모든 시더를 자동 검색합니다. (역호환)
|
||||
*
|
||||
* @return array<class-string<\Illuminate\Database\Seeder>> 시더 클래스명 배열 (FQCN)
|
||||
*/
|
||||
public function getSeeders(): array;
|
||||
|
||||
/**
|
||||
* 플러그인이 정의하는 역할 목록을 반환합니다.
|
||||
*
|
||||
* 역할 배열의 각 항목은 다음 구조를 따라야 합니다:
|
||||
* - identifier: 역할 고유 식별자 (vendor-plugin.rolename 형식)
|
||||
* - name: 다국어 배열 ['ko' => '역할명', 'en' => 'Role Name']
|
||||
* - description: 다국어 배열 ['ko' => '설명', 'en' => 'Description']
|
||||
*
|
||||
* @return array 역할 정보 배열
|
||||
*/
|
||||
public function getRoles(): array;
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 경로를 반환합니다.
|
||||
*
|
||||
* @return string extensions 디렉토리 경로
|
||||
*/
|
||||
public function getExtensionsPath(): string;
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 파일 목록을 반환합니다.
|
||||
*
|
||||
* resources/extensions 디렉토리에서 JSON 파일을 검색합니다.
|
||||
*
|
||||
* @return array<string> JSON 파일 경로 목록
|
||||
*/
|
||||
public function getLayoutExtensions(): array;
|
||||
|
||||
/**
|
||||
* 그누보드7 코어 요구 버전 제약을 반환합니다.
|
||||
*
|
||||
* Semantic Versioning 제약 문자열 반환 (예: ">=1.0.0", "^1.0", "~1.2.0")
|
||||
* null 반환 시 버전 검증을 건너뜁니다 (역호환성 보장).
|
||||
*
|
||||
* @return string|null 버전 제약 문자열 또는 null
|
||||
*/
|
||||
public function getRequiredCoreVersion(): ?string;
|
||||
|
||||
/**
|
||||
* 플러그인이 설정 페이지를 가지고 있는지 확인합니다.
|
||||
*
|
||||
* @return bool 설정 페이지 존재 여부
|
||||
*/
|
||||
public function hasSettings(): bool;
|
||||
|
||||
/**
|
||||
* 플러그인 설정 스키마를 반환합니다.
|
||||
*
|
||||
* 설정 스키마는 설정 필드의 타입, 라벨, 기본값, 유효성 검사 규칙 등을 정의합니다.
|
||||
* FormRequest에서 동적 유효성 검사 규칙 생성에 사용됩니다.
|
||||
*
|
||||
* @return array 설정 스키마 배열
|
||||
*
|
||||
* @example
|
||||
* ```php
|
||||
* return [
|
||||
* 'display_mode' => [
|
||||
* 'type' => 'enum',
|
||||
* 'options' => ['popup', 'layer'],
|
||||
* 'default' => 'layer',
|
||||
* 'label' => ['ko' => '표시 방식', 'en' => 'Display Mode'],
|
||||
* 'required' => false,
|
||||
* ],
|
||||
* 'api_key' => [
|
||||
* 'type' => 'string',
|
||||
* 'label' => ['ko' => 'API 키', 'en' => 'API Key'],
|
||||
* 'sensitive' => true, // 암호화 저장
|
||||
* 'required' => true,
|
||||
* ],
|
||||
* ];
|
||||
* ```
|
||||
*/
|
||||
public function getSettingsSchema(): array;
|
||||
|
||||
/**
|
||||
* 플러그인 설정 페이지 레이아웃 경로를 반환합니다.
|
||||
*
|
||||
* 설정 페이지의 JSON 레이아웃 파일 경로를 반환합니다.
|
||||
* null 반환 시 설정 페이지가 없는 것으로 간주합니다.
|
||||
*
|
||||
* @return string|null 레이아웃 파일 절대 경로 또는 null
|
||||
*/
|
||||
public function getSettingsLayout(): ?string;
|
||||
|
||||
/**
|
||||
* 플러그인 설정 페이지 라우트 경로를 반환합니다.
|
||||
*
|
||||
* 플러그인 목록에서 설정 버튼 클릭 시 이동할 경로입니다.
|
||||
* null 반환 시 설정 페이지가 없는 것으로 간주합니다.
|
||||
*
|
||||
* @return string|null 설정 페이지 라우트 (예: '/admin/plugins/{identifier}/settings')
|
||||
*/
|
||||
public function getSettingsRoute(): ?string;
|
||||
|
||||
/**
|
||||
* 플러그인 설정 값을 반환합니다.
|
||||
*
|
||||
* 현재 저장된 설정 값을 반환합니다. (DB 조회용)
|
||||
*
|
||||
* @return array 설정 값 배열
|
||||
*/
|
||||
public function getConfigValues(): array;
|
||||
|
||||
/**
|
||||
* 플러그인 설정 기본값 파일 경로를 반환합니다.
|
||||
*
|
||||
* config/settings/defaults.json 파일이 존재하면 해당 경로를 반환합니다.
|
||||
* 이 파일에는 defaults(기본값)와 frontend_schema(프론트엔드 노출 스키마)가 정의됩니다.
|
||||
*
|
||||
* @return string|null defaults.json 파일 절대 경로 또는 null
|
||||
*/
|
||||
public function getSettingsDefaultsPath(): ?string;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface PluginManagerInterface
|
||||
{
|
||||
/**
|
||||
* 모든 플러그인을 로드하고 초기화합니다.
|
||||
*/
|
||||
public function loadPlugins(): void;
|
||||
|
||||
/**
|
||||
* 활성화된 플러그인들만 반환합니다.
|
||||
*
|
||||
* @return array 활성화된 플러그인 배열
|
||||
*/
|
||||
public function getActivePlugins(): array;
|
||||
|
||||
/**
|
||||
* 지정된 플러그인을 시스템에 설치합니다.
|
||||
*
|
||||
* @param string $pluginName 설치할 플러그인명
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return bool 설치 성공 여부
|
||||
*
|
||||
* @throws \Exception 플러그인을 찾을 수 없거나 의존성 문제 시
|
||||
*/
|
||||
public function installPlugin(string $pluginName, ?\Closure $onProgress = null): bool;
|
||||
|
||||
/**
|
||||
* 지정된 플러그인을 활성화합니다.
|
||||
*
|
||||
* @param string $pluginName 활성화할 플러그인명
|
||||
* @return array{success: bool, layouts_registered: int} 활성화 결과
|
||||
*/
|
||||
public function activatePlugin(string $pluginName): array;
|
||||
|
||||
/**
|
||||
* 지정된 플러그인을 비활성화합니다.
|
||||
*
|
||||
* @param string $pluginName 비활성화할 플러그인명
|
||||
* @param bool $force 의존 템플릿이 있어도 강제 비활성화 여부
|
||||
* @return array{success: bool, layouts_deleted: int, warning?: bool, dependent_templates?: array, message?: string} 비활성화 결과
|
||||
*/
|
||||
public function deactivatePlugin(string $pluginName, bool $force = false): array;
|
||||
|
||||
/**
|
||||
* 지정된 플러그인을 시스템에서 제거합니다.
|
||||
*
|
||||
* @param string $pluginName 제거할 플러그인명
|
||||
* @param bool $deleteData 데이터 삭제 여부 (마이그레이션 롤백)
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return bool 제거 성공 여부
|
||||
*
|
||||
* @throws \Exception 플러그인을 찾을 수 없을 때
|
||||
*/
|
||||
public function uninstallPlugin(string $pluginName, bool $deleteData = false, ?\Closure $onProgress = null): bool;
|
||||
|
||||
/**
|
||||
* 지정된 이름의 플러그인 인스턴스를 반환합니다.
|
||||
*
|
||||
* @param string $pluginName 플러그인명
|
||||
* @return PluginInterface|null 플러그인 인스턴스 또는 null
|
||||
*/
|
||||
public function getPlugin(string $pluginName): ?PluginInterface;
|
||||
|
||||
/**
|
||||
* 로드된 모든 플러그인 인스턴스들을 반환합니다.
|
||||
*
|
||||
* @return array 모든 플러그인 배열
|
||||
*/
|
||||
public function getAllPlugins(): array;
|
||||
|
||||
/**
|
||||
* 설치되지 않은 플러그인들을 반환합니다.
|
||||
*
|
||||
* @return array 미설치 플러그인 배열
|
||||
*/
|
||||
public function getUninstalledPlugins(): array;
|
||||
|
||||
/**
|
||||
* 설치된 플러그인 정보를 데이터베이스 레코드와 함께 반환합니다.
|
||||
*
|
||||
* @return array 설치된 플러그인 배열
|
||||
*/
|
||||
public function getInstalledPluginsWithDetails(): array;
|
||||
|
||||
/**
|
||||
* 특정 플러그인의 정보를 반환합니다 (설치 여부와 관계없이).
|
||||
*
|
||||
* @param string $pluginName 플러그인명
|
||||
* @return array|null 플러그인 정보 배열 또는 null
|
||||
*/
|
||||
public function getPluginInfo(string $pluginName): ?array;
|
||||
|
||||
/**
|
||||
* 플러그인의 레이아웃을 파일에서 다시 읽어 DB에 갱신합니다.
|
||||
*
|
||||
* @param string $pluginName 플러그인명
|
||||
* @return array{success: bool, layouts_refreshed: int} 갱신 결과 및 갱신된 레이아웃 개수
|
||||
*
|
||||
* @throws \Exception 플러그인을 찾을 수 없거나 레이아웃 갱신 실패 시
|
||||
*/
|
||||
public function refreshPluginLayouts(string $pluginName): array;
|
||||
|
||||
/**
|
||||
* 플러그인 삭제 시 삭제될 데이터 정보를 반환합니다.
|
||||
*
|
||||
* @param string $pluginName 플러그인명
|
||||
* @return array|null 삭제 정보 (테이블 목록, 스토리지 디렉토리 목록, 용량) 또는 null
|
||||
*/
|
||||
public function getPluginUninstallInfo(string $pluginName): ?array;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인) 스토리지 인터페이스
|
||||
*
|
||||
* 모듈과 플러그인에서 파일을 저장하고 관리하기 위한 표준화된 인터페이스입니다.
|
||||
* 카테고리별로 파일을 분리하여 저장하며, 다양한 스토리지 백엔드를 지원합니다.
|
||||
*/
|
||||
interface StorageInterface
|
||||
{
|
||||
/**
|
||||
* 파일을 저장합니다.
|
||||
*
|
||||
* @param string $category 카테고리 (settings, attachments, images, cache, temp)
|
||||
* @param string $path 파일 경로 (카테고리 하위 상대 경로)
|
||||
* @param mixed $content 파일 내용 (string|resource)
|
||||
* @return bool 저장 성공 여부
|
||||
*/
|
||||
public function put(string $category, string $path, mixed $content): bool;
|
||||
|
||||
/**
|
||||
* 파일 내용을 가져옵니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @return string|null 파일 내용 (파일이 없으면 null)
|
||||
*/
|
||||
public function get(string $category, string $path): ?string;
|
||||
|
||||
/**
|
||||
* 파일이 존재하는지 확인합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @return bool 파일 존재 여부
|
||||
*/
|
||||
public function exists(string $category, string $path): bool;
|
||||
|
||||
/**
|
||||
* 파일을 삭제합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(string $category, string $path): bool;
|
||||
|
||||
/**
|
||||
* 파일의 공개 URL을 반환합니다.
|
||||
*
|
||||
* public disk인 경우 직접 URL을 반환하고,
|
||||
* private disk인 경우 null을 반환합니다 (별도 API 엔드포인트 사용).
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @return string|null 파일 URL (private disk인 경우 null)
|
||||
*/
|
||||
public function url(string $category, string $path): ?string;
|
||||
|
||||
/**
|
||||
* 디렉토리 내 모든 파일 목록을 반환합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $directory 디렉토리 경로 (카테고리 하위 상대 경로, 빈 문자열이면 카테고리 루트)
|
||||
* @return array 파일 경로 배열
|
||||
*/
|
||||
public function files(string $category, string $directory = ''): array;
|
||||
|
||||
/**
|
||||
* 디렉토리와 그 하위의 모든 파일을 삭제합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $directory 디렉토리 경로 (카테고리 하위 상대 경로, 빈 문자열이면 카테고리 루트)
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function deleteDirectory(string $category, string $directory = ''): bool;
|
||||
|
||||
/**
|
||||
* 카테고리의 전체 파일 시스템 경로를 반환합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @return string 전체 경로 (예: storage/app/modules/{identifier}/{category})
|
||||
*/
|
||||
public function getBasePath(string $category): string;
|
||||
|
||||
/**
|
||||
* 사용 중인 디스크 이름을 반환합니다.
|
||||
*
|
||||
* @return string 디스크 이름 (local, public, s3 등)
|
||||
*/
|
||||
public function getDisk(): string;
|
||||
|
||||
/**
|
||||
* 카테고리의 모든 파일을 삭제합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function deleteAll(string $category): bool;
|
||||
|
||||
/**
|
||||
* 파일을 스트리밍 응답으로 반환합니다.
|
||||
*
|
||||
* 파일을 다운로드하거나 브라우저에 표시할 수 있도록
|
||||
* StreamedResponse를 생성합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @param string $filename 다운로드 시 표시될 파일명
|
||||
* @param array $headers 추가 HTTP 헤더
|
||||
* @return \Symfony\Component\HttpFoundation\StreamedResponse|null 파일 스트림 (파일이 없으면 null)
|
||||
*/
|
||||
public function response(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* 사용할 디스크를 변경한 새 인스턴스를 반환합니다.
|
||||
*
|
||||
* 기존 인스턴스는 변경하지 않고, 새 디스크를 사용하는 복제된 인스턴스를 반환합니다.
|
||||
* 첨부파일 등 레코드별로 다른 디스크를 사용하는 경우에 활용합니다.
|
||||
*
|
||||
* @param string $disk 디스크 이름 (local, public, s3 등)
|
||||
* @return static 새 디스크를 사용하는 인스턴스
|
||||
*/
|
||||
public function withDisk(string $disk): static;
|
||||
|
||||
/**
|
||||
* 파일을 다운로드 응답으로 반환합니다.
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @param string $path 파일 경로
|
||||
* @param string $filename 다운로드 시 표시될 파일명
|
||||
* @param array $headers 추가 HTTP 헤더
|
||||
* @return \Symfony\Component\HttpFoundation\StreamedResponse|null 다운로드 응답 (파일이 없으면 null)
|
||||
*/
|
||||
public function download(string $category, string $path, string $filename, array $headers = []): ?\Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface TemplateInterface
|
||||
{
|
||||
/**
|
||||
* 템플릿의 고유 식별자를 반환합니다 (vendor-name 형식).
|
||||
*
|
||||
* @return string 템플릿 식별자 (예: sirsoft-admin_basic)
|
||||
*/
|
||||
public function getIdentifier(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 벤더/개발자명을 반환합니다.
|
||||
*
|
||||
* @return string 벤더명 (예: sirsoft)
|
||||
*/
|
||||
public function getVendor(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 이름을 반환합니다 (표시용).
|
||||
*
|
||||
* @return string 템플릿 이름 (예: Admin Basic)
|
||||
*/
|
||||
public function getName(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 버전을 반환합니다.
|
||||
*
|
||||
* @return string 템플릿 버전 (시맨틱 버전, 예: 1.0.0)
|
||||
*/
|
||||
public function getVersion(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 설명을 반환합니다.
|
||||
*
|
||||
* @return string 템플릿 설명
|
||||
*/
|
||||
public function getDescription(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 타입을 반환합니다.
|
||||
*
|
||||
* @return string 템플릿 타입 (admin: 관리자용, user: 사용자용)
|
||||
*/
|
||||
public function getType(): string;
|
||||
|
||||
/**
|
||||
* 템플릿을 설치합니다.
|
||||
*
|
||||
* @return bool 설치 성공 여부
|
||||
*/
|
||||
public function install(): bool;
|
||||
|
||||
/**
|
||||
* 템플릿을 제거합니다.
|
||||
*
|
||||
* @return bool 제거 성공 여부
|
||||
*/
|
||||
public function uninstall(): bool;
|
||||
|
||||
/**
|
||||
* 템플릿을 활성화합니다.
|
||||
*
|
||||
* @return bool 활성화 성공 여부
|
||||
*/
|
||||
public function activate(): bool;
|
||||
|
||||
/**
|
||||
* 템플릿을 비활성화합니다.
|
||||
*
|
||||
* @return bool 비활성화 성공 여부
|
||||
*/
|
||||
public function deactivate(): bool;
|
||||
|
||||
/**
|
||||
* 템플릿의 의존성 정보를 반환합니다.
|
||||
*
|
||||
* @return array 의존성 목록 배열 (모듈/플러그인 identifier => 버전)
|
||||
*/
|
||||
public function getDependencies(): array;
|
||||
|
||||
/**
|
||||
* 템플릿이 제공하는 기본 레이아웃 목록을 반환합니다.
|
||||
*
|
||||
* @return array 레이아웃 파일 경로 배열
|
||||
*/
|
||||
public function getDefaultLayouts(): array;
|
||||
|
||||
/**
|
||||
* 템플릿의 컴포넌트 매니페스트 경로를 반환합니다.
|
||||
*
|
||||
* @return string 컴포넌트 매니페스트 파일 경로 (components.json)
|
||||
*/
|
||||
public function getComponentsManifestPath(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 라우트 정의 파일 경로를 반환합니다.
|
||||
*
|
||||
* @return string 라우트 정의 파일 경로 (routes.json)
|
||||
*/
|
||||
public function getRoutesPath(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 빌드된 컴포넌트 번들 경로를 반환합니다.
|
||||
*
|
||||
* @return string 컴포넌트 번들 파일 경로 (dist/components.js)
|
||||
*/
|
||||
public function getComponentsBundlePath(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 에셋 디렉토리 경로를 반환합니다.
|
||||
*
|
||||
* @return string 에셋 디렉토리 경로 (assets/)
|
||||
*/
|
||||
public function getAssetsPath(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 다국어 파일 디렉토리 경로를 반환합니다.
|
||||
*
|
||||
* @return string 다국어 파일 디렉토리 경로 (lang/)
|
||||
*/
|
||||
public function getLangPath(): string;
|
||||
|
||||
/**
|
||||
* 템플릿의 메타데이터를 반환합니다.
|
||||
*
|
||||
* @return array 메타데이터 배열 (template.json 내용)
|
||||
*/
|
||||
public function getMetadata(): array;
|
||||
|
||||
/**
|
||||
* 템플릿의 GitHub 저장소 URL을 반환합니다.
|
||||
*
|
||||
* @return string|null GitHub URL 또는 null
|
||||
*/
|
||||
public function getGithubUrl(): ?string;
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
interface TemplateManagerInterface
|
||||
{
|
||||
/**
|
||||
* 모든 템플릿을 로드하고 초기화합니다.
|
||||
*/
|
||||
public function loadTemplates(): void;
|
||||
|
||||
/**
|
||||
* /templates 디렉토리를 스캔하여 사용 가능한 템플릿을 발견합니다.
|
||||
*
|
||||
* @return array 발견된 템플릿 배열 (identifier => path)
|
||||
*/
|
||||
public function scanTemplates(): array;
|
||||
|
||||
/**
|
||||
* 로드된 모든 템플릿 인스턴스들을 반환합니다.
|
||||
*
|
||||
* @return array 모든 템플릿 배열
|
||||
*/
|
||||
public function getAllTemplates(): array;
|
||||
|
||||
/**
|
||||
* 활성화된 템플릿을 반환합니다.
|
||||
*
|
||||
* @param string $type 템플릿 타입 (admin 또는 user)
|
||||
* @return array|null 활성화된 템플릿 데이터 또는 null
|
||||
*/
|
||||
public function getActiveTemplate(string $type): ?array;
|
||||
|
||||
/**
|
||||
* 지정된 식별자의 템플릿 데이터를 반환합니다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자 (vendor-name 형식)
|
||||
* @return array|null 템플릿 데이터 또는 null
|
||||
*/
|
||||
public function getTemplate(string $identifier): ?array;
|
||||
|
||||
/**
|
||||
* 지정된 템플릿을 시스템에 설치합니다.
|
||||
*
|
||||
* @param string $identifier 설치할 템플릿 식별자
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return bool 설치 성공 여부
|
||||
*
|
||||
* @throws \Exception 템플릿을 찾을 수 없거나 의존성 문제 시
|
||||
*/
|
||||
public function installTemplate(string $identifier, ?\Closure $onProgress = null): bool;
|
||||
|
||||
/**
|
||||
* 지정된 템플릿을 제거합니다.
|
||||
*
|
||||
* @param string $identifier 제거할 템플릿 식별자
|
||||
* @param \Closure|null $onProgress 진행 콜백 (?string $step, string $message)
|
||||
* @return bool 제거 성공 여부
|
||||
*
|
||||
* @throws \Exception 템플릿을 찾을 수 없을 때
|
||||
*/
|
||||
public function uninstallTemplate(string $identifier, ?\Closure $onProgress = null): bool;
|
||||
|
||||
/**
|
||||
* 지정된 템플릿을 활성화합니다.
|
||||
*
|
||||
* @param string $identifier 활성화할 템플릿 식별자
|
||||
* @param bool $force 의존성 미충족 시에도 강제 활성화 여부
|
||||
* @return array{success: bool, warning?: bool, missing_modules?: array, missing_plugins?: array, message?: string} 활성화 결과
|
||||
*/
|
||||
public function activateTemplate(string $identifier, bool $force = false): array;
|
||||
|
||||
/**
|
||||
* 지정된 템플릿을 비활성화합니다.
|
||||
*
|
||||
* @param string $identifier 비활성화할 템플릿 식별자
|
||||
* @return bool 비활성화 성공 여부
|
||||
*/
|
||||
public function deactivateTemplate(string $identifier): bool;
|
||||
|
||||
/**
|
||||
* 템플릿의 의존성을 검증합니다.
|
||||
*
|
||||
* @param string $identifier 검증할 템플릿 식별자
|
||||
* @return bool 의존성 충족 여부
|
||||
*
|
||||
* @throws \Exception 의존성이 충족되지 않을 때
|
||||
*/
|
||||
public function validateTemplate(string $identifier): bool;
|
||||
|
||||
/**
|
||||
* 설치되지 않은 템플릿들을 반환합니다.
|
||||
*
|
||||
* @return array 미설치 템플릿 배열
|
||||
*/
|
||||
public function getUninstalledTemplates(): array;
|
||||
|
||||
/**
|
||||
* 설치된 템플릿 정보를 데이터베이스 레코드와 함께 반환합니다.
|
||||
*
|
||||
* @return array 설치된 템플릿 배열
|
||||
*/
|
||||
public function getInstalledTemplatesWithDetails(): array;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 정보를 반환합니다 (설치 여부와 관계없이).
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return array|null 템플릿 정보 배열 또는 null
|
||||
*/
|
||||
public function getTemplateInfo(string $identifier): ?array;
|
||||
|
||||
/**
|
||||
* 타입별 템플릿 목록을 반환합니다.
|
||||
*
|
||||
* @param string $type 템플릿 타입 (admin 또는 user)
|
||||
* @return array 해당 타입의 템플릿 배열
|
||||
*/
|
||||
public function getTemplatesByType(string $type): array;
|
||||
|
||||
/**
|
||||
* 템플릿의 레이아웃을 파일에서 다시 읽어 DB에 갱신합니다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return array{success: bool, layouts_refreshed: int} 갱신 결과 및 갱신된 레이아웃 개수
|
||||
*
|
||||
* @throws \Exception 템플릿을 찾을 수 없거나 레이아웃 갱신 실패 시
|
||||
*/
|
||||
public function refreshTemplateLayouts(string $identifier): array;
|
||||
|
||||
/**
|
||||
* 템플릿의 의존성 충족 상태를 확인합니다.
|
||||
*
|
||||
* template.json의 dependencies를 기반으로 모든 모듈/플러그인의
|
||||
* 활성화 상태 및 버전 요구사항 충족 여부를 확인합니다.
|
||||
*
|
||||
* 각 의존성 항목 구조:
|
||||
* - identifier: 모듈/플러그인 식별자
|
||||
* - name: 로케일화된 이름 (미설치 시 identifier 사용)
|
||||
* - required_version: 요구 버전 제약조건
|
||||
* - installed_version: 설치된 버전 (null이면 미설치)
|
||||
* - is_active: 활성화 여부
|
||||
* - version_met: 버전 요구사항 충족 여부
|
||||
* - met: 전체 요구사항 충족 여부
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return array{met: bool, modules: array, plugins: array} 의존성 상태
|
||||
*/
|
||||
public function checkDependenciesStatus(string $identifier): array;
|
||||
|
||||
/**
|
||||
* 템플릿의 미충족 의존성 목록을 반환합니다.
|
||||
*
|
||||
* checkDependenciesStatus()를 활용하여 충족되지 않은 의존성만 필터링합니다.
|
||||
* 각 항목에는 identifier, name, required_version 등이 포함됩니다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return array{modules: array, plugins: array} 미충족 의존성 목록
|
||||
*/
|
||||
public function getUnmetDependencies(string $identifier): array;
|
||||
|
||||
/**
|
||||
* 특정 모듈에 의존하는 활성 템플릿 목록을 반환합니다.
|
||||
*
|
||||
* 모든 활성화된 템플릿을 조회하여 해당 모듈을 dependencies.modules에
|
||||
* 포함하고 있는 템플릿의 identifier 목록을 반환합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return array 의존하는 템플릿 identifier 배열
|
||||
*/
|
||||
public function getTemplatesDependingOnModule(string $moduleIdentifier): array;
|
||||
|
||||
/**
|
||||
* 특정 플러그인에 의존하는 활성 템플릿 목록을 반환합니다.
|
||||
*
|
||||
* 모든 활성화된 템플릿을 조회하여 해당 플러그인을 dependencies.plugins에
|
||||
* 포함하고 있는 템플릿의 identifier 목록을 반환합니다.
|
||||
*
|
||||
* @param string $pluginIdentifier 플러그인 식별자
|
||||
* @return array 의존하는 템플릿 identifier 배열
|
||||
*/
|
||||
public function getTemplatesDependingOnPlugin(string $pluginIdentifier): array;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Extension;
|
||||
|
||||
use App\Extension\UpgradeContext;
|
||||
|
||||
/**
|
||||
* 버전별 업그레이드 스텝 인터페이스
|
||||
*
|
||||
* 모듈/플러그인의 버전별 업그레이드 로직을 정의합니다.
|
||||
* 각 스텝은 upgrades/ 디렉토리에 위치하며, 파일명에서 버전을 추출합니다.
|
||||
*
|
||||
* 주요 사용 사례:
|
||||
* - DB 스키마/데이터 마이그레이션
|
||||
* - 설정 구조 변경
|
||||
* - 정적 메뉴/권한 제거 (cleanupStaleMenus/cleanupStalePermissions 활용)
|
||||
*
|
||||
* ⚠️ 동적 데이터 정리:
|
||||
* 확장이 런타임에 생성한 동적 메뉴/권한/역할은 자동으로 정리되지 않습니다.
|
||||
* 새 버전에서 동적 데이터의 형식이 변경되거나, 기존 정적 메뉴/권한을 제거해야 하는 경우
|
||||
* UpgradeStep에서 ExtensionMenuSyncHelper::cleanupStaleMenus() 또는
|
||||
* ExtensionRoleSyncHelper::cleanupStalePermissions()를 명시적으로 호출하세요.
|
||||
*
|
||||
* @example Upgrade_1_1_0.php → 버전 1.1.0 업그레이드 스텝
|
||||
*/
|
||||
interface UpgradeStepInterface
|
||||
{
|
||||
/**
|
||||
* 업그레이드 스텝을 실행합니다.
|
||||
*
|
||||
* @param UpgradeContext $context 업그레이드 컨텍스트 (버전 정보, 로거 등)
|
||||
*
|
||||
* @throws \Exception 업그레이드 실패 시 예외 발생 (상위에서 백업 복원 처리)
|
||||
*/
|
||||
public function run(UpgradeContext $context): void;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* 활동 로그 Repository 인터페이스
|
||||
*/
|
||||
interface ActivityLogRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 특정 모델의 활동 로그를 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param Model $model 대상 모델
|
||||
* @param array $filters 필터 조건
|
||||
* @return LengthAwarePaginator 페이지네이션된 로그 목록
|
||||
*/
|
||||
|
||||
public function getPaginatedForModel(Model $model, array $filters = []): LengthAwarePaginator;
|
||||
/**
|
||||
* 활동 로그 목록을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @return LengthAwarePaginator 페이지네이션된 로그 목록
|
||||
*/
|
||||
public function getPaginated(array $filters = []): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 활동 로그를 삭제합니다.
|
||||
*
|
||||
* @param int $id 삭제할 활동 로그 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(int $id): bool;
|
||||
|
||||
/**
|
||||
* 여러 활동 로그를 일괄 삭제합니다.
|
||||
*
|
||||
* @param array<int> $ids 삭제할 활동 로그 ID 목록
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function deleteMany(array $ids): int;
|
||||
|
||||
/**
|
||||
* 최근 활동 로그를 스코프 권한 적용하여 조회합니다.
|
||||
*
|
||||
* @param string $permission 권한 식별자
|
||||
* @param int $limit 조회할 활동 수
|
||||
* @return Collection 활동 로그 컬렉션
|
||||
*/
|
||||
public function getRecent(string $permission, int $limit = 5): Collection;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\Attachment;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
/**
|
||||
* 첨부파일 Repository 인터페이스
|
||||
*/
|
||||
interface AttachmentRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* ID로 첨부파일 조회
|
||||
*
|
||||
* @param int $id 첨부파일 ID
|
||||
* @return Attachment|null 첨부파일 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?Attachment;
|
||||
|
||||
/**
|
||||
* 여러 ID로 첨부파일 조회 (order 정렬)
|
||||
*
|
||||
* @param array<int> $ids 첨부파일 ID 배열
|
||||
* @return Collection<int, Attachment>
|
||||
*/
|
||||
public function findByIds(array $ids): Collection;
|
||||
|
||||
/**
|
||||
* 해시로 첨부파일 조회
|
||||
*
|
||||
* @param string $hash 첨부파일 해시
|
||||
* @return Attachment|null 첨부파일 또는 null
|
||||
*/
|
||||
public function findByHash(string $hash): ?Attachment;
|
||||
|
||||
/**
|
||||
* 첨부 대상별 첨부파일 조회
|
||||
*
|
||||
* @param string $type attachmentable_type
|
||||
* @param int $id attachmentable_id
|
||||
* @param string|null $collection 컬렉션 필터 (null이면 전체)
|
||||
* @return Collection<int, Attachment>
|
||||
*/
|
||||
public function getByAttachmentable(string $type, int $id, ?string $collection = null): Collection;
|
||||
|
||||
/**
|
||||
* 첨부파일 생성
|
||||
*
|
||||
* @param array<string, mixed> $data 생성 데이터
|
||||
* @return Attachment 생성된 첨부파일
|
||||
*/
|
||||
public function create(array $data): Attachment;
|
||||
|
||||
/**
|
||||
* 첨부파일 업데이트
|
||||
*
|
||||
* @param int $id 첨부파일 ID
|
||||
* @param array<string, mixed> $data 업데이트 데이터
|
||||
* @return Attachment 업데이트된 첨부파일
|
||||
*/
|
||||
public function update(int $id, array $data): Attachment;
|
||||
|
||||
/**
|
||||
* 첨부파일 삭제 (soft delete)
|
||||
*
|
||||
* @param int $id 첨부파일 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(int $id): bool;
|
||||
|
||||
/**
|
||||
* 첨부파일 영구 삭제
|
||||
*
|
||||
* @param int $id 첨부파일 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function forceDelete(int $id): bool;
|
||||
|
||||
/**
|
||||
* 순서 변경
|
||||
*
|
||||
* @param array<int, array{id: int, order: int}> $orderData 순서 데이터
|
||||
*/
|
||||
public function reorder(array $orderData): void;
|
||||
|
||||
/**
|
||||
* 특정 소스 식별자의 첨부파일 목록 조회
|
||||
*
|
||||
* @param string $identifier 소스 식별자
|
||||
* @return Collection 첨부파일 컬렉션
|
||||
*/
|
||||
public function getBySourceIdentifier(string $identifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 소스 식별자의 첨부파일 일괄 삭제
|
||||
*
|
||||
* @param string $identifier 소스 식별자
|
||||
* @return int 삭제된 개수
|
||||
*/
|
||||
public function deleteBySourceIdentifier(string $identifier): int;
|
||||
|
||||
/**
|
||||
* 컬렉션 내 최대 order 값 조회
|
||||
*
|
||||
* @param string $type attachmentable_type
|
||||
* @param int $id attachmentable_id
|
||||
* @param string $collection 컬렉션명
|
||||
* @return int 최대 order 값
|
||||
*/
|
||||
public function getMaxOrder(string $type, int $id, string $collection): int;
|
||||
|
||||
/**
|
||||
* 컬렉션명으로만 최대 order 값 조회 (attachmentable 없는 경우)
|
||||
*
|
||||
* @param string $collection 컬렉션명
|
||||
* @return int 최대 order 값
|
||||
*/
|
||||
public function getMaxOrderByCollection(string $collection): int;
|
||||
|
||||
/**
|
||||
* 컬렉션명으로 첨부파일 조회 (attachmentable 없는 경우)
|
||||
*
|
||||
* @param string $collection 컬렉션명
|
||||
* @return Collection<int, Attachment>
|
||||
*/
|
||||
public function getByCollection(string $collection): Collection;
|
||||
|
||||
/**
|
||||
* 미연결 첨부파일을 특정 엔티티에 연결합니다.
|
||||
*
|
||||
* @param string $collection 컬렉션명
|
||||
* @param string $attachmentableType 연결할 모델 클래스명
|
||||
* @param int $attachmentableId 연결할 모델 ID
|
||||
* @return int 연결된 첨부파일 수
|
||||
*/
|
||||
public function linkUnattachedFiles(string $collection, string $attachmentableType, int $attachmentableId): int;
|
||||
|
||||
/**
|
||||
* 특정 엔티티의 첨부파일 순서를 재정렬합니다.
|
||||
* 삭제 등으로 중간에 빈 순서가 생긴 경우 1부터 연속된 순서로 재정렬합니다.
|
||||
*
|
||||
* @param string $attachmentableType 첨부 대상 타입
|
||||
* @param int $attachmentableId 첨부 대상 ID
|
||||
* @param string $collection 컬렉션명
|
||||
*/
|
||||
public function reorderAfterDelete(string $attachmentableType, int $attachmentableId, string $collection): void;
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
/**
|
||||
* 설정 저장소 인터페이스
|
||||
*
|
||||
* JSON 파일 기반 설정 관리를 위한 Repository 인터페이스입니다.
|
||||
*/
|
||||
interface ConfigRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 카테고리의 설정을 조회합니다.
|
||||
*
|
||||
* @return array<string, array<string, mixed>> 카테고리별 설정 배열
|
||||
*/
|
||||
public function all(): array;
|
||||
|
||||
/**
|
||||
* 특정 카테고리의 설정을 조회합니다.
|
||||
*
|
||||
* @param string $category 카테고리명 (예: 'general', 'mail')
|
||||
* @return array<string, mixed> 설정 배열
|
||||
*/
|
||||
public function getCategory(string $category): array;
|
||||
|
||||
/**
|
||||
* 도트 노테이션으로 특정 설정값을 조회합니다.
|
||||
*
|
||||
* @param string $key 설정 키 (예: 'mail.host', 'general.site_name')
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값
|
||||
*/
|
||||
public function get(string $key, mixed $default = null): mixed;
|
||||
|
||||
/**
|
||||
* 도트 노테이션으로 특정 설정값을 저장합니다.
|
||||
*
|
||||
* @param string $key 설정 키
|
||||
* @param mixed $value 저장할 값
|
||||
* @return bool 저장 성공 여부
|
||||
*/
|
||||
public function set(string $key, mixed $value): bool;
|
||||
|
||||
/**
|
||||
* 여러 설정을 일괄 저장합니다.
|
||||
*
|
||||
* @param array<string, mixed> $settings 설정 배열
|
||||
* @return bool 저장 성공 여부
|
||||
*/
|
||||
public function setMany(array $settings): bool;
|
||||
|
||||
/**
|
||||
* 특정 카테고리의 설정을 저장합니다.
|
||||
*
|
||||
* @param string $category 카테고리명
|
||||
* @param array<string, mixed> $settings 설정 배열
|
||||
* @return bool 저장 성공 여부
|
||||
*/
|
||||
public function saveCategory(string $category, array $settings): bool;
|
||||
|
||||
/**
|
||||
* 설정 키 존재 여부를 확인합니다.
|
||||
*
|
||||
* @param string $key 설정 키
|
||||
* @return bool 존재 여부
|
||||
*/
|
||||
public function has(string $key): bool;
|
||||
|
||||
/**
|
||||
* 특정 설정을 삭제합니다.
|
||||
*
|
||||
* @param string $key 설정 키
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(string $key): bool;
|
||||
|
||||
/**
|
||||
* 사용 가능한 카테고리 목록을 반환합니다.
|
||||
*
|
||||
* @return array<string> 카테고리 목록
|
||||
*/
|
||||
public function getCategories(): array;
|
||||
|
||||
/**
|
||||
* 카테고리 존재 여부를 확인합니다.
|
||||
*
|
||||
* @param string $category 카테고리명
|
||||
* @return bool 존재 여부
|
||||
*/
|
||||
public function categoryExists(string $category): bool;
|
||||
|
||||
/**
|
||||
* 설정 파일을 초기화합니다.
|
||||
*
|
||||
* @param array<string, array<string, mixed>> $settings 초기 설정값
|
||||
* @return bool 초기화 성공 여부
|
||||
*/
|
||||
public function initialize(array $settings = []): bool;
|
||||
|
||||
/**
|
||||
* 설정을 백업합니다.
|
||||
*
|
||||
* @return string 백업 파일 경로
|
||||
*/
|
||||
public function backup(): string;
|
||||
|
||||
/**
|
||||
* 백업에서 설정을 복원합니다.
|
||||
*
|
||||
* @param string $backupPath 백업 파일 경로
|
||||
* @return bool 복원 성공 여부
|
||||
*/
|
||||
public function restore(string $backupPath): bool;
|
||||
|
||||
/**
|
||||
* 기본 설정값을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<string, mixed>> 카테고리별 기본 설정
|
||||
*/
|
||||
public function getDefaults(): array;
|
||||
|
||||
/**
|
||||
* 프론트엔드 스키마를 반환합니다.
|
||||
*
|
||||
* 프론트엔드에 노출할 설정 필드와 타입 캐스팅 규칙을 정의합니다.
|
||||
*
|
||||
* @return array<string, array<string, mixed>> 카테고리별 스키마
|
||||
*/
|
||||
public function getFrontendSchema(): array;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Models\LayoutExtension;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 리포지토리 인터페이스
|
||||
*/
|
||||
interface LayoutExtensionRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 특정 확장점에 등록된 확장 목록 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getByExtensionPoint(int $templateId, string $extensionPointName): Collection;
|
||||
|
||||
/**
|
||||
* 특정 레이아웃을 타겟으로 하는 오버레이 목록 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getOverlaysByLayout(int $templateId, string $layoutName): Collection;
|
||||
|
||||
/**
|
||||
* 확장 등록
|
||||
*
|
||||
* @param array $data 확장 데이터
|
||||
* @return LayoutExtension
|
||||
*/
|
||||
public function create(array $data): LayoutExtension;
|
||||
|
||||
/**
|
||||
* 확장 등록 또는 업데이트 (upsert)
|
||||
*
|
||||
* 동일한 조건의 확장이 존재하면 업데이트하고, 없으면 생성합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건 (template_id, extension_type, target_name, source_type, source_identifier)
|
||||
* @param array $values 생성/업데이트할 값
|
||||
* @return LayoutExtension
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): LayoutExtension;
|
||||
|
||||
/**
|
||||
* 출처별 확장 삭제 (soft delete)
|
||||
*
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function softDeleteBySource(LayoutSourceType $sourceType, string $identifier): int;
|
||||
|
||||
/**
|
||||
* 출처별 확장 복원
|
||||
*
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @return int 복원된 레코드 수
|
||||
*/
|
||||
public function restoreBySource(LayoutSourceType $sourceType, string $identifier): int;
|
||||
|
||||
/**
|
||||
* 출처별 확장 영구 삭제
|
||||
*
|
||||
* @param LayoutSourceType $sourceType 출처 타입
|
||||
* @param string $identifier 출처 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function forceDeleteBySource(LayoutSourceType $sourceType, string $identifier): int;
|
||||
|
||||
/**
|
||||
* 템플릿 오버라이드 확인 (Extension Point용)
|
||||
*
|
||||
* 특정 extension_point에 대해 템플릿이 오버라이드를 정의했는지 확인합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @param string $moduleIdentifier 모듈/플러그인 식별자
|
||||
* @return LayoutExtension|null 템플릿 오버라이드 또는 null
|
||||
*/
|
||||
public function findTemplateOverrideForExtensionPoint(
|
||||
int $templateId,
|
||||
string $extensionPointName,
|
||||
string $moduleIdentifier
|
||||
): ?LayoutExtension;
|
||||
|
||||
/**
|
||||
* 템플릿 오버라이드 확인 (Overlay용)
|
||||
*
|
||||
* 특정 target_layout에 대해 템플릿이 오버라이드를 정의했는지 확인합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param string $moduleIdentifier 모듈/플러그인 식별자
|
||||
* @return LayoutExtension|null 템플릿 오버라이드 또는 null
|
||||
*/
|
||||
public function findTemplateOverrideForOverlay(
|
||||
int $templateId,
|
||||
string $layoutName,
|
||||
string $moduleIdentifier
|
||||
): ?LayoutExtension;
|
||||
|
||||
/**
|
||||
* 오버라이드를 고려한 Extension Point 조회
|
||||
*
|
||||
* 템플릿 오버라이드가 있는 모듈 확장은 제외하고,
|
||||
* 오버라이드된 버전과 원본 모듈 확장을 함께 반환합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extensionPointName 확장점 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getResolvedExtensionPoints(int $templateId, string $extensionPointName): Collection;
|
||||
|
||||
/**
|
||||
* 오버라이드를 고려한 Overlay 조회
|
||||
*
|
||||
* 템플릿 오버라이드가 있는 모듈 확장은 제외하고,
|
||||
* 오버라이드된 버전과 원본 모듈 확장을 함께 반환합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getResolvedOverlays(int $templateId, string $layoutName): Collection;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 확장 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection<int, LayoutExtension>
|
||||
*/
|
||||
public function getByTemplateId(int $templateId): Collection;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 확장 삭제
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByTemplateId(int $templateId): int;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\TemplateLayoutPreview;
|
||||
|
||||
interface LayoutPreviewRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 미리보기를 생성합니다.
|
||||
*
|
||||
* @param array $data 생성 데이터
|
||||
* @return TemplateLayoutPreview 생성된 미리보기 모델
|
||||
*/
|
||||
public function create(array $data): TemplateLayoutPreview;
|
||||
|
||||
/**
|
||||
* 토큰으로 미리보기를 조회합니다.
|
||||
*
|
||||
* @param string $token 미리보기 토큰
|
||||
* @return TemplateLayoutPreview|null 찾은 미리보기 모델 또는 null
|
||||
*/
|
||||
public function findByToken(string $token): ?TemplateLayoutPreview;
|
||||
|
||||
/**
|
||||
* 토큰으로 미리보기를 삭제합니다.
|
||||
*
|
||||
* @param string $token 미리보기 토큰
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function deleteByToken(string $token): bool;
|
||||
|
||||
/**
|
||||
* 만료된 미리보기를 일괄 삭제합니다.
|
||||
*
|
||||
* @return int 삭제된 행 수
|
||||
*/
|
||||
public function deleteExpired(): int;
|
||||
|
||||
/**
|
||||
* 특정 관리자의 특정 레이아웃 미리보기를 삭제합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @param int $adminId 관리자 ID
|
||||
* @return int 삭제된 행 수
|
||||
*/
|
||||
public function deleteByLayoutAndAdmin(int $templateId, string $layoutName, int $adminId): int;
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Enums\LayoutSourceType;
|
||||
use App\Models\TemplateLayout;
|
||||
use App\Models\TemplateLayoutVersion;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface LayoutRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getByTemplateId(int $templateId): Collection;
|
||||
|
||||
/**
|
||||
* 특정 레이아웃 조회 (템플릿 ID와 이름으로)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findByName(int $templateId, string $name): ?TemplateLayout;
|
||||
|
||||
/**
|
||||
* ID로 레이아웃 조회
|
||||
*
|
||||
* @param int $id 레이아웃 ID
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?TemplateLayout;
|
||||
|
||||
/**
|
||||
* 레이아웃이 존재하는지 확인
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return bool 존재 여부
|
||||
*/
|
||||
public function exists(int $templateId, string $name): bool;
|
||||
|
||||
/**
|
||||
* extends를 가진 자식 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $extendsName extends 이름
|
||||
* @return Collection 자식 레이아웃 컬렉션
|
||||
*/
|
||||
public function getChildrenByExtends(int $templateId, string $extendsName): Collection;
|
||||
|
||||
/**
|
||||
* 레이아웃 업데이트
|
||||
*
|
||||
* @param int $id 레이아웃 ID
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return TemplateLayout 업데이트된 레이아웃 모델
|
||||
*/
|
||||
public function update(int $id, array $data): TemplateLayout;
|
||||
|
||||
/**
|
||||
* 특정 레이아웃의 모든 버전 조회
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @return Collection 버전 컬렉션
|
||||
*/
|
||||
public function getVersionsByLayoutId(int $layoutId): Collection;
|
||||
|
||||
/**
|
||||
* 특정 버전 조회
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @param int $version 버전 번호
|
||||
* @return TemplateLayoutVersion|null 찾은 버전 모델 또는 null
|
||||
*/
|
||||
public function findVersionByNumber(int $layoutId, int $version): ?TemplateLayoutVersion;
|
||||
|
||||
/**
|
||||
* 템플릿 오버라이드 레이아웃 찾기
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findTemplateOverride(int $templateId, string $layoutName): ?TemplateLayout;
|
||||
|
||||
/**
|
||||
* 모듈 기본 레이아웃 찾기
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findModuleLayout(int $templateId, string $layoutName): ?TemplateLayout;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃 이름 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return \Illuminate\Support\Collection<int, string> 레이아웃 이름 컬렉션
|
||||
*/
|
||||
public function getLayoutNamesByTemplateId(int $templateId): \Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 모든 레이아웃 조회
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getLayoutsByModule(string $moduleIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 템플릿에서 오버라이드된 모든 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection 오버라이드 레이아웃 컬렉션
|
||||
*/
|
||||
public function getOverriddenLayouts(int $templateId): Collection;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 레이아웃 중 템플릿에서 오버라이드된 것들 조회
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection 오버라이드 레이아웃 컬렉션
|
||||
*/
|
||||
public function getModuleLayoutOverrides(string $moduleIdentifier, int $templateId): Collection;
|
||||
|
||||
/**
|
||||
* 우선순위에 따라 레이아웃 조회 (오버라이드 우선)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string $name 레이아웃 이름
|
||||
* @return TemplateLayout|null 찾은 레이아웃 모델 또는 null
|
||||
*/
|
||||
public function findByNameWithOverride(int $templateId, string $name): ?TemplateLayout;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 모듈 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $moduleIdentifier 특정 모듈만 조회 (선택)
|
||||
* @return Collection 모듈 레이아웃 컬렉션
|
||||
*/
|
||||
public function findModuleLayouts(int $templateId, ?string $moduleIdentifier = null): Collection;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃 조회 (source_type 필터 옵션 포함)
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $sourceType 소스 타입 필터
|
||||
* @param string|null $sourceIdentifier 소스 식별자 필터
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getByTemplateIdWithFilter(
|
||||
int $templateId,
|
||||
?string $sourceType = null,
|
||||
?string $sourceIdentifier = null
|
||||
): Collection;
|
||||
|
||||
/**
|
||||
* 특정 플러그인의 모든 레이아웃 조회
|
||||
*
|
||||
* @param string $pluginIdentifier 플러그인 식별자
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getLayoutsByPlugin(string $pluginIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 플러그인 레이아웃 조회
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @param string|null $pluginIdentifier 특정 플러그인만 조회 (선택)
|
||||
* @return Collection 플러그인 레이아웃 컬렉션
|
||||
*/
|
||||
public function findPluginLayouts(int $templateId, ?string $pluginIdentifier = null): Collection;
|
||||
|
||||
/**
|
||||
* 레이아웃을 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 데이터
|
||||
* @return TemplateLayout 생성 또는 업데이트된 레이아웃 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): TemplateLayout;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 soft delete된 레이아웃을 조회합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return Collection soft delete된 레이아웃 컬렉션
|
||||
*/
|
||||
public function getTrashedByModule(string $moduleIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 레이아웃을 soft delete합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return int soft delete된 레코드 수
|
||||
*/
|
||||
public function softDeleteByModule(string $moduleIdentifier): int;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 레이아웃을 영구 삭제합니다 (soft delete 포함).
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function forceDeleteByModule(string $moduleIdentifier): int;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 레이아웃 개수를 반환합니다 (soft delete 포함).
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return int 레이아웃 개수
|
||||
*/
|
||||
public function countByModule(string $moduleIdentifier): int;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 soft delete된 레이아웃을 복원합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return int 복원된 레코드 수
|
||||
*/
|
||||
public function restoreByModule(string $moduleIdentifier): int;
|
||||
|
||||
/**
|
||||
* 특정 모듈의 레이아웃들을 조회합니다 (soft delete 제외).
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getByModuleIdentifier(string $moduleIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 확장(모듈 또는 플러그인)의 레이아웃들을 소스 타입과 함께 조회합니다.
|
||||
*
|
||||
* @param string $sourceIdentifier 확장 식별자
|
||||
* @param LayoutSourceType $sourceType 소스 타입 (Module 또는 Plugin)
|
||||
* @return Collection 레이아웃 컬렉션
|
||||
*/
|
||||
public function getBySourceIdentifier(string $sourceIdentifier, LayoutSourceType $sourceType): Collection;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 모든 레이아웃을 삭제합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByTemplateId(int $templateId): int;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 레이아웃 개수를 조회합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return int 레이아웃 개수
|
||||
*/
|
||||
public function countByTemplateId(int $templateId): int;
|
||||
|
||||
/**
|
||||
* 특정 템플릿의 오버라이드 레이아웃들을 조회합니다.
|
||||
*
|
||||
* @param int $templateId 템플릿 ID
|
||||
* @return Collection 오버라이드 레이아웃 컬렉션
|
||||
*/
|
||||
public function getOverridesByTemplateId(int $templateId): Collection;
|
||||
|
||||
/**
|
||||
* 특정 소스 식별자의 레이아웃을 모두 삭제합니다.
|
||||
*
|
||||
* @param string $sourceIdentifier 소스 식별자 (모듈/템플릿 식별자)
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteBySourceIdentifier(string $sourceIdentifier): int;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\TemplateLayoutVersion;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface LayoutVersionRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 버전 저장 (자동 증가)
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @param array $oldContent 이전 콘텐츠
|
||||
* @param array|null $newContent 새 콘텐츠 (null이면 현재 레이아웃 content 사용)
|
||||
* @return TemplateLayoutVersion 생성된 버전 모델
|
||||
*/
|
||||
public function saveVersion(int $layoutId, array $oldContent, ?array $newContent = null): TemplateLayoutVersion;
|
||||
|
||||
/**
|
||||
* 특정 레이아웃의 모든 버전 조회 (최신순)
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @return Collection 버전 컬렉션
|
||||
*/
|
||||
public function getVersions(int $layoutId): Collection;
|
||||
|
||||
/**
|
||||
* 특정 버전 조회
|
||||
*
|
||||
* @param int $versionId 버전 ID
|
||||
* @return TemplateLayoutVersion|null 찾은 버전 모델 또는 null
|
||||
*/
|
||||
public function getVersion(int $versionId): ?TemplateLayoutVersion;
|
||||
|
||||
/**
|
||||
* 다음 버전 번호 계산
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @return int 다음 버전 번호
|
||||
*/
|
||||
public function getNextVersion(int $layoutId): int;
|
||||
|
||||
/**
|
||||
* JSON content 변경사항 계산
|
||||
*
|
||||
* @param array $oldContent 이전 콘텐츠
|
||||
* @param array $newContent 새 콘텐츠
|
||||
* @return array 변경사항 (added, removed, modified)
|
||||
*/
|
||||
public function calculateChanges(array $oldContent, array $newContent): array;
|
||||
|
||||
/**
|
||||
* 버전 복원
|
||||
*
|
||||
* @param int $layoutId 레이아웃 ID
|
||||
* @param int $versionId 복원할 버전 ID
|
||||
* @return TemplateLayoutVersion 복원 후 생성된 새 버전 모델
|
||||
*
|
||||
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException 버전을 찾을 수 없는 경우
|
||||
*/
|
||||
public function restoreVersion(int $layoutId, int $versionId): TemplateLayoutVersion;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\MailSendLog;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 메일 발송 이력 리포지토리 인터페이스
|
||||
*/
|
||||
interface MailSendLogRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 발송 이력을 생성합니다.
|
||||
*
|
||||
* @param array $data 생성 데이터
|
||||
* @return MailSendLog 생성된 발송 이력 모델
|
||||
*/
|
||||
public function create(array $data): MailSendLog;
|
||||
|
||||
/**
|
||||
* 발송 이력 목록을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건 (module, template_type, status, search, date_from, date_to)
|
||||
* @param int $perPage 페이지 당 항목 수
|
||||
* @return LengthAwarePaginator 페이지네이션 결과
|
||||
*/
|
||||
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 발송 통계를 조회합니다.
|
||||
*
|
||||
* @return array{total: int, sent: int, failed: int, today: int} 통계 정보
|
||||
*/
|
||||
public function getStatistics(): array;
|
||||
|
||||
/**
|
||||
* 발송 이력을 삭제합니다.
|
||||
*
|
||||
* @param int $id 삭제할 발송 이력 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(int $id): bool;
|
||||
|
||||
/**
|
||||
* 여러 발송 이력을 일괄 삭제합니다.
|
||||
*
|
||||
* @param array<int> $ids 삭제할 발송 이력 ID 목록
|
||||
* @return int 삭제된 건수
|
||||
*/
|
||||
public function deleteMany(array $ids): int;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\MailTemplate;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface MailTemplateRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* ID로 메일 템플릿을 찾습니다.
|
||||
*
|
||||
* @param int $id 메일 템플릿 ID
|
||||
* @return MailTemplate|null 찾은 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?MailTemplate;
|
||||
|
||||
/**
|
||||
* 유형으로 메일 템플릿을 찾습니다.
|
||||
*
|
||||
* @param string $type 템플릿 유형
|
||||
* @return MailTemplate|null 찾은 모델 또는 null
|
||||
*/
|
||||
public function findByType(string $type): ?MailTemplate;
|
||||
|
||||
/**
|
||||
* 활성 상태인 특정 유형 템플릿을 찾습니다.
|
||||
*
|
||||
* @param string $type 템플릿 유형
|
||||
* @return MailTemplate|null 활성 템플릿 또는 null
|
||||
*/
|
||||
public function getActiveByType(string $type): ?MailTemplate;
|
||||
|
||||
/**
|
||||
* 모든 메일 템플릿 목록을 반환합니다.
|
||||
*
|
||||
* @return Collection 메일 템플릿 컬렉션
|
||||
*/
|
||||
public function getAllTemplates(): Collection;
|
||||
|
||||
/**
|
||||
* 메일 템플릿을 수정합니다.
|
||||
*
|
||||
* @param MailTemplate $template 수정 대상
|
||||
* @param array $data 수정 데이터
|
||||
* @return bool 수정 성공 여부
|
||||
*/
|
||||
public function update(MailTemplate $template, array $data): bool;
|
||||
|
||||
/**
|
||||
* 메일 템플릿 목록을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @param int $perPage 페이지 당 항목 수
|
||||
* @return LengthAwarePaginator 페이지네이션 결과
|
||||
*/
|
||||
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator;
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Menu;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface MenuRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 메뉴를 조회합니다.
|
||||
*
|
||||
* @return Collection 메뉴 컬렉션 (관계 데이터 포함)
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* 최상위 메뉴들을 조회합니다.
|
||||
*
|
||||
* @return Collection 최상위 메뉴 컬렉션 (활성화된 것만)
|
||||
*/
|
||||
public function getTopLevelMenus(): Collection;
|
||||
|
||||
public function getTopLevelMenusForManagement(array $activeModuleIdentifiers = [], array $activePluginIdentifiers = [], ?User $user = null): Collection;
|
||||
|
||||
/**
|
||||
* 활성화된 메뉴들만 조회합니다.
|
||||
*
|
||||
* @return Collection 활성화된 메뉴 컬렉션
|
||||
*/
|
||||
public function getActiveMenus(): Collection;
|
||||
|
||||
/**
|
||||
* ID로 메뉴를 찾습니다.
|
||||
*
|
||||
* @param int $id 메뉴 ID
|
||||
* @return Menu|null 찾은 메뉴 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?Menu;
|
||||
|
||||
/**
|
||||
* 슬러그로 메뉴를 찾습니다.
|
||||
*
|
||||
* @param string $slug 메뉴 슬러그
|
||||
* @return Menu|null 찾은 메뉴 모델 또는 null
|
||||
*/
|
||||
public function findBySlug(string $slug): ?Menu;
|
||||
|
||||
/**
|
||||
* 새로운 메뉴를 생성합니다.
|
||||
*
|
||||
* @param array $data 메뉴 생성 데이터
|
||||
* @return Menu 생성된 메뉴 모델
|
||||
*/
|
||||
public function create(array $data): Menu;
|
||||
|
||||
/**
|
||||
* 기존 메뉴를 업데이트합니다.
|
||||
*
|
||||
* @param Menu $menu 업데이트할 메뉴 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(Menu $menu, array $data): bool;
|
||||
|
||||
/**
|
||||
* 메뉴를 삭제합니다.
|
||||
*
|
||||
* @param Menu $menu 삭제할 메뉴 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(Menu $menu): bool;
|
||||
|
||||
/**
|
||||
* 메뉴의 순서를 업데이트합니다.
|
||||
*
|
||||
* @param array $menuOrders 메뉴 ID와 순서 매핑 배열
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function updateOrder(array $menuOrders): bool;
|
||||
|
||||
/**
|
||||
* 계층 구조를 고려한 메뉴 순서를 업데이트합니다.
|
||||
*
|
||||
* @param array $orderData 계층 구조 순서 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function updateOrderWithHierarchy(array $orderData): bool;
|
||||
|
||||
/**
|
||||
* 특정 확장에 속한 메뉴들을 조회합니다.
|
||||
*
|
||||
* @param ExtensionOwnerType $type 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return Collection 확장에 속한 메뉴 컬렉션
|
||||
*/
|
||||
public function getMenusByExtension(ExtensionOwnerType $type, string $identifier): Collection;
|
||||
|
||||
/**
|
||||
* 부모 메뉴의 자식 메뉴들을 조회합니다.
|
||||
*
|
||||
* @param int $parentId 부모 메뉴 ID
|
||||
* @return Collection 자식 메뉴 컬렉션
|
||||
*/
|
||||
public function getChildrenByParent(int $parentId): Collection;
|
||||
|
||||
/**
|
||||
* 네비게이션용 활성화된 메뉴들을 자식 메뉴와 함께 조회합니다.
|
||||
*
|
||||
* @return Collection 활성화된 메뉴 컬렉션 (자식 메뉴 포함)
|
||||
*/
|
||||
public function getActiveMenusWithChildren(): Collection;
|
||||
|
||||
/**
|
||||
* 사용자가 접근 가능한 네비게이션용 메뉴들을 조회합니다.
|
||||
*
|
||||
* @param User $user 접근 권한을 확인할 사용자
|
||||
* @return Collection 사용자가 접근 가능한 메뉴 컬렉션
|
||||
*/
|
||||
public function getAccessibleNavigationMenus(User $user): Collection;
|
||||
|
||||
/**
|
||||
* 메뉴를 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 데이터
|
||||
* @return Menu 생성 또는 업데이트된 메뉴 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): Menu;
|
||||
|
||||
/**
|
||||
* slug와 확장 정보로 메뉴를 찾습니다.
|
||||
*
|
||||
* @param string $slug 메뉴 슬러그
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @return Menu|null 찾은 메뉴 모델 또는 null
|
||||
*/
|
||||
public function findBySlugAndExtension(string $slug, ExtensionOwnerType $extensionType, string $extensionIdentifier): ?Menu;
|
||||
|
||||
/**
|
||||
* 특정 확장의 모든 메뉴를 삭제합니다.
|
||||
*
|
||||
* @param ExtensionOwnerType $type 확장 타입
|
||||
* @param string $identifier 확장 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByExtension(ExtensionOwnerType $type, string $identifier): int;
|
||||
|
||||
/**
|
||||
* 같은 부모 내에서 최대 순서 값을 조회합니다.
|
||||
*
|
||||
* @param int|null $parentId 부모 메뉴 ID (null이면 최상위)
|
||||
* @return int 최대 순서 값 (없으면 0)
|
||||
*/
|
||||
public function getMaxOrder(?int $parentId = null): int;
|
||||
|
||||
public function getFilteredTopLevelMenus(array $filters, array $activeModuleIdentifiers = [], array $activePluginIdentifiers = [], ?User $user = null): Collection;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\Module;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface ModuleRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 모듈을 조회합니다.
|
||||
*
|
||||
* @return Collection 모듈 컬렉션
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* 모든 모듈을 identifier로 키잉하여 조회합니다.
|
||||
*
|
||||
* @return Collection identifier를 키로 하는 모듈 컬렉션
|
||||
*/
|
||||
public function getAllKeyedByIdentifier(): Collection;
|
||||
|
||||
/**
|
||||
* 설치된 모든 모듈의 identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array 설치된 모듈 identifier 배열
|
||||
*/
|
||||
public function getInstalledIdentifiers(): array;
|
||||
|
||||
/**
|
||||
* 이름으로 모듈을 찾습니다.
|
||||
*
|
||||
* @param string $name 찾을 모듈 이름
|
||||
* @return Module|null 찾은 모듈 모델 또는 null
|
||||
*/
|
||||
public function findByName(string $name): ?Module;
|
||||
|
||||
/**
|
||||
* 활성화된 모듈들을 조회합니다.
|
||||
*
|
||||
* @return Collection 활성화된 모듈 컬렉션
|
||||
*/
|
||||
public function getActive(): Collection;
|
||||
|
||||
/**
|
||||
* 새로운 모듈을 생성합니다.
|
||||
*
|
||||
* @param array $data 모듈 생성 데이터
|
||||
* @return Module 생성된 모듈 모델
|
||||
*/
|
||||
public function create(array $data): Module;
|
||||
|
||||
/**
|
||||
* 모듈을 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 데이터
|
||||
* @return Module 생성 또는 업데이트된 모듈 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): Module;
|
||||
|
||||
/**
|
||||
* 기존 모듈을 업데이트합니다.
|
||||
*
|
||||
* @param Module $module 업데이트할 모듈 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(Module $module, array $data): bool;
|
||||
|
||||
/**
|
||||
* 식별자로 모듈 상태를 업데이트합니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return int 업데이트된 레코드 수
|
||||
*/
|
||||
public function updateByIdentifier(string $identifier, array $data): int;
|
||||
|
||||
/**
|
||||
* 모듈을 삭제합니다.
|
||||
*
|
||||
* @param Module $module 삭제할 모듈 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(Module $module): bool;
|
||||
|
||||
/**
|
||||
* 식별자로 모듈을 삭제합니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByIdentifier(string $identifier): int;
|
||||
|
||||
/**
|
||||
* 모듈을 활성화합니다.
|
||||
*
|
||||
* @param Module $module 활성화할 모듈 모델
|
||||
* @return bool 활성화 성공 여부
|
||||
*/
|
||||
public function activate(Module $module): bool;
|
||||
|
||||
/**
|
||||
* 모듈을 비활성화합니다.
|
||||
*
|
||||
* @param Module $module 비활성화할 모듈 모델
|
||||
* @return bool 비활성화 성공 여부
|
||||
*/
|
||||
public function deactivate(Module $module): bool;
|
||||
|
||||
/**
|
||||
* 모듈의 설치 상태를 업데이트합니다.
|
||||
*
|
||||
* @param Module $module 대상 모듈 모델
|
||||
* @param bool $installed 설치 상태 (기본값: true)
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function setInstalled(Module $module, bool $installed = true): bool;
|
||||
|
||||
/**
|
||||
* 설치된 모듈들을 조회합니다.
|
||||
*
|
||||
* @return Collection 설치된 모듈 컬렉션
|
||||
*/
|
||||
public function getInstalled(): Collection;
|
||||
|
||||
/**
|
||||
* 마켓플레이스용 모듈들을 조회합니다.
|
||||
*
|
||||
* @return Collection 공개된 모듈 컬렉션
|
||||
*/
|
||||
public function getForMarketplace(): Collection;
|
||||
|
||||
/**
|
||||
* 의존성 정보가 포함된 모든 모듈을 조회합니다.
|
||||
*
|
||||
* @return Collection 의존성 정보를 포함한 모듈 컬렉션
|
||||
*/
|
||||
public function getAllWithDependencies(): Collection;
|
||||
|
||||
/**
|
||||
* 슬러그로 모듈을 찾습니다.
|
||||
*
|
||||
* @param string $slug 모듈 슬러그
|
||||
* @return Module|null 찾은 모듈 모델 또는 null
|
||||
*/
|
||||
public function findBySlug(string $slug): ?Module;
|
||||
|
||||
/**
|
||||
* 식별자로 모듈을 찾습니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return Module|null 찾은 모듈 모델 또는 null
|
||||
*/
|
||||
public function findByIdentifier(string $identifier): ?Module;
|
||||
|
||||
/**
|
||||
* 활성화된 모듈들의 ID 목록을 반환합니다.
|
||||
*
|
||||
* @return array 활성화된 모듈 ID 배열
|
||||
*/
|
||||
public function getActiveModuleIds(): array;
|
||||
|
||||
/**
|
||||
* 활성화된 모듈들의 identifier 목록을 반환합니다.
|
||||
*
|
||||
* @return array 활성화된 모듈 identifier 배열
|
||||
*/
|
||||
public function getActiveModuleIdentifiers(): array;
|
||||
|
||||
/**
|
||||
* 식별자로 활성화된 모듈을 찾습니다.
|
||||
*
|
||||
* @param string $identifier 모듈 식별자
|
||||
* @return Module|null 찾은 모듈 모델 또는 null
|
||||
*/
|
||||
public function findActiveByIdentifier(string $identifier): ?Module;
|
||||
|
||||
/**
|
||||
* 특정 모듈에 의존하는 활성 모듈을 조회합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 의존 대상 모듈 식별자
|
||||
* @return Collection 해당 모듈에 의존하는 활성 모듈 컬렉션
|
||||
*/
|
||||
public function findActiveByModuleDependency(string $moduleIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 플러그인에 의존하는 활성 모듈을 조회합니다.
|
||||
*
|
||||
* @param string $pluginIdentifier 의존 대상 플러그인 식별자
|
||||
* @return Collection 해당 플러그인에 의존하는 활성 모듈 컬렉션
|
||||
*/
|
||||
public function findActiveByPluginDependency(string $pluginIdentifier): Collection;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\PasswordResetToken;
|
||||
|
||||
/**
|
||||
* 비밀번호 재설정 토큰 Repository 인터페이스
|
||||
*/
|
||||
interface PasswordResetTokenRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 이메일로 비밀번호 재설정 토큰을 조회합니다.
|
||||
*
|
||||
* @param string $email 사용자 이메일
|
||||
* @return PasswordResetToken|null 토큰 레코드 또는 null
|
||||
*/
|
||||
public function findByEmail(string $email): ?PasswordResetToken;
|
||||
|
||||
/**
|
||||
* 비밀번호 재설정 토큰을 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param string $email 사용자 이메일
|
||||
* @param array $data 토큰 데이터
|
||||
* @return PasswordResetToken 생성 또는 업데이트된 토큰
|
||||
*/
|
||||
public function updateOrCreateByEmail(string $email, array $data): PasswordResetToken;
|
||||
|
||||
/**
|
||||
* 비밀번호 재설정 토큰을 삭제합니다.
|
||||
*
|
||||
* @param PasswordResetToken $token 삭제할 토큰
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(PasswordResetToken $token): bool;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface PermissionRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 권한을 조회합니다.
|
||||
*
|
||||
* @return Collection 권한 컬렉션
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* ID로 권한을 찾습니다.
|
||||
*
|
||||
* @param int $id 권한 ID
|
||||
* @return Permission|null 찾은 권한 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?Permission;
|
||||
|
||||
/**
|
||||
* 식별자로 권한을 찾습니다.
|
||||
*
|
||||
* @param string $identifier 권한 식별자
|
||||
* @return Permission|null 찾은 권한 모델 또는 null
|
||||
*/
|
||||
public function findByIdentifier(string $identifier): ?Permission;
|
||||
|
||||
/**
|
||||
* 새로운 권한을 생성합니다.
|
||||
*
|
||||
* @param array $data 권한 생성 데이터
|
||||
* @return Permission 생성된 권한 모델
|
||||
*/
|
||||
public function create(array $data): Permission;
|
||||
|
||||
/**
|
||||
* 권한을 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 데이터
|
||||
* @return Permission 생성 또는 업데이트된 권한 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): Permission;
|
||||
|
||||
/**
|
||||
* 기존 권한을 업데이트합니다.
|
||||
*
|
||||
* @param Permission $permission 업데이트할 권한 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(Permission $permission, array $data): bool;
|
||||
|
||||
/**
|
||||
* 권한을 삭제합니다.
|
||||
*
|
||||
* @param Permission $permission 삭제할 권한 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(Permission $permission): bool;
|
||||
|
||||
/**
|
||||
* 특정 확장의 모든 권한을 조회합니다.
|
||||
*
|
||||
* @param ExtensionOwnerType $type 확장 타입
|
||||
* @param string|null $identifier 확장 식별자
|
||||
* @return Collection 확장에 속한 권한 컬렉션
|
||||
*/
|
||||
public function getByExtension(ExtensionOwnerType $type, ?string $identifier = null): Collection;
|
||||
|
||||
/**
|
||||
* 특정 확장의 모든 권한을 삭제합니다.
|
||||
*
|
||||
* @param ExtensionOwnerType $type 확장 타입
|
||||
* @param string|null $identifier 확장 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByExtension(ExtensionOwnerType $type, ?string $identifier = null): int;
|
||||
|
||||
/**
|
||||
* 코어 권한들을 조회합니다.
|
||||
*
|
||||
* @return Collection 코어 권한 컬렉션
|
||||
*/
|
||||
public function getCorePermissions(): Collection;
|
||||
|
||||
/**
|
||||
* 최상위 권한(루트)을 모든 자식과 함께 조회합니다.
|
||||
*
|
||||
* @return Collection 루트 권한 컬렉션 (allChildren 관계 포함)
|
||||
*/
|
||||
public function getRootsWithChildren(): Collection;
|
||||
|
||||
/**
|
||||
* 할당 가능한 권한 ID 목록을 반환합니다. (리프 노드만)
|
||||
*
|
||||
* @return array 할당 가능한 권한 ID 배열
|
||||
*/
|
||||
public function getAssignableIds(): array;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\Plugin;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface PluginRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 플러그인을 조회합니다.
|
||||
*
|
||||
* @return Collection 플러그인 컬렉션
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* 이름으로 플러그인을 찾습니다.
|
||||
*
|
||||
* @param string $name 찾을 플러그인 이름
|
||||
* @return Plugin|null 찾은 플러그인 모델 또는 null
|
||||
*/
|
||||
public function findByName(string $name): ?Plugin;
|
||||
|
||||
/**
|
||||
* 활성화된 플러그인들을 조회합니다.
|
||||
*
|
||||
* @return Collection 활성화된 플러그인 컬렉션
|
||||
*/
|
||||
public function getActive(): Collection;
|
||||
|
||||
/**
|
||||
* 새로운 플러그인을 생성합니다.
|
||||
*
|
||||
* @param array $data 플러그인 생성 데이터
|
||||
* @return Plugin 생성된 플러그인 모델
|
||||
*/
|
||||
public function create(array $data): Plugin;
|
||||
|
||||
/**
|
||||
* 기존 플러그인을 업데이트합니다.
|
||||
*
|
||||
* @param Plugin $plugin 업데이트할 플러그인 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(Plugin $plugin, array $data): bool;
|
||||
|
||||
/**
|
||||
* 플러그인을 삭제합니다.
|
||||
*
|
||||
* @param Plugin $plugin 삭제할 플러그인 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(Plugin $plugin): bool;
|
||||
|
||||
/**
|
||||
* 플러그인을 활성화합니다.
|
||||
*
|
||||
* @param Plugin $plugin 활성화할 플러그인 모델
|
||||
* @return bool 활성화 성공 여부
|
||||
*/
|
||||
public function activate(Plugin $plugin): bool;
|
||||
|
||||
/**
|
||||
* 플러그인을 비활성화합니다.
|
||||
*
|
||||
* @param Plugin $plugin 비활성화할 플러그인 모델
|
||||
* @return bool 비활성화 성공 여부
|
||||
*/
|
||||
public function deactivate(Plugin $plugin): bool;
|
||||
|
||||
/**
|
||||
* 플러그인의 설치 상태를 업데이트합니다.
|
||||
*
|
||||
* @param Plugin $plugin 대상 플러그인 모델
|
||||
* @param bool $installed 설치 상태 (기본값: true)
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function setInstalled(Plugin $plugin, bool $installed = true): bool;
|
||||
|
||||
/**
|
||||
* 식별자로 플러그인을 찾습니다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return Plugin|null 찾은 플러그인 모델 또는 null
|
||||
*/
|
||||
public function findByIdentifier(string $identifier): ?Plugin;
|
||||
|
||||
/**
|
||||
* 식별자로 활성화된 플러그인을 찾습니다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return Plugin|null 찾은 플러그인 모델 또는 null
|
||||
*/
|
||||
public function findActiveByIdentifier(string $identifier): ?Plugin;
|
||||
|
||||
/**
|
||||
* 플러그인을 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 데이터
|
||||
* @return Plugin 생성 또는 업데이트된 플러그인 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): Plugin;
|
||||
|
||||
/**
|
||||
* 식별자로 플러그인 상태를 업데이트합니다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return int 업데이트된 레코드 수
|
||||
*/
|
||||
public function updateByIdentifier(string $identifier, array $data): int;
|
||||
|
||||
/**
|
||||
* 식별자로 플러그인을 삭제합니다.
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByIdentifier(string $identifier): int;
|
||||
|
||||
/**
|
||||
* 모든 플러그인을 identifier로 키잉하여 조회합니다.
|
||||
*
|
||||
* @return Collection identifier를 키로 하는 플러그인 컬렉션
|
||||
*/
|
||||
public function getAllKeyedByIdentifier(): Collection;
|
||||
|
||||
/**
|
||||
* 설치된 모든 플러그인의 identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array 설치된 플러그인 identifier 배열
|
||||
*/
|
||||
public function getInstalledIdentifiers(): array;
|
||||
|
||||
/**
|
||||
* 특정 모듈에 의존하는 활성 플러그인을 조회합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 의존 대상 모듈 식별자
|
||||
* @return Collection 해당 모듈에 의존하는 활성 플러그인 컬렉션
|
||||
*/
|
||||
public function findActiveByModuleDependency(string $moduleIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 플러그인에 의존하는 활성 플러그인을 조회합니다.
|
||||
*
|
||||
* @param string $pluginIdentifier 의존 대상 플러그인 식별자
|
||||
* @return Collection 해당 플러그인에 의존하는 활성 플러그인 컬렉션
|
||||
*/
|
||||
public function findActiveByPluginDependency(string $pluginIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 활성화된 플러그인들의 identifier 목록을 반환합니다.
|
||||
*
|
||||
* @return array 활성화된 플러그인 identifier 배열
|
||||
*/
|
||||
public function getActivePluginIdentifiers(): array;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface RoleRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 역할을 조회합니다.
|
||||
*
|
||||
* @return Collection 역할 컬렉션
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* 활성화된 역할들만 조회합니다.
|
||||
*
|
||||
* @return Collection 활성화된 역할 컬렉션
|
||||
*/
|
||||
public function getActiveRoles(): Collection;
|
||||
|
||||
/**
|
||||
* ID로 역할을 찾습니다.
|
||||
*
|
||||
* @param int $id 역할 ID
|
||||
* @return Role|null 찾은 역할 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?Role;
|
||||
|
||||
/**
|
||||
* 식별자로 역할을 찾습니다.
|
||||
*
|
||||
* @param string $identifier 역할 식별자
|
||||
* @return Role|null 찾은 역할 모델 또는 null
|
||||
*/
|
||||
public function findByIdentifier(string $identifier): ?Role;
|
||||
|
||||
/**
|
||||
* 새로운 역할을 생성합니다.
|
||||
*
|
||||
* @param array $data 역할 생성 데이터
|
||||
* @return Role 생성된 역할 모델
|
||||
*/
|
||||
public function create(array $data): Role;
|
||||
|
||||
/**
|
||||
* 역할을 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 데이터
|
||||
* @return Role 생성 또는 업데이트된 역할 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): Role;
|
||||
|
||||
/**
|
||||
* 기존 역할을 업데이트합니다.
|
||||
*
|
||||
* @param Role $role 업데이트할 역할 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(Role $role, array $data): bool;
|
||||
|
||||
/**
|
||||
* 역할을 삭제합니다.
|
||||
*
|
||||
* @param Role $role 삭제할 역할 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(Role $role): bool;
|
||||
|
||||
/**
|
||||
* 확장이 소유한 역할을 식별자로 찾습니다.
|
||||
*
|
||||
* @param string $identifier 역할 식별자
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @return Role|null 찾은 역할 모델 또는 null
|
||||
*/
|
||||
public function findExtensionRoleByIdentifier(string $identifier, ExtensionOwnerType $extensionType, string $extensionIdentifier): ?Role;
|
||||
|
||||
/**
|
||||
* 역할에 권한을 할당합니다.
|
||||
*
|
||||
* @param Role $role 역할 모델
|
||||
* @param int $permissionId 권한 ID
|
||||
* @param array $pivotData 피벗 테이블에 저장할 추가 데이터
|
||||
*/
|
||||
public function attachPermission(Role $role, int $permissionId, array $pivotData = []): void;
|
||||
|
||||
/**
|
||||
* 역할에서 권한을 해제합니다.
|
||||
*
|
||||
* @param Role $role 역할 모델
|
||||
* @param int $permissionId 권한 ID
|
||||
* @return int 해제된 권한 수
|
||||
*/
|
||||
public function detachPermission(Role $role, int $permissionId): int;
|
||||
|
||||
/**
|
||||
* 역할의 모든 권한을 해제합니다.
|
||||
*
|
||||
* @param Role $role 역할 모델
|
||||
* @return int 해제된 권한 수
|
||||
*/
|
||||
public function detachAllPermissions(Role $role): int;
|
||||
|
||||
/**
|
||||
* 역할 목록을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @return LengthAwarePaginator 페이지네이션된 역할 목록
|
||||
*/
|
||||
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 역할에 할당된 권한 개수를 반환합니다.
|
||||
*
|
||||
* @param Role $role 역할 모델
|
||||
* @return int 권한 개수
|
||||
*/
|
||||
public function getPermissionCount(Role $role): int;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\ScheduleHistory;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface ScheduleHistoryRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* ID로 실행 이력을 찾습니다.
|
||||
*
|
||||
* @param int $id 이력 ID
|
||||
* @return ScheduleHistory|null 찾은 이력 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?ScheduleHistory;
|
||||
|
||||
/**
|
||||
* 새로운 실행 이력을 생성합니다.
|
||||
*
|
||||
* @param array $data 이력 생성 데이터
|
||||
* @return ScheduleHistory 생성된 이력 모델
|
||||
*/
|
||||
public function create(array $data): ScheduleHistory;
|
||||
|
||||
/**
|
||||
* 기존 실행 이력을 업데이트합니다.
|
||||
*
|
||||
* @param ScheduleHistory $history 업데이트할 이력 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(ScheduleHistory $history, array $data): bool;
|
||||
|
||||
/**
|
||||
* 실행 이력을 삭제합니다.
|
||||
*
|
||||
* @param ScheduleHistory $history 삭제할 이력 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(ScheduleHistory $history): bool;
|
||||
|
||||
/**
|
||||
* 특정 스케줄의 실행 이력을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param int $scheduleId 스케줄 ID
|
||||
* @param array $filters 필터 조건 배열
|
||||
* @return LengthAwarePaginator 페이지네이션된 이력 목록
|
||||
*/
|
||||
public function getPaginatedByScheduleId(int $scheduleId, array $filters = []): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 특정 스케줄의 최근 실행 이력을 조회합니다.
|
||||
*
|
||||
* @param int $scheduleId 스케줄 ID
|
||||
* @param int $limit 조회 개수
|
||||
* @return Collection 최근 이력 컬렉션
|
||||
*/
|
||||
public function getRecentByScheduleId(int $scheduleId, int $limit = 10): Collection;
|
||||
|
||||
/**
|
||||
* 여러 이력을 일괄 삭제합니다.
|
||||
*
|
||||
* @param array $ids 이력 ID 배열
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function bulkDelete(array $ids): int;
|
||||
|
||||
/**
|
||||
* 특정 스케줄의 모든 이력을 삭제합니다.
|
||||
*
|
||||
* @param int $scheduleId 스케줄 ID
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByScheduleId(int $scheduleId): int;
|
||||
|
||||
/**
|
||||
* 특정 기간 이전의 이력을 삭제합니다.
|
||||
*
|
||||
* @param int $days 보관 기간 (일)
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteOlderThan(int $days): int;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\Schedule;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface ScheduleRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* ID로 스케줄을 찾습니다.
|
||||
*
|
||||
* @param int $id 스케줄 ID
|
||||
* @return Schedule|null 찾은 스케줄 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?Schedule;
|
||||
|
||||
/**
|
||||
* 새로운 스케줄을 생성합니다.
|
||||
*
|
||||
* @param array $data 스케줄 생성 데이터
|
||||
* @return Schedule 생성된 스케줄 모델
|
||||
*/
|
||||
public function create(array $data): Schedule;
|
||||
|
||||
/**
|
||||
* 기존 스케줄을 업데이트합니다.
|
||||
*
|
||||
* @param Schedule $schedule 업데이트할 스케줄 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(Schedule $schedule, array $data): bool;
|
||||
|
||||
/**
|
||||
* 스케줄을 삭제합니다.
|
||||
*
|
||||
* @param Schedule $schedule 삭제할 스케줄 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(Schedule $schedule): bool;
|
||||
|
||||
/**
|
||||
* 모든 스케줄을 조회합니다.
|
||||
*
|
||||
* @return Collection 스케줄 컬렉션
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* 필터링 및 페이지네이션이 적용된 스케줄 목록을 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건 배열
|
||||
* @return LengthAwarePaginator 페이지네이션된 스케줄 목록
|
||||
*/
|
||||
public function getPaginatedSchedules(array $filters = []): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 스케줄 관련 통계 정보를 조회합니다.
|
||||
*
|
||||
* @return array 스케줄 통계 데이터 배열
|
||||
*/
|
||||
public function getStatistics(): array;
|
||||
|
||||
/**
|
||||
* 활성화된 스케줄들을 조회합니다.
|
||||
*
|
||||
* @return Collection 활성화된 스케줄 컬렉션
|
||||
*/
|
||||
public function getActiveSchedules(): Collection;
|
||||
|
||||
/**
|
||||
* 실행 대기 중인 스케줄들을 조회합니다.
|
||||
*
|
||||
* @return Collection 실행 대기 중인 스케줄 컬렉션
|
||||
*/
|
||||
public function getDueSchedules(): Collection;
|
||||
|
||||
/**
|
||||
* 여러 스케줄의 상태를 일괄 업데이트합니다.
|
||||
*
|
||||
* @param array $ids 스케줄 ID 배열
|
||||
* @param bool $isActive 활성화 여부
|
||||
* @return int 업데이트된 레코드 수
|
||||
*/
|
||||
public function bulkUpdateStatus(array $ids, bool $isActive): int;
|
||||
|
||||
/**
|
||||
* 여러 스케줄을 일괄 삭제합니다.
|
||||
*
|
||||
* @param array $ids 스케줄 ID 배열
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function bulkDelete(array $ids): int;
|
||||
|
||||
/**
|
||||
* 스케줄을 복제합니다.
|
||||
*
|
||||
* @param Schedule $schedule 복제할 스케줄
|
||||
* @return Schedule 복제된 스케줄
|
||||
*/
|
||||
public function duplicate(Schedule $schedule): Schedule;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\SystemConfig;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface SystemConfigRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 시스템 설정을 조회합니다.
|
||||
*
|
||||
* @return Collection 시스템 설정 컬렉션
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* 키로 시스템 설정을 찾습니다.
|
||||
*
|
||||
* @param string $key 설정 키
|
||||
* @return SystemConfig|null 찾은 설정 모델 또는 null
|
||||
*/
|
||||
public function findByKey(string $key): ?SystemConfig;
|
||||
|
||||
/**
|
||||
* 새로운 시스템 설정을 생성합니다.
|
||||
*
|
||||
* @param array $data 설정 생성 데이터
|
||||
* @return SystemConfig 생성된 설정 모델
|
||||
*/
|
||||
public function create(array $data): SystemConfig;
|
||||
|
||||
/**
|
||||
* 기존 시스템 설정을 업데이트합니다.
|
||||
*
|
||||
* @param SystemConfig $config 업데이트할 설정 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(SystemConfig $config, array $data): bool;
|
||||
|
||||
/**
|
||||
* 시스템 설정을 삭제합니다.
|
||||
*
|
||||
* @param SystemConfig $config 삭제할 설정 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(SystemConfig $config): bool;
|
||||
|
||||
/**
|
||||
* 키로 시스템 설정을 삭제합니다.
|
||||
*
|
||||
* @param string $key 삭제할 설정 키
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function deleteByKey(string $key): bool;
|
||||
|
||||
/**
|
||||
* 주어진 키의 시스템 설정 존재 여부를 확인합니다.
|
||||
*
|
||||
* @param string $key 확인할 설정 키
|
||||
* @return bool 설정 존재 여부
|
||||
*/
|
||||
public function exists(string $key): bool;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\Template;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface TemplateRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 모든 템플릿 조회
|
||||
*
|
||||
* @param string|null $type 템플릿 타입 필터
|
||||
* @return Collection 템플릿 컬렉션
|
||||
*/
|
||||
public function getAll(?string $type = null): Collection;
|
||||
|
||||
/**
|
||||
* ID로 템플릿 조회
|
||||
*
|
||||
* @param int $id 템플릿 ID
|
||||
* @return Template|null 찾은 템플릿 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?Template;
|
||||
|
||||
/**
|
||||
* identifier로 템플릿 조회
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return Template|null 찾은 템플릿 모델 또는 null
|
||||
*/
|
||||
public function findByIdentifier(string $identifier): ?Template;
|
||||
|
||||
/**
|
||||
* 타입별 활성화된 템플릿 조회
|
||||
*
|
||||
* @param string $type 템플릿 타입
|
||||
* @return Template|null 찾은 템플릿 모델 또는 null
|
||||
*/
|
||||
public function findActiveByType(string $type): ?Template;
|
||||
|
||||
/**
|
||||
* 템플릿 업데이트
|
||||
*
|
||||
* @param int $id 템플릿 ID
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return Template 업데이트된 템플릿 모델
|
||||
*/
|
||||
public function update(int $id, array $data): Template;
|
||||
|
||||
/**
|
||||
* 템플릿 삭제 (Soft Delete)
|
||||
*
|
||||
* @param int $id 템플릿 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(int $id): bool;
|
||||
|
||||
/**
|
||||
* 특정 타입의 활성화된 모든 템플릿을 조회합니다.
|
||||
*
|
||||
* @param string $type 템플릿 타입 (admin, user 등)
|
||||
* @return Collection 활성화된 템플릿 컬렉션
|
||||
*/
|
||||
public function getActiveByType(string $type): Collection;
|
||||
|
||||
/**
|
||||
* 모든 활성화된 템플릿을 조회합니다.
|
||||
*
|
||||
* @return Collection 모든 활성화된 템플릿 컬렉션
|
||||
*/
|
||||
public function getActive(): Collection;
|
||||
|
||||
/**
|
||||
* 모든 템플릿을 identifier로 키잉하여 조회합니다.
|
||||
*
|
||||
* @return Collection identifier를 키로 하는 템플릿 컬렉션
|
||||
*/
|
||||
public function getAllKeyedByIdentifier(): Collection;
|
||||
|
||||
/**
|
||||
* 설치된 모든 템플릿의 identifier 목록을 조회합니다.
|
||||
*
|
||||
* @return array 설치된 템플릿 identifier 배열
|
||||
*/
|
||||
public function getInstalledIdentifiers(): array;
|
||||
|
||||
/**
|
||||
* 템플릿을 생성하거나 업데이트합니다.
|
||||
*
|
||||
* @param array $attributes 조회 조건
|
||||
* @param array $values 생성/업데이트할 데이터
|
||||
* @return Template 생성 또는 업데이트된 템플릿 모델
|
||||
*/
|
||||
public function updateOrCreate(array $attributes, array $values): Template;
|
||||
|
||||
/**
|
||||
* 식별자로 템플릿 상태를 업데이트합니다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return int 업데이트된 레코드 수
|
||||
*/
|
||||
public function updateByIdentifier(string $identifier, array $data): int;
|
||||
|
||||
/**
|
||||
* 식별자로 템플릿을 삭제합니다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @return int 삭제된 레코드 수
|
||||
*/
|
||||
public function deleteByIdentifier(string $identifier): int;
|
||||
|
||||
/**
|
||||
* 특정 모듈에 의존하는 활성 템플릿을 조회합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자
|
||||
* @return Collection 해당 모듈에 의존하는 활성 템플릿 컬렉션
|
||||
*/
|
||||
public function findActiveByModuleDependency(string $moduleIdentifier): Collection;
|
||||
|
||||
/**
|
||||
* 특정 플러그인에 의존하는 활성 템플릿을 조회합니다.
|
||||
*
|
||||
* @param string $pluginIdentifier 플러그인 식별자
|
||||
* @return Collection 해당 플러그인에 의존하는 활성 템플릿 컬렉션
|
||||
*/
|
||||
public function findActiveByPluginDependency(string $pluginIdentifier): Collection;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\UserConsent;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface UserConsentRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 새로운 동의 이력을 기록합니다.
|
||||
*
|
||||
* @param array $data 동의 데이터 (user_id, consent_type, page_id, version, agreed_at, ip_address)
|
||||
* @return UserConsent 생성된 동의 이력 모델
|
||||
*/
|
||||
public function record(array $data): UserConsent;
|
||||
|
||||
/**
|
||||
* 특정 사용자의 모든 동의 이력을 조회합니다 (최신순).
|
||||
*
|
||||
* @param int $userId 사용자 ID
|
||||
* @return Collection 동의 이력 컬렉션
|
||||
*/
|
||||
public function getByUser(int $userId): Collection;
|
||||
|
||||
/**
|
||||
* 특정 사용자의 특정 유형 최신 동의 이력을 조회합니다.
|
||||
*
|
||||
* @param int $userId 사용자 ID
|
||||
* @param string $consentType 동의 유형 (ConsentType 값)
|
||||
* @return UserConsent|null 최신 동의 이력 또는 null
|
||||
*/
|
||||
public function getLatestByType(int $userId, string $consentType): ?UserConsent;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
interface UserRepositoryInterface
|
||||
{
|
||||
/**
|
||||
* 이메일로 사용자를 찾습니다.
|
||||
*
|
||||
* @param string $email 찾을 사용자의 이메일
|
||||
* @return User|null 찾은 사용자 모델 또는 null
|
||||
*/
|
||||
public function findByEmail(string $email): ?User;
|
||||
|
||||
/**
|
||||
* 새로운 사용자를 생성합니다.
|
||||
*
|
||||
* @param array $data 사용자 생성 데이터
|
||||
* @return User 생성된 사용자 모델
|
||||
*/
|
||||
public function create(array $data): User;
|
||||
|
||||
/**
|
||||
* 기존 사용자를 업데이트합니다.
|
||||
*
|
||||
* @param User $user 업데이트할 사용자 모델
|
||||
* @param array $data 업데이트할 데이터
|
||||
* @return bool 업데이트 성공 여부
|
||||
*/
|
||||
public function update(User $user, array $data): bool;
|
||||
|
||||
/**
|
||||
* 사용자를 삭제합니다.
|
||||
*
|
||||
* @param User $user 삭제할 사용자 모델
|
||||
* @return bool 삭제 성공 여부
|
||||
*/
|
||||
public function delete(User $user): bool;
|
||||
|
||||
/**
|
||||
* 모든 사용자를 조회합니다.
|
||||
*
|
||||
* @return Collection 사용자 컬렉션
|
||||
*/
|
||||
public function getAll(): Collection;
|
||||
|
||||
/**
|
||||
* ID로 사용자를 찾습니다.
|
||||
*
|
||||
* @param int $id 사용자 ID
|
||||
* @return User|null 찾은 사용자 모델 또는 null
|
||||
*/
|
||||
public function findById(int $id): ?User;
|
||||
|
||||
/**
|
||||
* 필터링 및 페이지네이션이 적용된 사용자 목록을 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건 배열
|
||||
* @return LengthAwarePaginator 페이지네이션된 사용자 목록
|
||||
*/
|
||||
public function getPaginatedUsers(array $filters = []): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 사용자 관련 통계 정보를 조회합니다.
|
||||
*
|
||||
* @return array 사용자 통계 데이터 배열
|
||||
*/
|
||||
public function getStatistics(): array;
|
||||
|
||||
/**
|
||||
* 키워드로 사용자를 검색합니다. (이름, 닉네임, 이메일)
|
||||
*
|
||||
* @param string $keyword 검색할 키워드
|
||||
* @return Collection 검색된 사용자 컬렉션
|
||||
*/
|
||||
public function searchByKeyword(string $keyword): Collection;
|
||||
|
||||
/**
|
||||
* 최근 등록된 사용자들을 조회합니다.
|
||||
*
|
||||
* @param int $limit 조회할 사용자 수 (기본값: 10)
|
||||
* @return Collection 최근 사용자 컬렉션
|
||||
*/
|
||||
public function getRecentUsers(int $limit = 10): Collection;
|
||||
|
||||
/**
|
||||
* 언어별 사용자 수를 조회합니다.
|
||||
*
|
||||
* @return array 언어별 사용자 수 배열
|
||||
*/
|
||||
public function getUsersByLanguage(): array;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts;
|
||||
|
||||
/**
|
||||
* 코어 고유 ID 생성 서비스 인터페이스
|
||||
*
|
||||
* UUID v7 및 NanoID 생성 기능을 제공합니다.
|
||||
*/
|
||||
interface UniqueIdServiceInterface
|
||||
{
|
||||
/**
|
||||
* UUID v7을 생성합니다.
|
||||
*
|
||||
* 시간 기반 정렬 가능한 UUID를 반환합니다.
|
||||
*
|
||||
* @return string UUID v7 문자열 (36자)
|
||||
*/
|
||||
public function generateUuid(): string;
|
||||
|
||||
/**
|
||||
* NanoID를 생성합니다.
|
||||
*
|
||||
* 암호학적으로 안전한 랜덤 문자열을 반환합니다.
|
||||
* Rejection sampling으로 모듈로 편향을 방지합니다.
|
||||
*
|
||||
* @param int $length 생성할 문자열 길이
|
||||
* @param string|null $alphabet 사용할 문자 집합 (null이면 기본 알파벳)
|
||||
* @return string 생성된 NanoID
|
||||
*/
|
||||
public function generateNanoId(int $length = 16, ?string $alphabet = null): string;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 활동 로그 유형 Enum
|
||||
*
|
||||
* 활동 로그의 유형을 정의합니다.
|
||||
*/
|
||||
enum ActivityLogType: string
|
||||
{
|
||||
/**
|
||||
* 관리자 활동
|
||||
*/
|
||||
case Admin = 'admin';
|
||||
|
||||
/**
|
||||
* 사용자 활동
|
||||
*/
|
||||
case User = 'user';
|
||||
|
||||
/**
|
||||
* 시스템 활동
|
||||
*/
|
||||
case System = 'system';
|
||||
|
||||
/**
|
||||
* 모든 유형 값을 문자열 배열로 반환합니다.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 유형 값인지 확인합니다.
|
||||
*
|
||||
* @param string $value 검증할 유형 값
|
||||
* @return bool 유효 여부
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 유형의 다국어 라벨을 반환합니다.
|
||||
*
|
||||
* @return string 번역된 유형 라벨
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return __('activity_log.type.' . $this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 유형별 CSS 클래스(variant)를 반환합니다.
|
||||
*
|
||||
* @return string 스타일 variant
|
||||
*/
|
||||
public function variant(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Admin => 'blue',
|
||||
self::User => 'green',
|
||||
self::System => 'gray',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 첨부파일 소스 타입 Enum
|
||||
*
|
||||
* 첨부파일이 어디서 생성되었는지 구분합니다.
|
||||
*/
|
||||
enum AttachmentSourceType: string
|
||||
{
|
||||
/** 코어 시스템에서 생성된 첨부파일 */
|
||||
case Core = 'core';
|
||||
|
||||
/** 모듈에서 생성된 첨부파일 */
|
||||
case Module = 'module';
|
||||
|
||||
/** 플러그인에서 생성된 첨부파일 */
|
||||
case Plugin = 'plugin';
|
||||
|
||||
/**
|
||||
* 모든 값 배열 반환
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 값이 유효한지 확인
|
||||
*
|
||||
* @param string $value 확인할 값
|
||||
* @return bool 유효 여부
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 라벨 반환
|
||||
*
|
||||
* @return string 다국어 라벨
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Core => __('attachment.source_type.core'),
|
||||
self::Module => __('attachment.source_type.module'),
|
||||
self::Plugin => __('attachment.source_type.plugin'),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
|
||||
/**
|
||||
* 약관 동의 유형 Enum
|
||||
*
|
||||
* 사용자 동의 유형을 정의합니다.
|
||||
* 플러그인은 core.consent.allowed_types 훅으로 추가 유형을 등록할 수 있습니다.
|
||||
*/
|
||||
enum ConsentType: string
|
||||
{
|
||||
/**
|
||||
* 이용약관 동의
|
||||
*/
|
||||
case Terms = 'terms';
|
||||
|
||||
/**
|
||||
* 개인정보처리방침 동의
|
||||
*/
|
||||
case Privacy = 'privacy';
|
||||
|
||||
/**
|
||||
* 모든 유형 값을 문자열 배열로 반환합니다.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 유형 값인지 확인합니다.
|
||||
*
|
||||
* @param string $value 검증할 유형 값
|
||||
* @return bool 유효 여부
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 유형의 다국어 라벨을 반환합니다.
|
||||
*
|
||||
* @return string 번역된 유형 라벨
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return __('consent.type.'.$this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 확장을 포함한 허용 동의 유형 목록을 반환합니다.
|
||||
*
|
||||
* core.consent.allowed_types 필터 훅을 통해 플러그인에서 추가 유형을 등록할 수 있습니다.
|
||||
*
|
||||
* @return array<string> 허용된 동의 유형 값 배열
|
||||
*/
|
||||
public static function allowedTypes(): array
|
||||
{
|
||||
return HookManager::applyFilters('core.consent.allowed_types', self::values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 확장 소유권 타입 Enum
|
||||
*
|
||||
* 권한, 역할, 메뉴, 스케줄 등의 엔티티를 생성한 확장의 유형을 구분합니다.
|
||||
*/
|
||||
enum ExtensionOwnerType: string
|
||||
{
|
||||
/** 코어 시스템에서 생성 */
|
||||
case Core = 'core';
|
||||
|
||||
/** 모듈에서 생성 */
|
||||
case Module = 'module';
|
||||
|
||||
/** 플러그인에서 생성 */
|
||||
case Plugin = 'plugin';
|
||||
|
||||
/**
|
||||
* 모든 값 배열 반환
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 값이 유효한지 확인
|
||||
*
|
||||
* @param string $value 확인할 값
|
||||
* @return bool 유효 여부
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 라벨 반환
|
||||
*
|
||||
* @return string 다국어 라벨
|
||||
*/
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Core => __('extension_owner_type.core'),
|
||||
self::Module => __('extension_owner_type.module'),
|
||||
self::Plugin => __('extension_owner_type.plugin'),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 확장(모듈, 플러그인, 템플릿) 상태 Enum
|
||||
*
|
||||
* 모듈, 플러그인, 템플릿에서 공통으로 사용하는 상태 값을 정의합니다.
|
||||
*/
|
||||
enum ExtensionStatus: string
|
||||
{
|
||||
/**
|
||||
* 활성화됨
|
||||
*/
|
||||
case Active = 'active';
|
||||
|
||||
/**
|
||||
* 비활성화됨
|
||||
*/
|
||||
case Inactive = 'inactive';
|
||||
|
||||
/**
|
||||
* 설치 중
|
||||
*/
|
||||
case Installing = 'installing';
|
||||
|
||||
/**
|
||||
* 제거 중
|
||||
*/
|
||||
case Uninstalling = 'uninstalling';
|
||||
|
||||
/**
|
||||
* 미설치 또는 삭제됨
|
||||
*/
|
||||
case Uninstalled = 'uninstalled';
|
||||
|
||||
/**
|
||||
* 업데이트 중
|
||||
*/
|
||||
case Updating = 'updating';
|
||||
|
||||
/**
|
||||
* 모든 상태 값을 문자열 배열로 반환
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 상태 값인지 확인
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 레이아웃 확장 타입 Enum
|
||||
*
|
||||
* 확장이 적용되는 방식을 구분합니다.
|
||||
*/
|
||||
enum LayoutExtensionType: string
|
||||
{
|
||||
/**
|
||||
* Extension Point 방식
|
||||
* 템플릿에서 명시적으로 정의한 확장점에 컴포넌트 주입
|
||||
*/
|
||||
case ExtensionPoint = 'extension_point';
|
||||
|
||||
/**
|
||||
* Overlay 방식
|
||||
* 기존 레이아웃의 특정 컴포넌트 ID를 타겟으로 주입
|
||||
*/
|
||||
case Overlay = 'overlay';
|
||||
|
||||
/**
|
||||
* 모든 확장 타입 값을 문자열 배열로 반환
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 확장 타입 값인지 확인
|
||||
*
|
||||
* @param string $value 확인할 값
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* 레이아웃 소스 타입 Enum
|
||||
*
|
||||
* 레이아웃이 제공되는 출처를 구분합니다.
|
||||
*/
|
||||
enum LayoutSourceType: string
|
||||
{
|
||||
/**
|
||||
* 템플릿에서 제공하는 레이아웃
|
||||
*/
|
||||
case Template = 'template';
|
||||
|
||||
/**
|
||||
* 모듈에서 제공하는 레이아웃
|
||||
*/
|
||||
case Module = 'module';
|
||||
|
||||
/**
|
||||
* 플러그인에서 제공하는 레이아웃
|
||||
*/
|
||||
case Plugin = 'plugin';
|
||||
|
||||
/**
|
||||
* 모든 소스 타입 값을 문자열 배열로 반환
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효한 소스 타입 값인지 확인
|
||||
*/
|
||||
public static function isValid(string $value): bool
|
||||
{
|
||||
return in_array($value, self::values(), true);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 3967 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user