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,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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user