v7.0.0-beta.4 release

This commit is contained in:
HeuJung committed 2026-05-11 11:29:41 +09:00
1 parent 05db17887d
commit 1db039ff34
1545 files changed
+136783 -11634

No files matched your search

@@ -0,0 +1,15 @@
# Changelog
이 프로젝트의 모든 주요 변경사항을 기록합니다.
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [0.1.0-beta.1] - 2026-05-11
### Added
- Hello 학습용 샘플 플러그인 초기 구현
- Hello 모듈의 `gnuboard7-hello_module.memo.created` Action 훅 구독 및 로그 기록 데모
- Filter 훅 구독 패턴(`type: 'filter'`) 시연용 `FilterMemoTitleListener`
- 플러그인 자체 훅 발행 데모: `gnuboard7-hello_plugin.log.written`
- 최소 설정 UI (`log_enabled` 토글) + 다국어(ko/en)
@@ -0,0 +1,14 @@
{
"name": "plugins/gnuboard7-hello_plugin",
"description": "Learning minimal sample plugin for Gnuboard7 platform (consumes Hello module hooks)",
"type": "library",
"version": "0.1.0-beta.1",
"autoload": {
"psr-4": {
"Plugins\\Gnuboard7\\HelloPlugin\\": ["src/", "./"]
}
},
"require": {
"php": "^8.2"
}
}
@@ -0,0 +1,12 @@
{
"_meta": {
"version": "1.0.0",
"description": "Hello 학습용 샘플 플러그인 환경설정"
},
"defaults": {
"log_enabled": true
},
"frontend_schema": {
"log_enabled": { "expose": true }
}
}
@@ -0,0 +1,22 @@
{
"identifier": "gnuboard7-hello_plugin",
"vendor": "gnuboard7",
"name": {
"ko": "Hello 플러그인",
"en": "Hello Plugin"
},
"version": "0.1.0-beta.1",
"license": "MIT",
"description": {
"ko": "학습용 최소 샘플 플러그인 (Hello 모듈 훅 소비)",
"en": "Learning minimal sample plugin (consumes Hello module hooks)"
},
"g7_version": ">=7.0.0-beta.4",
"hidden": true,
"dependencies": {
"modules": {
"gnuboard7-hello_module": ">=0.1.0"
},
"plugins": {}
}
}
@@ -0,0 +1,90 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin;
use App\Extension\AbstractPlugin;
use Plugins\Gnuboard7\HelloPlugin\Listeners\FilterMemoTitleListener;
use Plugins\Gnuboard7\HelloPlugin\Listeners\LogMemoCreatedListener;
/**
* Hello 학습용 샘플 플러그인
*
* `gnuboard7-hello_module` 이 발행하는 훅을 구독해 동작하는 최소 샘플입니다.
* manifest `hidden: true` 로 관리자 UI 에서 숨겨집니다.
*/
class Plugin extends AbstractPlugin
{
/**
* 훅 리스너 목록 반환
*
* @return array<class-string>
*/
public function getHookListeners(): array
{
return [
LogMemoCreatedListener::class,
FilterMemoTitleListener::class,
];
}
/**
* 플러그인이 제공하는 훅 정보 반환
*
* 이 플러그인이 로그 기록 시 발행하는 데모 훅을 선언합니다.
*
* @return array<int, array<string, mixed>>
*/
public function getHooks(): array
{
return [
[
'name' => 'gnuboard7-hello_plugin.log.written',
'type' => 'action',
'description' => [
'ko' => 'Hello 플러그인이 로그 파일에 기록을 남긴 직후 실행되는 액션 훅',
'en' => 'Action hook executed right after Hello Plugin writes a log entry',
],
'parameters' => [
'message' => 'string - 기록된 메시지',
'context' => 'array - 기록 시점의 부가 컨텍스트',
],
],
];
}
/**
* 플러그인 설정 스키마 반환
*
* @return array<string, array<string, mixed>>
*/
public function getSettingsSchema(): array
{
return [
'log_enabled' => [
'type' => 'boolean',
'default' => true,
'label' => [
'ko' => '로그 기록 사용',
'en' => 'Enable log writing',
],
'hint' => [
'ko' => '활성화하면 메모 생성 시 hello-plugin.log 파일에 기록합니다.',
'en' => 'When enabled, writes to hello-plugin.log on memo creation.',
],
'required' => false,
],
];
}
/**
* 플러그인 설정 기본값 반환
*
* @return array<string, mixed>
*/
public function getConfigValues(): array
{
return [
'log_enabled' => true,
];
}
}
@@ -0,0 +1,14 @@
{
"name": "Hello Plugin",
"description": "Learning minimal sample plugin (consumes Hello module hooks)",
"settings": {
"title": "Hello Plugin Settings",
"description": "A learning sample that subscribes to Hello module's memo creation hook and writes a log entry.",
"fields": {
"log_enabled": {
"label": "Enable log writing",
"hint": "When enabled, writes to hello-plugin.log on memo creation."
}
}
}
}
@@ -0,0 +1,14 @@
{
"name": "Hello 플러그인",
"description": "학습용 최소 샘플 플러그인 (Hello 모듈 훅 소비)",
"settings": {
"title": "Hello 플러그인 설정",
"description": "Hello 모듈의 메모 생성 훅을 구독해 로그를 남기는 학습용 샘플입니다.",
"fields": {
"log_enabled": {
"label": "로그 기록 사용",
"hint": "활성화하면 메모 생성 시 hello-plugin.log 파일에 기록합니다."
}
}
}
}
@@ -0,0 +1,245 @@
{
"version": "1.0.0",
"layout_name": "plugin_settings",
"permissions": [
"core.plugins.update"
],
"extends": "_admin_base",
"meta": {
"title": "$t:gnuboard7-hello_plugin.settings.title",
"description": "$t:gnuboard7-hello_plugin.settings.description"
},
"data_sources": [
{
"id": "settings",
"type": "api",
"endpoint": "/api/admin/plugins/{{route.identifier}}/settings",
"method": "GET",
"auto_fetch": true,
"auth_required": true,
"initLocal": "form",
"refetchOnMount": true
}
],
"slots": {
"content": [
{
"id": "plugin_settings_content",
"type": "basic",
"name": "Div",
"blur_until_loaded": "{{_local.isSaving}}",
"dataKey": "form",
"trackChanges": true,
"props": {
"className": "p-4 sm:p-6 lg:p-8 bg-gray-50 dark:bg-gray-900 min-h-screen"
},
"children": [
{
"id": "page_header",
"type": "composite",
"name": "PageHeader",
"props": {
"title": "$t:gnuboard7-hello_plugin.settings.title",
"description": "$t:gnuboard7-hello_plugin.settings.description",
"backPath": "/admin/plugins",
"backLabel": "$t:admin.plugins.back_to_list"
}
},
{
"id": "settings_form",
"type": "basic",
"name": "Div",
"props": {
"className": "mt-6 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700"
},
"children": [
{
"id": "settings_fields",
"type": "basic",
"name": "Div",
"props": {
"className": "p-6 space-y-6"
},
"children": [
{
"id": "field_log_enabled",
"type": "basic",
"name": "Div",
"props": {
"className": "flex items-start gap-3"
},
"children": [
{
"type": "basic",
"name": "Input",
"props": {
"type": "checkbox",
"name": "log_enabled",
"className": "mt-1 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
}
},
{
"type": "basic",
"name": "Div",
"children": [
{
"type": "basic",
"name": "Label",
"props": {
"className": "block text-sm font-medium text-gray-700 dark:text-gray-300"
},
"text": "$t:gnuboard7-hello_plugin.settings.fields.log_enabled.label"
},
{
"type": "basic",
"name": "P",
"props": {
"className": "mt-1 text-xs text-gray-500 dark:text-gray-400"
},
"text": "$t:gnuboard7-hello_plugin.settings.fields.log_enabled.hint"
}
]
}
]
}
]
}
]
},
{
"id": "footer_buttons",
"type": "basic",
"name": "Div",
"props": {
"className": "flex justify-end gap-3 mt-6"
},
"children": [
{
"id": "cancel_button",
"type": "basic",
"name": "Button",
"props": {
"type": "button",
"className": "px-4 py-2 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 font-medium transition-colors"
},
"actions": [
{
"type": "click",
"handler": "navigate",
"params": {
"path": "/admin/plugins"
}
}
],
"children": [
{
"type": "basic",
"name": "Span",
"text": "$t:common.cancel"
}
]
},
{
"id": "save_button",
"type": "basic",
"name": "Button",
"props": {
"type": "button",
"disabled": "{{!_local.hasChanges || _local.isSaving}}",
"className": "flex items-center gap-1.5 px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg hover:bg-gray-800 dark:hover:bg-gray-100 font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
},
"actions": [
{
"type": "click",
"handler": "sequence",
"actions": [
{
"handler": "setState",
"params": {
"target": "local",
"isSaving": true,
"errors": null
}
},
{
"handler": "apiCall",
"auth_required": true,
"target": "/api/admin/plugins/{{route.identifier}}/settings",
"params": {
"method": "PUT",
"body": "{{_local.form}}"
},
"onSuccess": [
{
"handler": "setState",
"params": {
"target": "local",
"isSaving": false,
"hasChanges": false
}
},
{
"handler": "toast",
"params": {
"type": "success",
"message": "$t:admin.plugins.settings.save_success"
}
},
{
"handler": "refetchDataSource",
"params": {
"dataSourceId": "settings"
}
}
],
"onError": [
{
"handler": "setState",
"params": {
"target": "local",
"isSaving": false,
"errors": "{{$error.errors}}"
}
},
{
"handler": "toast",
"params": {
"type": "error",
"message": "$t:admin.plugins.settings.save_error"
}
}
]
}
]
}
],
"children": [
{
"type": "basic",
"name": "Span",
"if": "{{!_local.isSaving}}",
"text": "$t:common.save"
},
{
"type": "basic",
"name": "Span",
"if": "{{_local.isSaving}}",
"text": "$t:common.saving"
}
]
}
]
}
]
}
]
},
"schema": {
"log_enabled": {
"type": "boolean",
"default": true,
"label": "$t:gnuboard7-hello_plugin.settings.fields.log_enabled.label",
"hint": "$t:gnuboard7-hello_plugin.settings.fields.log_enabled.hint"
}
}
}
@@ -0,0 +1,66 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin\Listeners;
use App\Contracts\Extension\HookListenerInterface;
/**
* 메모 제목 Filter 훅 리스너 (Filter 훅 시연)
*
* Hello 모듈이 `gnuboard7-hello_module.memo.title.filter` 필터 훅을 발행한다고
* 가정하고, 그 제목 앞에 `[Hello] ` 접두사를 붙이는 간단한 데모입니다.
*
* 학습 포인트:
* - Filter 훅 리스너는 반드시 `'type' => 'filter'` 를 명시해야 반환값이 체인에 반영됩니다.
* - 훅이 실제로 발행되지 않더라도 리스너 등록 자체가 유효하며, 발행 시점이 오면 자동으로 호출됩니다.
*/
class FilterMemoTitleListener implements HookListenerInterface
{
/**
* 구독할 훅 목록 반환
*
* Filter 훅은 `'type' => 'filter'` 를 반드시 명시해야 합니다.
* 미지정 시 Action 으로 처리되어 반환값이 무시됩니다.
*
* @return array<string, array<string, mixed>>
*/
public static function getSubscribedHooks(): array
{
return [
'gnuboard7-hello_module.memo.title.filter' => [
'method' => 'prependHelloPrefix',
'priority' => 10,
'type' => 'filter',
],
];
}
/**
* HookListenerInterface 기본 핸들러 (미사용)
*
* @param mixed ...$args 훅 인자
* @return void
*/
public function handle(...$args): void
{
// 개별 메서드에서 처리
}
/**
* 메모 제목 앞에 `[Hello] ` 접두사를 덧붙입니다.
*
* @param mixed $title 현재 제목 (앞선 필터의 반환값)
* @param mixed ...$extra 추가 인자 (사용하지 않음)
* @return string 변형된 제목
*/
public function prependHelloPrefix(mixed $title, mixed ...$extra): string
{
$value = is_string($title) ? $title : (string) ($title ?? '');
if (str_starts_with($value, '[Hello] ')) {
return $value;
}
return '[Hello] '.$value;
}
}
@@ -0,0 +1,89 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin\Listeners;
use App\Contracts\Extension\HookListenerInterface;
use App\Extension\HookManager;
use App\Services\PluginSettingsService;
use Plugins\Gnuboard7\HelloPlugin\Services\HelloLogService;
/**
* Hello 모듈 메모 생성 훅 로그 리스너 (Action 훅 시연)
*
* Hello 모듈이 발행하는 `gnuboard7-hello_module.memo.created` Action 훅을 구독해
* 플러그인 설정의 `log_enabled` 가 true 일 때만 로그 파일에 기록합니다.
* 기록 직후 자체 훅 `gnuboard7-hello_plugin.log.written` 을 발행해
* 플러그인이 훅 소비자이자 생산자가 될 수 있음을 시연합니다.
*/
class LogMemoCreatedListener implements HookListenerInterface
{
/**
* 플러그인 식별자
*/
private const PLUGIN_ID = 'gnuboard7-hello_plugin';
/**
* 구독할 훅 목록 반환
*
* Action 훅은 type 생략 시 기본값 'action' 으로 처리됩니다.
*
* @return array<string, array<string, mixed>>
*/
public static function getSubscribedHooks(): array
{
return [
'gnuboard7-hello_module.memo.created' => [
'method' => 'onMemoCreated',
'priority' => 10,
],
];
}
/**
* HookListenerInterface 기본 핸들러 (미사용)
*
* @param mixed ...$args 훅 인자
* @return void
*/
public function handle(...$args): void
{
// 개별 메서드에서 처리
}
/**
* 메모 생성 시 로그 파일에 기록합니다.
*
* @param mixed ...$args 훅 인자 (첫 번째: Memo 모델)
* @return void
*/
public function onMemoCreated(...$args): void
{
// 설정 확인 — log_enabled 가 false 면 조용히 스킵
/** @var PluginSettingsService $settings */
$settings = app(PluginSettingsService::class);
$enabled = (bool) $settings->get(self::PLUGIN_ID, 'log_enabled', true);
if (! $enabled) {
return;
}
$memo = $args[0] ?? null;
$context = [
'memo_id' => is_object($memo) ? ($memo->id ?? null) : null,
'memo_uuid' => is_object($memo) ? ($memo->uuid ?? null) : null,
'memo_title' => is_object($memo) ? ($memo->title ?? null) : null,
];
/** @var HelloLogService $logService */
$logService = app(HelloLogService::class);
$logService->log('[HelloPlugin] Memo created hook received', $context);
// 플러그인 자체 훅 발행 데모 — 다른 확장이 이 훅을 구독할 수 있습니다
HookManager::doAction(
'gnuboard7-hello_plugin.log.written',
'[HelloPlugin] Memo created hook received',
$context,
);
}
}
@@ -0,0 +1,37 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin\Providers;
use Illuminate\Support\ServiceProvider;
use Plugins\Gnuboard7\HelloPlugin\Services\HelloLogService;
/**
* Hello 플러그인 서비스 프로바이더
*
* HelloLogService 를 싱글톤으로 바인딩합니다. 플러그인에서 DI 가 필요할 때의
* 구조를 시연하기 위한 최소 프로바이더입니다.
*/
class HelloPluginServiceProvider extends ServiceProvider
{
/**
* 서비스 컨테이너 바인딩을 등록합니다.
*
* @return void
*/
public function register(): void
{
$this->app->singleton(HelloLogService::class, function () {
return new HelloLogService();
});
}
/**
* 부트 로직을 실행합니다.
*
* @return void
*/
public function boot(): void
{
// 학습용 샘플은 부트 단계 로직이 없습니다.
}
}
@@ -0,0 +1,65 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin\Services;
use Illuminate\Log\LogManager;
use Illuminate\Support\Facades\Log;
/**
* Hello 플러그인 로그 서비스
*
* `storage/logs/hello-plugin.log` 파일에 기록을 남기는 단순한 래퍼입니다.
* 학습용 샘플이므로 Monolog 채널을 런타임에 즉석 구성합니다.
*/
class HelloLogService
{
/**
* 로그 채널 이름
*/
public const CHANNEL = 'gnuboard7-hello_plugin';
/**
* 로그 파일 상대 경로 (storage_path 기준)
*/
public const LOG_FILE = 'logs/hello-plugin.log';
/**
* 메시지를 hello-plugin.log 에 기록합니다.
*
* @param string $message 기록할 메시지
* @param array<string, mixed> $context 부가 컨텍스트
* @return void
*/
public function log(string $message, array $context = []): void
{
$this->resolveChannel()->info($message, $context);
}
/**
* 전용 Monolog 채널을 획득합니다.
*
* 채널 설정이 등록되어 있지 않으면 런타임에 설정을 주입해 생성합니다.
*
* @return \Psr\Log\LoggerInterface 로거 인스턴스
*/
private function resolveChannel(): \Psr\Log\LoggerInterface
{
$logManager = Log::getFacadeRoot();
// Laravel 의 LogManager 일 경우에만 동적 채널 구성
if ($logManager instanceof LogManager) {
$config = config('logging.channels.'.self::CHANNEL);
if ($config === null) {
config([
'logging.channels.'.self::CHANNEL => [
'driver' => 'single',
'path' => storage_path(self::LOG_FILE),
'level' => 'debug',
],
]);
}
}
return Log::channel(self::CHANNEL);
}
}
@@ -0,0 +1,8 @@
<?php
/**
* Hello 플러그인 라우트
*
* 플러그인 설정 저장 라우트는 코어 PluginSettingsController 가 처리하므로
* 이 파일은 학습용 샘플에서는 비어 있습니다.
*/
@@ -0,0 +1,176 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin\Tests\Feature;
use App\Extension\HookManager;
use App\Services\PluginSettingsService;
use Plugins\Gnuboard7\HelloPlugin\Services\HelloLogService;
use Plugins\Gnuboard7\HelloPlugin\Tests\PluginTestCase;
/**
* Hello 모듈 메모 생성 훅 E2E 테스트
*
* Hello 모듈이 발행하는 `gnuboard7-hello_module.memo.created` 훅을
* HookManager::doAction() 으로 시뮬레이션 발행했을 때,
* Hello 플러그인 리스너가 실제 파일에 기록하는지 검증합니다.
*
* 이 테스트는 Hook/Event 도메인 규약을 따릅니다:
* - mock 금지
* - 실제 HookManager 체인 사용
* - 관찰 가능한 상태(파일 존재 및 내용) 로 검증
*/
class MemoCreatedHookTest extends PluginTestCase
{
/**
* 테스트마다 로그 파일을 초기화합니다.
*/
protected function setUp(): void
{
parent::setUp();
$logFile = storage_path(HelloLogService::LOG_FILE);
if (file_exists($logFile)) {
@unlink($logFile);
}
}
/**
* 테스트 종료 시 생성된 로그 파일을 제거합니다.
*/
protected function tearDown(): void
{
$logFile = storage_path(HelloLogService::LOG_FILE);
if (file_exists($logFile)) {
@unlink($logFile);
}
parent::tearDown();
}
/**
* log_enabled=true (기본값) 인 상태에서 훅 발행 시 파일에 기록되어야 합니다.
*/
public function test_memo_created_hook_writes_log_when_enabled(): void
{
// PluginSettingsService 를 스텁으로 대체해 log_enabled=true 반환
$settings = new class extends PluginSettingsService
{
public function __construct() {}
public function get(string $identifier, ?string $key = null, mixed $default = null): mixed
{
if ($key === 'log_enabled') {
return true;
}
return $default;
}
};
$this->app->instance(PluginSettingsService::class, $settings);
// 가짜 Memo 데이터 객체 (stdClass) — 리스너는 id/uuid/title 만 참조합니다
$fakeMemo = (object) [
'id' => 42,
'uuid' => 'test-uuid-0001',
'title' => 'Sample Memo',
];
// 훅 발행 시뮬레이션
HookManager::doAction('gnuboard7-hello_module.memo.created', $fakeMemo);
$logFile = storage_path(HelloLogService::LOG_FILE);
$this->assertFileExists($logFile, '훅 발행 시 로그 파일이 생성되어야 합니다.');
$contents = file_get_contents($logFile);
$this->assertStringContainsString('Memo created hook received', $contents);
$this->assertStringContainsString('test-uuid-0001', $contents);
$this->assertStringContainsString('Sample Memo', $contents);
}
/**
* log_enabled=false 인 상태에서는 훅이 발행되어도 파일에 기록되지 않아야 합니다.
*/
public function test_memo_created_hook_skips_log_when_disabled(): void
{
$settings = new class extends PluginSettingsService
{
public function __construct() {}
public function get(string $identifier, ?string $key = null, mixed $default = null): mixed
{
if ($key === 'log_enabled') {
return false;
}
return $default;
}
};
$this->app->instance(PluginSettingsService::class, $settings);
$fakeMemo = (object) [
'id' => 7,
'uuid' => 'test-uuid-disabled',
'title' => 'Disabled Memo',
];
HookManager::doAction('gnuboard7-hello_module.memo.created', $fakeMemo);
$logFile = storage_path(HelloLogService::LOG_FILE);
$this->assertFileDoesNotExist(
$logFile,
'log_enabled=false 일 때는 파일이 생성되지 않아야 합니다.'
);
}
/**
* 로그 기록 직후 플러그인 자체 훅 `gnuboard7-hello_plugin.log.written` 이 발행되어야 합니다.
*/
public function test_listener_dispatches_own_log_written_action_hook(): void
{
$settings = new class extends PluginSettingsService
{
public function __construct() {}
public function get(string $identifier, ?string $key = null, mixed $default = null): mixed
{
return $key === 'log_enabled' ? true : $default;
}
};
$this->app->instance(PluginSettingsService::class, $settings);
$received = [];
HookManager::addAction(
'gnuboard7-hello_plugin.log.written',
function (...$args) use (&$received) {
$received[] = $args;
},
10,
);
$fakeMemo = (object) [
'id' => 1,
'uuid' => 'uuid-own-hook',
'title' => 'Own Hook Memo',
];
HookManager::doAction('gnuboard7-hello_module.memo.created', $fakeMemo);
$this->assertNotEmpty($received, '플러그인 자체 훅이 발행되어야 합니다.');
$this->assertSame('[HelloPlugin] Memo created hook received', $received[0][0] ?? null);
$this->assertIsArray($received[0][1] ?? null);
$this->assertSame('uuid-own-hook', $received[0][1]['memo_uuid'] ?? null);
}
/**
* Filter 훅 리스너가 type:'filter' 로 등록되어 반환값이 체인에 반영되어야 합니다.
*/
public function test_filter_listener_prepends_hello_prefix_to_title(): void
{
$result = HookManager::applyFilters(
'gnuboard7-hello_module.memo.title.filter',
'original title',
);
$this->assertSame('[Hello] original title', $result);
}
}
@@ -0,0 +1,202 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin\Tests;
use App\Extension\HookManager;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
/**
* Hello 플러그인 테스트 베이스 클래스
*
* 플러그인 오토로드, ServiceProvider 등록, 훅 리스너 수동 등록을 담당합니다.
* 실 런타임에서는 PluginManager 가 처리하는 부분을 테스트 환경에서 대신 수행합니다.
*/
abstract class PluginTestCase extends TestCase
{
use DatabaseTransactions;
/**
* 마이그레이션 완료 플래그 (프로세스당 한 번만 실행)
*/
protected static bool $migrated = false;
/**
* HookManager static state 스냅샷 — tearDown 에서 복원하여 테스트 간 훅 격리 보장.
*
* 테스트 내에서 `HookManager::addFilter()` / `addAction()` 으로 등록한 훅이
* 다음 테스트로 누수되어 예상치 못한 콜백 호출 및 doAction::$dispatching 가드
* 상태 leak 을 차단한다.
*
* @var array{hooks: array, filters: array, dispatching: array}|null
*/
private ?array $hookSnapshot = null;
/**
* 플러그인 루트 경로를 반환합니다.
*
* @return string 플러그인 루트 절대 경로
*/
protected function getPluginBasePath(): string
{
return dirname(__DIR__);
}
/**
* 테스트 환경 설정
*/
protected function setUp(): void
{
parent::setUp();
$this->registerPluginAutoload();
$this->app->register(\Plugins\Gnuboard7\HelloPlugin\Providers\HelloPluginServiceProvider::class);
$this->runCoreMigrationIfNeeded();
$this->registerPluginHookListeners();
// 훅 등록 완료 후 스냅샷 — tearDown 에서 이 시점으로 복원하여
// 테스트 본문이 추가한 훅만 제거 (framework 및 setUp 훅은 보존)
$this->snapshotHookManager();
}
/**
* tearDown 에 HookManager 상태 복원.
*/
protected function tearDown(): void
{
$this->restoreHookManager();
parent::tearDown();
}
/**
* HookManager static $hooks / $filters / $dispatching 를 스냅샷.
*/
private function snapshotHookManager(): void
{
$ref = new \ReflectionClass(HookManager::class);
$hooks = $ref->getProperty('hooks');
$filters = $ref->getProperty('filters');
$dispatching = $ref->getProperty('dispatching');
$this->hookSnapshot = [
'hooks' => $hooks->getValue(),
'filters' => $filters->getValue(),
'dispatching' => $dispatching->getValue(),
];
}
/**
* 스냅샷 시점으로 HookManager 복원 — 테스트 내 추가된 훅만 제거.
*/
private function restoreHookManager(): void
{
if ($this->hookSnapshot === null) {
return;
}
$ref = new \ReflectionClass(HookManager::class);
$ref->getProperty('hooks')->setValue(null, $this->hookSnapshot['hooks']);
$ref->getProperty('filters')->setValue(null, $this->hookSnapshot['filters']);
$ref->getProperty('dispatching')->setValue(null, $this->hookSnapshot['dispatching']);
$this->hookSnapshot = null;
}
/**
* 코어 마이그레이션이 필요한 경우 실행합니다.
*
* 플러그인 자체는 마이그레이션이 없지만 PluginSettingsService 등
* 코어 기능을 호출하려면 기본 테이블들이 필요할 수 있습니다.
*/
protected function runCoreMigrationIfNeeded(): void
{
if (static::$migrated) {
return;
}
if (! Schema::hasTable('users') || ! Schema::hasTable('plugins')) {
// 코어 + 모든 번들 확장 마이그레이션을 함께 실행
// (Plugin suite 전체 실행 시 다른 플러그인의 테이블도 필요)
$paths = ['database/migrations'];
foreach (glob(base_path('modules/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
foreach (glob(base_path('plugins/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
$this->artisan('migrate', ['--path' => $paths]);
}
static::$migrated = true;
}
/**
* 플러그인 오토로드를 등록합니다.
*/
protected function registerPluginAutoload(): void
{
$pluginBasePath = $this->getPluginBasePath();
spl_autoload_register(function ($class) use ($pluginBasePath) {
$prefix = 'Plugins\\Gnuboard7\\HelloPlugin\\';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$relativeClass = substr($class, $len);
$file = $pluginBasePath.'/src/'.str_replace('\\', '/', $relativeClass).'.php';
if (file_exists($file)) {
require $file;
}
});
}
/**
* 플러그인 훅 리스너를 HookManager 에 수동 등록합니다.
*
* 실 런타임에서는 PluginManager 가 자동 등록하지만 테스트 환경에서는
* 수동으로 주입해 실제 훅 체인이 동작하도록 합니다.
*
* @return void
*/
protected function registerPluginHookListeners(): void
{
$pluginClass = 'Plugins\\Gnuboard7\\HelloPlugin\\Plugin';
if (! class_exists($pluginClass)) {
require_once $this->getPluginBasePath().'/plugin.php';
}
$plugin = new $pluginClass([
'identifier' => 'gnuboard7-hello_plugin',
'vendor' => 'gnuboard7',
'name' => ['ko' => 'Hello 플러그인', 'en' => 'Hello Plugin'],
'version' => '0.1.0-beta.1',
]);
foreach ($plugin->getHookListeners() as $listenerClass) {
foreach ($listenerClass::getSubscribedHooks() as $hookName => $config) {
$method = is_array($config) ? ($config['method'] ?? 'handle') : 'handle';
$priority = is_array($config) ? ($config['priority'] ?? 10) : 10;
$type = is_array($config) ? ($config['type'] ?? 'action') : 'action';
$listenerInstance = new $listenerClass();
$callback = [$listenerInstance, $method];
if ($type === 'filter') {
HookManager::addFilter($hookName, $callback, $priority);
} else {
HookManager::addAction($hookName, $callback, $priority);
}
}
}
}
}
@@ -0,0 +1,62 @@
<?php
namespace Plugins\Gnuboard7\HelloPlugin\Tests\Unit;
use Plugins\Gnuboard7\HelloPlugin\Services\HelloLogService;
use Plugins\Gnuboard7\HelloPlugin\Tests\PluginTestCase;
/**
* HelloLogService 단위 테스트
*
* 실제 파일시스템에 기록하는 단순 래퍼이므로 실제 파일에 기록되고
* 이후 정리되는지 관찰 가능한 상태로 검증합니다.
*/
class HelloLogServiceTest extends PluginTestCase
{
/**
* 테스트 종료 후 생성된 로그 파일을 정리합니다.
*/
protected function tearDown(): void
{
$logFile = storage_path(HelloLogService::LOG_FILE);
if (file_exists($logFile)) {
@unlink($logFile);
}
parent::tearDown();
}
/**
* log() 호출 시 hello-plugin.log 파일에 메시지가 기록되어야 합니다.
*/
public function test_log_writes_message_to_hello_plugin_log_file(): void
{
/** @var HelloLogService $service */
$service = app(HelloLogService::class);
$service->log('[Unit] sample message', ['foo' => 'bar']);
$logFile = storage_path(HelloLogService::LOG_FILE);
$this->assertFileExists($logFile, 'hello-plugin.log 파일이 생성되어야 합니다.');
$contents = file_get_contents($logFile);
$this->assertStringContainsString('[Unit] sample message', $contents);
$this->assertStringContainsString('foo', $contents);
}
/**
* 여러 번 호출하면 모든 메시지가 추가 기록되어야 합니다.
*/
public function test_log_appends_multiple_messages(): void
{
/** @var HelloLogService $service */
$service = app(HelloLogService::class);
$service->log('first message');
$service->log('second message');
$contents = file_get_contents(storage_path(HelloLogService::LOG_FILE));
$this->assertStringContainsString('first message', $contents);
$this->assertStringContainsString('second message', $contents);
}
}
@@ -4,6 +4,12 @@
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [1.0.0-beta.3] - 2026-05-11
### Added
- 이미지 업로드 전후에 외부 확장이 본인인증·정책 가드를 붙일 수 있는 확장점 제공
## [1.0.0-beta.2] - 2026-04-22
### Fixed
@@ -2,7 +2,7 @@
"name": "plugins/sirsoft-ckeditor5",
"description": "CKEditor 5 WYSIWYG Editor Plugin for Gnuboard7 platform",
"type": "library",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"authors": [
{
"name": "sirsoft",
@@ -1,6 +1,6 @@
{
"name": "@g7/sirsoft-ckeditor5",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"description": "그누보드7 CKEditor 5 WYSIWYG 에디터 플러그인 프론트엔드 에셋",
"private": true,
"type": "module",
@@ -5,7 +5,7 @@
"ko": "CKEditor 5 WYSIWYG 에디터",
"en": "CKEditor 5 WYSIWYG Editor"
},
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"license": "MIT",
"description": {
"ko": "CKEditor 5를 이용한 WYSIWYG 에디터 플러그인입니다. 플러그인 설치만으로 기존 HtmlEditor가 교체됩니다.",
@@ -33,13 +33,16 @@ class ImageUploadService
*/
public function upload(UploadedFile $file, ?int $uploadedBy): Ckeditor5ImageUpload
{
// 훅: 이미지 업로드 전 (본인인증 등 확장 지점)
\App\Extension\HookManager::doAction('sirsoft-ckeditor5.image.before_upload', $file, $uploadedBy);
$extension = $file->guessExtension() ?? $file->getClientOriginalExtension();
$storedFilename = Str::uuid().'.'.$extension;
$path = date('Y/m/d').'/'.$storedFilename;
$this->storage->put('images', $path, file_get_contents($file->getRealPath()));
return $this->repository->create([
$record = $this->repository->create([
'original_name' => $file->getClientOriginalName(),
'file_path' => "images/{$path}",
'storage_disk' => $this->storage->getDisk(),
@@ -47,5 +50,9 @@ class ImageUploadService
'mime_type' => $file->getMimeType(),
'uploaded_by' => $uploadedBy,
]);
\App\Extension\HookManager::doAction('sirsoft-ckeditor5.image.after_upload', $record);
return $record;
}
}
@@ -48,6 +48,9 @@ abstract class PluginTestCase extends TestCase
->needs(StorageInterface::class)
->give(fn () => new PluginStorageDriver('sirsoft-ckeditor5', 'plugins'));
// HookManager 상태 스냅샷 (tearDown 에서 복원하여 테스트 간 훅 격리)
$this->snapshotHookManager();
// 라우트 등록
Route::prefix('api/plugins/sirsoft-ckeditor5')
->middleware('api')
@@ -60,6 +63,53 @@ abstract class PluginTestCase extends TestCase
});
}
/**
* HookManager static state 스냅샷 — tearDown 에서 복원하여 테스트 간 훅 격리 보장.
*
* @var array{hooks: array, filters: array, dispatching: array}|null
*/
private ?array $hookSnapshot = null;
/**
* tearDown 에 HookManager 상태 복원.
*/
protected function tearDown(): void
{
$this->restoreHookManager();
parent::tearDown();
}
/**
* HookManager static $hooks / $filters / $dispatching 를 스냅샷.
*/
private function snapshotHookManager(): void
{
$ref = new \ReflectionClass(\App\Extension\HookManager::class);
$this->hookSnapshot = [
'hooks' => $ref->getProperty('hooks')->getValue(),
'filters' => $ref->getProperty('filters')->getValue(),
'dispatching' => $ref->getProperty('dispatching')->getValue(),
];
}
/**
* 스냅샷 시점으로 HookManager 복원.
*/
private function restoreHookManager(): void
{
if ($this->hookSnapshot === null) {
return;
}
$ref = new \ReflectionClass(\App\Extension\HookManager::class);
$ref->getProperty('hooks')->setValue(null, $this->hookSnapshot['hooks']);
$ref->getProperty('filters')->setValue(null, $this->hookSnapshot['filters']);
$ref->getProperty('dispatching')->setValue(null, $this->hookSnapshot['dispatching']);
$this->hookSnapshot = null;
}
/**
* 관리자 권한을 가진 사용자를 생성합니다.
*
@@ -92,14 +142,20 @@ abstract class PluginTestCase extends TestCase
*/
protected function migrateFreshUsing(): array
{
// 모든 번들 확장 migrations 포함 — Plugin suite 전체 실행 시 스키마 보장
$paths = ['database/migrations'];
foreach (glob(base_path('modules/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
foreach (glob(base_path('plugins/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
return [
'--drop-views' => $this->shouldDropViews(),
'--drop-types' => $this->shouldDropTypes(),
'--seed' => false,
'--path' => [
'database/migrations',
'plugins/_bundled/sirsoft-ckeditor5/database/migrations',
],
'--path' => $paths,
];
}
}
@@ -4,6 +4,13 @@
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [1.0.0-beta.3] - 2026-05-11
### Changed
- 기본 system 마케팅 동의 채널(이메일 수신) 라벨이 활성 언어팩으로 자동 보강되도록 변경
- sirsoft-page 의존성 제약을 `>=1.0.0-beta.3` 로 정비 (번들 최신 버전과 동기화)
## [1.0.0-beta.2] - 2026-04-20
### Changed
@@ -2,7 +2,7 @@
"name": "plugins/sirsoft-marketing",
"description": "Marketing consent and subscription management plugin for Gnuboard7 platform",
"type": "library",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"autoload": {
"psr-4": {
"Plugins\\Sirsoft\\Marketing\\": ["src/", "./"]
@@ -0,0 +1,14 @@
<?php
/**
* Marketing consent channel labels (English)
*
* Labels referenced by `label_key` in system channels returned by
* `MarketingConsentService::getDefaultSystemChannels()`.
* Automatically supplemented by active language packs.
*/
return [
'email_subscription' => [
'label' => 'Email Marketing',
],
];
@@ -0,0 +1,13 @@
<?php
/**
* 마케팅 동의 채널 라벨 (Korean)
*
* `MarketingConsentService::getDefaultSystemChannels()` 가 반환하는 system 채널의
* `label_key` 가 가리키는 라벨. 활성 언어팩으로 자동 보강.
*/
return [
'email_subscription' => [
'label' => '광고성 이메일 수신',
],
];
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@g7/sirsoft-marketing",
"version": "0.1.5",
"version": "1.0.0-beta.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@g7/sirsoft-marketing",
"version": "0.1.5",
"version": "1.0.0-beta.3",
"devDependencies": {
"jsdom": "^27.4.0",
"typescript": "^5.3.3",
@@ -1,6 +1,6 @@
{
"name": "@g7/sirsoft-marketing",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"description": "G7 마케팅 동의 플러그인 프론트엔드 에셋",
"private": true,
"type": "module",
@@ -5,7 +5,7 @@
"ko": "마케팅 동의",
"en": "Marketing Consent"
},
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"description": {
"ko": "이메일 구독, 마케팅 동의, 제3자 제공 동의 등을 관리하는 플러그인",
"en": "Plugin for managing email subscriptions, marketing consent, and third-party data sharing consent"
@@ -14,7 +14,7 @@
"g7_version": ">=7.0.0-beta.2",
"dependencies": {
"modules": {
"sirsoft-page": ">=1.0.0-beta.2"
"sirsoft-page": ">=1.0.0-beta.3"
},
"plugins": {}
},
@@ -71,7 +71,7 @@ class MarketingSettingsController extends PublicBaseController
$slug = $channel['page_slug'] ?? '';
$labelRaw = $channel['label'] ?? [];
$labelString = is_array($labelRaw)
? ($labelRaw[$locale] ?? $labelRaw['ko'] ?? $channel['key'])
? ($labelRaw[$locale] ?? $labelRaw[config('app.fallback_locale', 'ko')] ?? $channel['key'])
: (string) $labelRaw;
return [
@@ -68,14 +68,24 @@ class MarketingConsentService
* 저장된 설정과 무관하게 항상 보장되어야 하는 system 채널 정의입니다.
* 채널 저장 시 system 채널 누락 방지에 사용됩니다.
*
* @return array<int, array{key: string, label: array{ko: string, en: string}, page_slug: string, enabled: bool, is_system: bool}>
* 라벨은 lang key 기반으로 선언되어 활성 언어팩으로 자동 보강됩니다.
* (registry payload name_key 계약 — 7.0.0-beta.4+)
*
* @return array<int, array{key: string, label_key: string, label: array{ko: string, en: string}, page_slug: string, enabled: bool, is_system: bool}>
*/
public function getDefaultSystemChannels(): array
{
$emailLabelKey = 'sirsoft-marketing::channels.email_subscription.label';
return [
[
'key' => 'email_subscription',
'label' => ['ko' => '광고성 이메일 수신', 'en' => 'Email Marketing'],
'label_key' => $emailLabelKey,
// label 은 plugin_settings 저장 시 fallback (lang pack 미설치 환경 보호)
'label' => [
'ko' => __($emailLabelKey, [], 'ko'),
'en' => __($emailLabelKey, [], 'en'),
],
'page_slug' => '',
'enabled' => true,
'is_system' => true,
@@ -8,7 +8,7 @@ use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Plugins\Sirsoft\Marketing\Contracts\MarketingConsentRepositoryInterface;
use Plugins\Sirsoft\Marketing\Repositories\Contracts\MarketingConsentRepositoryInterface;
use Plugins\Sirsoft\Marketing\Http\Controllers\MarketingAdminController;
use Plugins\Sirsoft\Marketing\Http\Controllers\MarketingSettingsController;
use Plugins\Sirsoft\Marketing\Repositories\MarketingConsentRepository;
@@ -30,6 +30,13 @@ abstract class PluginTestCase extends TestCase
* 플러그인 라우트는 테스트 환경에서 플러그인이 로드되지 않으므로
* 직접 등록합니다.
*/
/**
* HookManager static state 스냅샷 — tearDown 에서 복원하여 테스트 간 훅 격리 보장.
*
* @var array{hooks: array, filters: array, dispatching: array}|null
*/
private ?array $hookSnapshot = null;
protected function setUp(): void
{
parent::setUp();
@@ -49,6 +56,49 @@ abstract class PluginTestCase extends TestCase
->name('api.sirsoft-marketing.admin.channels.update');
});
});
// HookManager 상태 스냅샷 (tearDown 에서 복원)
$this->snapshotHookManager();
}
/**
* tearDown 에 HookManager 상태 복원.
*/
protected function tearDown(): void
{
$this->restoreHookManager();
parent::tearDown();
}
/**
* HookManager static $hooks / $filters / $dispatching 를 스냅샷.
*/
private function snapshotHookManager(): void
{
$ref = new \ReflectionClass(\App\Extension\HookManager::class);
$this->hookSnapshot = [
'hooks' => $ref->getProperty('hooks')->getValue(),
'filters' => $ref->getProperty('filters')->getValue(),
'dispatching' => $ref->getProperty('dispatching')->getValue(),
];
}
/**
* 스냅샷 시점으로 HookManager 복원.
*/
private function restoreHookManager(): void
{
if ($this->hookSnapshot === null) {
return;
}
$ref = new \ReflectionClass(\App\Extension\HookManager::class);
$ref->getProperty('hooks')->setValue(null, $this->hookSnapshot['hooks']);
$ref->getProperty('filters')->setValue(null, $this->hookSnapshot['filters']);
$ref->getProperty('dispatching')->setValue(null, $this->hookSnapshot['dispatching']);
$this->hookSnapshot = null;
}
/**
@@ -87,14 +137,22 @@ abstract class PluginTestCase extends TestCase
*/
protected function migrateFreshUsing(): array
{
// RefreshDatabase 는 첫 테스트의 migrateFreshUsing 만 적용하므로
// Plugin suite 실행 시에도 필요한 테이블이 모두 있도록 모든 번들 확장의
// migrations 를 포함시킨다.
$paths = ['database/migrations'];
foreach (glob(base_path('modules/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
foreach (glob(base_path('plugins/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
return [
'--drop-views' => $this->shouldDropViews(),
'--drop-types' => $this->shouldDropTypes(),
'--seed' => false,
'--path' => [
'database/migrations',
'plugins/_bundled/sirsoft-marketing/database/migrations',
],
'--path' => $paths,
];
}
}
@@ -318,4 +318,32 @@ class MarketingConsentServiceTest extends PluginTestCase
$this->assertEquals(2, $record->consent_count);
}
// ── getDefaultSystemChannels (registry payload name_key 계약, 7.0.0-beta.4+) ──
public function test_default_system_channels_carry_label_key(): void
{
$channels = $this->service->getDefaultSystemChannels();
$this->assertCount(1, $channels);
$email = $channels[0];
$this->assertSame('email_subscription', $email['key']);
$this->assertSame('sirsoft-marketing::channels.email_subscription.label', $email['label_key']);
$this->assertTrue($email['is_system']);
}
public function test_default_system_channels_label_resolves_via_lang_pack(): void
{
// label 은 lang 파일에서 해석된 ko/en 값으로 자동 채워져 plugin_settings 저장 시 fallback 보장
$channels = $this->service->getDefaultSystemChannels();
$email = $channels[0];
$this->assertIsArray($email['label']);
$this->assertArrayHasKey('ko', $email['label']);
$this->assertArrayHasKey('en', $email['label']);
// 활성 lang 파일이 등록되어 있으면 실제 라벨, 미등록 환경이면 키 그대로 (둘 다 string)
$this->assertIsString($email['label']['ko']);
$this->assertIsString($email['label']['en']);
}
}
@@ -4,6 +4,16 @@
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [1.0.0-beta.3] - 2026-05-11
### Added
- 결제 취소 전후에 외부 확장이 본인인증 등 추가 로직을 붙일 수 있는 확장점 제공
### Changed
- sirsoft-ecommerce 의존성을 `>=1.0.0-beta.3` 으로 정비
## [1.0.0-beta.2] - 2026-04-20
### Changed
@@ -1,7 +1,7 @@
{
"name": "plugins/sirsoft-tosspayments",
"description": "TossPayments PG Plugin for G7 platform",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"type": "library",
"authors": [
{
@@ -0,0 +1,12 @@
<?php
/**
* TossPayments PG provider metadata (English)
*
* Label referenced by name_key in `sirsoft-ecommerce.payment.registered_pg_providers` hook payload.
* Automatically supplemented by active language packs.
*/
return [
'name' => 'TossPayments',
'description' => 'TossPayments domestic payment gateway integration',
];
@@ -0,0 +1,12 @@
<?php
/**
* 토스페이먼츠 PG 프로바이더 메타 (Korean)
*
* `sirsoft-ecommerce.payment.registered_pg_providers` 훅 페이로드의
* name_key 가 가리키는 라벨. 활성 언어팩으로 자동 보강된다.
*/
return [
'name' => '토스페이먼츠',
'description' => '국내 PG 사 토스페이먼츠 결제 연동',
];
@@ -1,6 +1,6 @@
{
"name": "@g7/sirsoft-tosspayments",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"type": "module",
"private": true,
"scripts": {
@@ -5,7 +5,7 @@
"ko": "토스페이먼츠",
"en": "TossPayments"
},
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"license": "MIT",
"description": {
"ko": "토스페이먼츠 결제 게이트웨이 (통합결제창 연동)",
@@ -14,7 +14,7 @@
"g7_version": ">=7.0.0-beta.2",
"dependencies": {
"modules": {
"sirsoft-ecommerce": ">=1.0.0-beta.2"
"sirsoft-ecommerce": ">=1.0.0-beta.3"
},
"plugins": {}
},
@@ -55,7 +55,8 @@ class RegisterPgProviderListener implements HookListenerInterface
{
$providers[] = [
'id' => 'tosspayments',
'name' => ['ko' => '토스페이먼츠', 'en' => 'TossPayments'],
'name_key' => 'sirsoft-tosspayments::provider.name',
'name' => localized_label(nameKey: 'sirsoft-tosspayments::provider.name'),
'icon' => 'credit-card',
'supported_methods' => ['card'],
];
@@ -70,7 +70,14 @@ class TossPaymentsApiService
$body['cancelAmount'] = $cancelAmount;
}
return $this->request('POST', "/v1/payments/{$paymentKey}/cancel", $body);
// 훅: 결제 취소 전 (본인인증 등 확장 지점)
\App\Extension\HookManager::doAction('sirsoft-tosspayments.payment.before_cancel', $paymentKey, $cancelReason, $cancelAmount);
$response = $this->request('POST', "/v1/payments/{$paymentKey}/cancel", $body);
\App\Extension\HookManager::doAction('sirsoft-tosspayments.payment.after_cancel', $paymentKey, $response);
return $response;
}
/**
@@ -42,18 +42,32 @@ abstract class PluginTestCase extends TestCase
*/
protected function migrateFreshUsing(): array
{
// RefreshDatabase 는 첫 테스트의 migrateFreshUsing 만 적용 — 모든 번들 확장
// migrations 를 포함시켜 Plugin suite 전체 실행 시에도 스키마 보장.
$paths = ['database/migrations'];
foreach (glob(base_path('modules/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
foreach (glob(base_path('plugins/_bundled/*/database/migrations'), GLOB_ONLYDIR) as $p) {
$paths[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $p);
}
return [
'--drop-views' => $this->shouldDropViews(),
'--drop-types' => $this->shouldDropTypes(),
'--seed' => $this->shouldSeed(),
'--seeder' => $this->seeder(),
'--path' => [
'database/migrations',
'modules/sirsoft-ecommerce/database/migrations',
],
'--path' => $paths,
];
}
/**
* HookManager static state 스냅샷 — tearDown 에서 복원하여 테스트 간 훅 격리 보장.
*
* @var array{hooks: array, filters: array, dispatching: array}|null
*/
private ?array $hookSnapshot = null;
/**
* 테스트 환경 설정
*/
@@ -75,6 +89,49 @@ abstract class PluginTestCase extends TestCase
// 플러그인 라우트를 수동으로 등록
$this->registerPluginRoutes();
// HookManager 상태 스냅샷 (tearDown 에서 복원)
$this->snapshotHookManager();
}
/**
* tearDown 에 HookManager 상태 복원.
*/
protected function tearDown(): void
{
$this->restoreHookManager();
parent::tearDown();
}
/**
* HookManager static $hooks / $filters / $dispatching 를 스냅샷.
*/
private function snapshotHookManager(): void
{
$ref = new \ReflectionClass(\App\Extension\HookManager::class);
$this->hookSnapshot = [
'hooks' => $ref->getProperty('hooks')->getValue(),
'filters' => $ref->getProperty('filters')->getValue(),
'dispatching' => $ref->getProperty('dispatching')->getValue(),
];
}
/**
* 스냅샷 시점으로 HookManager 복원.
*/
private function restoreHookManager(): void
{
if ($this->hookSnapshot === null) {
return;
}
$ref = new \ReflectionClass(\App\Extension\HookManager::class);
$ref->getProperty('hooks')->setValue(null, $this->hookSnapshot['hooks']);
$ref->getProperty('filters')->setValue(null, $this->hookSnapshot['filters']);
$ref->getProperty('dispatching')->setValue(null, $this->hookSnapshot['dispatching']);
$this->hookSnapshot = null;
}
/**
@@ -94,9 +94,9 @@ class PaymentRefundListenerTest extends TestCase
$defaultResult = ['success' => false, 'error_code' => null, 'error_message' => null, 'transaction_id' => null];
// getApiService()에서 app() 호출 시 예외 발생 → 정상적으로 진입했다는 증거
// (Unit 테스트에서 Laravel 컨테이너 없으므로 BindingResolutionException 발생)
$this->expectException(\RuntimeException::class);
// getApiService()에서 app() 호출 시 Laravel 컨테이너 미준비로
// BindingResolutionException 발생 → 정상적으로 tosspayments 분기로 진입했다는 증거
$this->expectException(\Throwable::class);
$listener->processRefund($defaultResult, $order, $payment, 10000.0);
}
@@ -52,12 +52,24 @@ class RegisterPgProviderListenerTest extends TestCase
$toss = $result[1];
$this->assertEquals('tosspayments', $toss['id']);
$this->assertEquals('토스페이먼츠', $toss['name']['ko']);
$this->assertEquals('TossPayments', $toss['name']['en']);
// 7.0.0-beta.4+ : registry payload name_key 계약
$this->assertEquals('sirsoft-tosspayments::provider.name', $toss['name_key']);
// name 은 활성 locale 로 해석된 문자열 (Container 미초기화 단위 환경에서는 빈 문자열)
$this->assertIsString($toss['name']);
$this->assertEquals('credit-card', $toss['icon']);
$this->assertContains('card', $toss['supported_methods']);
}
/**
* registerProvider 페이로드가 name_key (lang key) 를 보유해 활성 언어팩 보강 가능한지 확인.
*/
public function test_register_provider_carries_name_key_for_lang_pack_resolution(): void
{
$result = $this->listener->registerProvider([]);
$this->assertArrayHasKey('name_key', $result[0]);
$this->assertSame('sirsoft-tosspayments::provider.name', $result[0]['name_key']);
}
/**
* registerProvider가 기존 제공자를 유지하는지 확인
*/
@@ -0,0 +1,70 @@
# 시나리오 매니페스트 예시 (실제 적용 아님 — .yaml.example 확장자)
# 실제 매니페스트로 채택할 때 .yaml 로 이름 변경 + test_files 의 실재 경로 매핑
#
# 참조: docs/testing-guide.md "기능 단위 시나리오 매트릭스"
feature: order_payment_pg_toss
description: 토스 PG 를 통한 주문 결제 흐름 (회원/비회원, 마일리지, 환율, 도서산간 등 모든 도메인 변수 cross product)
# 매니페스트를 검증하는 테스트 파일 (실제 작성 시 경로 갱신)
test_files:
- plugins/_bundled/sirsoft-tosspayments/tests/Feature/Payment/TossPgPaymentTest.php
- plugins/_bundled/sirsoft-tosspayments/tests/Feature/Payment/WebhookTest.php
# 축이 많아 full cross product 가 폭발하므로 pairwise 전략
coverage_strategy: pairwise
# 입력 axis — 결제 흐름에 영향을 주는 도메인 변수 전수
axes:
user_type: [member, guest]
mileage_enabled: [true, false]
product_options: [single, multi_option, bundle]
shipping_region: [domestic, jeju, remote_island]
shipping_policy: [free, fixed, range_based, conditional_free]
coupon_applied: [none, product, category, all]
currency: [krw, usd_with_fx]
rounding_unit: [1, 10, 100]
# 의미 없는 조합 컷 — 사유 명시 필수
exclusions:
- { user_type: guest, mileage_enabled: true, reason: "비회원은 마일리지 사용 불가" }
- { currency: usd_with_fx, rounding_unit: 1, reason: "환율 적용 시 1원 단위 절사 무의미" }
# 후속 효과 체인 — 결제 후 모든 부수효과
effects:
- webhook_received
- payment_approved
- mileage_deducted
- notification_sent_to_user
- notification_amount_matches_total
- vat_calculated
- tax_free_amount_split
- coupon_marked_used
- inventory_decremented
- order_status_transitioned_to_paid
# 보조 흐름 — 취소/환불 등
sub_flows:
- id: partial_cancel
description: 부분 취소 시 할인/배송 정책 재계산
effects:
- shipping_policy_recalculated
- discount_recalculated
- mileage_partial_refunded
- vat_recalculated
- id: full_cancel
description: 전체 취소 시 모든 부수효과 역방향
effects:
- payment_voided
- mileage_fully_refunded
- coupon_unused
- inventory_restored
- order_status_transitioned_to_cancelled
notes: |
이 매니페스트는 예시이며 실제 채택 시 다음을 갱신하세요:
1. test_files 경로
2. axes 값 목록 (실제 도메인 enum/policy 와 일치하도록)
3. effects 명명 (테스트 docblock @effects 와 1:1 매칭)
pairwise 전략 케이스 수: 약 16~20 (full 일 경우 2*2*3*3*4*4*2*3 = 3456)