feat(core,ecommerce,ckeditor5,board,admin_basic): 공개 자산 직접 URL(CDN) 서빙 옵트인
StorageInterface::url 의 public 하드코딩을 완화하고 core.storage.filter_url 훅을 신설해, 완전 공개 자산(상품·카테고리·리뷰·에디터 이미지)의 직접 URL 서빙을 옵트인으로 열었다. 미설정 시 기존 스트리밍 100% 보존. 디스크 결정은 확장 개별 설정 > 코어 전역 > 미설정 순이며, 서빙·삭제·이동은 행에 기록된 disk 를 따라 전환 전후 자산이 혼재해도 각자 실제 저장 위치를 향한다. 고아 disk(공급 플러그인 비활성화)는 스트리밍으로 폴백해 500 이 되지 않는다. 공개 이슈 (@lyg-kaban 건의) 대응.
This commit is contained in:
1 parent
37fad55333
commit
057e002ad1
125 files changed
+5913
-203
No files matched your search
@@ -9,6 +9,8 @@
|
||||
### Changed
|
||||
|
||||
- 글 저장·수정 시 비밀글 여부 값을 문자열(`"true"`/`"false"`)로 보내는 클라이언트도 수용하도록 해석을 관대화했습니다. 해석할 수 없는 값은 종전과 동일하게 거부됩니다.
|
||||
- 첨부 미리보기·작성자 아바타 주소 조립을 코어와 공유하는 단일 지점으로 정리했습니다. 표시되는 주소와 동작은 종전과 동일합니다.
|
||||
- 코어 최소 요구 버전을 7.0.7 로 상향했습니다.
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
@@ -351,7 +351,7 @@ _목록 응답: `data.data[]` 배열 항목의 필드 + `data.pagination`._
|
||||
| reply_count | integer | `0` | reply 개수 (집계) |
|
||||
| attachment_count | integer | `0` | attachment 개수 (집계) |
|
||||
| has_attachment | boolean | `false` | attachment 여부 |
|
||||
| thumbnail | string | `/api/modules/sirsoft-board/boards/api…` | 썸네일 이미지 URL/경로 |
|
||||
| thumbnail | string | `/api/modules/sirsoft-board/boards/api…` | 썸네일 이미지 URL/경로 — `/api/modules/sirsoft-board/boards/{slug}/attachment/{hash}/preview` 형식 (첫 이미지 첨부의 미리보기 서빙 URL) |
|
||||
| parent_id | null | `null` | parent 식별자 (연관 리소스 참조) |
|
||||
| depth | integer | `0` | 계층 트리에서의 깊이 (0 = 최상위, 하위로 갈수록 증가) |
|
||||
| is_reply | boolean | `false` | reply 여부 |
|
||||
@@ -1029,7 +1029,7 @@ _단건 응답: `data` 객체의 필드._
|
||||
| reply_count | integer | `0` | reply 개수 (집계) |
|
||||
| attachment_count | integer | `0` | attachment 개수 (집계) |
|
||||
| has_attachment | boolean | `false` | attachment 여부 |
|
||||
| thumbnail | string | `/api/modules/sirsoft-board/boards/api…` | 썸네일 이미지 URL/경로 |
|
||||
| thumbnail | string | `/api/modules/sirsoft-board/boards/api…` | 썸네일 이미지 URL/경로 — `/api/modules/sirsoft-board/boards/{slug}/attachment/{hash}/preview` 형식 (첫 이미지 첨부의 미리보기 서빙 URL) |
|
||||
| parent_id | null | `null` | parent 식별자 (연관 리소스 참조) |
|
||||
| depth | integer | `0` | 계층 트리에서의 깊이 (0 = 최상위, 하위로 갈수록 증가) |
|
||||
| is_reply | boolean | `false` | reply 여부 |
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"ko": "게시판 관리를 위한 모듈",
|
||||
"en": "Module for board management"
|
||||
},
|
||||
"g7_version": ">=7.0.6",
|
||||
"g7_version": ">=7.0.7",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
|
||||
@@ -312,7 +312,7 @@ class PostResource extends BaseApiResource
|
||||
$slug = request()->route('slug') ?? ($this->relationLoaded('board') ? $this->board?->slug : null);
|
||||
|
||||
if ($slug && $attachment->hash) {
|
||||
return '/api/modules/sirsoft-board/boards/'.$slug.'/attachment/'.$attachment->hash.'/preview';
|
||||
return $attachment->previewUrlForSlug($slug);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -127,6 +127,8 @@ class Attachment extends Model
|
||||
|
||||
/**
|
||||
* 게시판과의 관계를 정의합니다.
|
||||
*
|
||||
* @return BelongsTo 게시판 관계
|
||||
*/
|
||||
public function board(): BelongsTo
|
||||
{
|
||||
@@ -135,6 +137,8 @@ class Attachment extends Model
|
||||
|
||||
/**
|
||||
* 게시글과의 관계를 정의합니다.
|
||||
*
|
||||
* @return BelongsTo 게시글 관계
|
||||
*/
|
||||
public function post(): BelongsTo
|
||||
{
|
||||
@@ -143,6 +147,8 @@ class Attachment extends Model
|
||||
|
||||
/**
|
||||
* 업로더와의 관계를 정의합니다.
|
||||
*
|
||||
* @return BelongsTo 업로더 사용자 관계
|
||||
*/
|
||||
public function creator(): BelongsTo
|
||||
{
|
||||
@@ -178,7 +184,21 @@ class Attachment extends Model
|
||||
? $this->board->slug
|
||||
: Board::find($this->board_id)?->slug;
|
||||
|
||||
return '/api/modules/sirsoft-board/boards/'.$boardSlug.'/attachment/'.$this->hash.'/preview';
|
||||
return $this->previewUrlForSlug((string) $boardSlug);
|
||||
}
|
||||
|
||||
/**
|
||||
* 슬러그가 이미 해석된 컨텍스트의 미리보기 URL 조립 단일 지점.
|
||||
*
|
||||
* 목록 직렬화(PostResource)처럼 slug 를 라우트/관계에서 이미 알고 있어
|
||||
* Board::find() 재조회(N+1)를 피해야 하는 호출측이 사용합니다.
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return string 미리보기 URL
|
||||
*/
|
||||
public function previewUrlForSlug(string $slug): string
|
||||
{
|
||||
return '/api/modules/sirsoft-board/boards/'.$slug.'/attachment/'.$this->hash.'/preview';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -180,6 +180,7 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function filterByType(string $type): Collection
|
||||
{
|
||||
// audit:allow query-unbounded-get reason: boards 는 운영자 등록 설정성 테이블 — 행 수가 운영자 행위에 묶여 데이터 증가에 비례하지 않는다
|
||||
return Board::where('type', $type)->get();
|
||||
}
|
||||
|
||||
@@ -203,6 +204,7 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function getRecentPosts(int $limit): array
|
||||
{
|
||||
// audit:allow query-unbounded-get reason: boards 는 운영자 등록 설정성 테이블 — 행 수가 운영자 행위에 묶여 데이터 증가에 비례하지 않는다
|
||||
$activeBoardIds = Board::where('is_active', true)->pluck('id');
|
||||
|
||||
if ($activeBoardIds->isEmpty()) {
|
||||
@@ -400,6 +402,7 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function getTotalCommentsCount(): int
|
||||
{
|
||||
// audit:allow query-unbounded-get reason: boards 는 운영자 등록 설정성 테이블 — 행 수가 운영자 행위에 묶여 데이터 증가에 비례하지 않는다
|
||||
$activeBoardIds = Board::where('is_active', true)->pluck('id');
|
||||
|
||||
return Comment::query()
|
||||
@@ -424,6 +427,7 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function getPopularPosts(string $period, int $limit): array
|
||||
{
|
||||
// audit:allow query-unbounded-get reason: boards 는 운영자 등록 설정성 테이블 — 행 수가 운영자 행위에 묶여 데이터 증가에 비례하지 않는다
|
||||
$activeBoardIds = Board::where('is_active', true)->pluck('id');
|
||||
|
||||
if ($activeBoardIds->isEmpty()) {
|
||||
@@ -486,10 +490,10 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
$viewCount = $post->view_count ?? 0;
|
||||
$commentCount = $post->comments_count ?? 0;
|
||||
|
||||
// Avatar URL 결정
|
||||
// Avatar URL 결정 — 코어 첨부 URL 조립은 코어 모델 단일 지점에 위임
|
||||
$avatarUrl = null;
|
||||
if ($post->user_id && $post->attachment_hash) {
|
||||
$avatarUrl = '/api/attachment/'.$post->attachment_hash;
|
||||
$avatarUrl = Attachment::urlForHash($post->attachment_hash);
|
||||
}
|
||||
|
||||
// 사용자 상태 처리 (탈퇴한 사용자는 익명화)
|
||||
@@ -560,6 +564,7 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function getActiveBoardsList(): Collection
|
||||
{
|
||||
// audit:allow query-unbounded-get reason: boards 는 운영자 등록 설정성 테이블 — 행 수가 운영자 행위에 묶여 데이터 증가에 비례하지 않는다
|
||||
return Board::where('is_active', true)
|
||||
->orderBy('created_at', 'asc')
|
||||
->get();
|
||||
@@ -620,6 +625,7 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function getActiveBoardsOrdered(string $orderBy = 'created_at', string $orderDirection = 'desc'): Collection
|
||||
{
|
||||
// audit:allow query-unbounded-get reason: boards 는 운영자 등록 설정성 테이블 — 행 수가 운영자 행위에 묶여 데이터 증가에 비례하지 않는다
|
||||
return Board::where('is_active', true)
|
||||
->orderBy($orderBy, $orderDirection)
|
||||
->get();
|
||||
@@ -648,6 +654,7 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function getActiveBoardsForMenu(): Collection
|
||||
{
|
||||
// audit:allow query-unbounded-get reason: boards 는 운영자 등록 설정성 테이블 — 행 수가 운영자 행위에 묶여 데이터 증가에 비례하지 않는다
|
||||
return Board::where('is_active', true)
|
||||
->select(['id', 'name', 'slug'])
|
||||
->orderBy('created_at', 'asc')
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Tests\Unit;
|
||||
|
||||
use Modules\Sirsoft\Board\Models\Attachment;
|
||||
use Modules\Sirsoft\Board\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* 게시판 첨부 미리보기 URL 조립 단일 지점(previewUrlForSlug) 회귀 테스트
|
||||
*
|
||||
* URL 중복 조립 정리(#100) 후에도 응답 문자열이 기존과 동일함을 고정합니다.
|
||||
* board 는 직접 URL 배선 대상이 아니므로 문자열 회귀 0 이 계약입니다.
|
||||
*/
|
||||
class AttachmentPreviewUrlTest extends ModuleTestCase
|
||||
{
|
||||
/**
|
||||
* @effects board_response_strings_unchanged
|
||||
*/
|
||||
#[Test]
|
||||
public function preview_url_for_slug_builds_board_preview_url(): void
|
||||
{
|
||||
$attachment = new Attachment;
|
||||
$attachment->hash = 'abc123def456';
|
||||
|
||||
$this->assertSame(
|
||||
'/api/modules/sirsoft-board/boards/notice/attachment/abc123def456/preview',
|
||||
$attachment->previewUrlForSlug('notice')
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function preview_url_accessor_delegates_to_single_assembly_point(): void
|
||||
{
|
||||
$attachment = new Attachment;
|
||||
$attachment->hash = 'abc123def456';
|
||||
$attachment->mime_type = 'image/png';
|
||||
$attachment->board_id = 0;
|
||||
|
||||
// board 관계 미로딩 + 존재하지 않는 board_id → slug 는 빈 문자열로 조립 (기존 동작 보존)
|
||||
$this->assertSame(
|
||||
'/api/modules/sirsoft-board/boards//attachment/abc123def456/preview',
|
||||
$attachment->preview_url
|
||||
);
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Tests\Unit\Repositories;
|
||||
|
||||
use App\Models\Attachment as CoreAttachment;
|
||||
use App\Models\User;
|
||||
use Modules\Sirsoft\Board\Repositories\BoardRepository;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* 인기 게시물 아바타 URL 호출측 회귀 테스트 (#100 URL 조립 단일화)
|
||||
*
|
||||
* urlForHash() 헬퍼 자체가 아니라 **호출측**(BoardRepository getPopularPosts)이
|
||||
* 조인으로 얻은 hash 를 코어 단일 지점에 위임해 응답 문자열이 기존과 동일하게
|
||||
* 직렬화되는지 고정합니다.
|
||||
*/
|
||||
class BoardRepositoryPopularAvatarTest extends BoardTestCase
|
||||
{
|
||||
/**
|
||||
* @effects board_response_strings_unchanged
|
||||
*/
|
||||
#[Test]
|
||||
public function popular_posts_avatar_serializes_core_attachment_url(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$avatar = CoreAttachment::create([
|
||||
'attachmentable_type' => User::class,
|
||||
'attachmentable_id' => $user->id,
|
||||
'original_filename' => 'avatar.png',
|
||||
'stored_filename' => 'stored-avatar.png',
|
||||
'disk' => 'local',
|
||||
'path' => 'avatars/avatar.png',
|
||||
'mime_type' => 'image/png',
|
||||
'size' => 100,
|
||||
'collection' => 'avatar',
|
||||
]);
|
||||
|
||||
$postId = $this->createTestPost([
|
||||
'user_id' => $user->id,
|
||||
'view_count' => 99,
|
||||
'comments_count' => 0,
|
||||
'replies_count' => 0,
|
||||
'attachments_count' => 0,
|
||||
]);
|
||||
|
||||
$posts = app(BoardRepository::class)->getPopularPosts('year', 10);
|
||||
|
||||
$target = collect($posts)->firstWhere('id', $postId);
|
||||
$this->assertNotNull($target, '생성한 게시글이 인기 게시물 목록에 있어야 합니다');
|
||||
$this->assertSame('/api/attachment/'.$avatar->hash, $target['author']['avatar']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects board_response_strings_unchanged
|
||||
*/
|
||||
#[Test]
|
||||
public function popular_posts_avatar_is_null_without_avatar_attachment(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$postId = $this->createTestPost([
|
||||
'user_id' => $user->id,
|
||||
'view_count' => 98,
|
||||
'comments_count' => 0,
|
||||
'replies_count' => 0,
|
||||
'attachments_count' => 0,
|
||||
]);
|
||||
|
||||
$posts = app(BoardRepository::class)->getPopularPosts('year', 10);
|
||||
|
||||
$target = collect($posts)->firstWhere('id', $postId);
|
||||
$this->assertNotNull($target);
|
||||
$this->assertNull($target['author']['avatar']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Tests\Unit\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Board\Http\Resources\PostResource;
|
||||
use Modules\Sirsoft\Board\Models\Attachment;
|
||||
use Modules\Sirsoft\Board\Models\Post;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* PostResource 썸네일 URL 호출측 회귀 테스트 (#100 URL 조립 단일화)
|
||||
*
|
||||
* previewUrlForSlug() 헬퍼 자체가 아니라 **호출측**(PostResource
|
||||
* getThumbnailUrlFromRelations)이 slug 인자를 올바르게 전달해 응답 문자열이
|
||||
* 기존과 동일하게 직렬화되는지 고정합니다 — 헬퍼 출력만 고정하면 인자 전달
|
||||
* 오류(슬러그 누락 등)가 전부 green 으로 통과합니다.
|
||||
*/
|
||||
class PostResourceThumbnailUrlTest extends BoardTestCase
|
||||
{
|
||||
/**
|
||||
* 이미지 첨부를 가진 게시글을 생성합니다.
|
||||
*
|
||||
* @param string $mimeType 첨부 MIME 타입
|
||||
* @return array{post: Post, attachment: Attachment} 게시글/첨부
|
||||
*/
|
||||
private function createPostWithAttachment(string $mimeType): array
|
||||
{
|
||||
$postId = $this->createTestPost();
|
||||
|
||||
$attachment = Attachment::create([
|
||||
'board_id' => $this->board->id,
|
||||
'post_id' => $postId,
|
||||
'original_filename' => 'thumb.jpg',
|
||||
'stored_filename' => 'stored-thumb.jpg',
|
||||
'disk' => 'modules',
|
||||
'path' => 'attachments/thumb.jpg',
|
||||
'mime_type' => $mimeType,
|
||||
'size' => 100,
|
||||
'collection' => 'attachments',
|
||||
'order' => 0,
|
||||
]);
|
||||
|
||||
$post = Post::with(['thumbnailAttachment', 'board'])->findOrFail($postId);
|
||||
|
||||
return ['post' => $post, 'attachment' => $attachment];
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects board_response_strings_unchanged
|
||||
*/
|
||||
#[Test]
|
||||
public function thumbnail_serializes_preview_url_with_board_slug(): void
|
||||
{
|
||||
['post' => $post, 'attachment' => $attachment] = $this->createPostWithAttachment('image/jpeg');
|
||||
|
||||
$response = (new PostResource($post))->toArray(Request::create('/'));
|
||||
|
||||
$this->assertSame(
|
||||
'/api/modules/sirsoft-board/boards/'.$this->board->slug.'/attachment/'.$attachment->hash.'/preview',
|
||||
$response['thumbnail'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects board_response_strings_unchanged
|
||||
*/
|
||||
#[Test]
|
||||
public function thumbnail_is_null_for_non_image_attachment(): void
|
||||
{
|
||||
['post' => $post] = $this->createPostWithAttachment('application/pdf');
|
||||
|
||||
$response = (new PostResource($post))->toArray(Request::create('/'));
|
||||
|
||||
$this->assertNull($response['thumbnail']);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@
|
||||
### Added
|
||||
|
||||
- 리뷰 이미지 업로드에 파일 가공 필터 훅 제공 — 확장에서 상품·카테고리 이미지와 동일하게 리뷰 이미지도 업로드 시점에 변환(압축·리사이즈·포맷 변경)할 수 있습니다. (#96 @lyg-kaban 님께서 건의해주셨습니다.)
|
||||
- 상품·카테고리·리뷰 이미지를 코어의 공개 자산 스토리지(S3+CDN 등) 디스크에 저장하고 화면에는 CDN 직접 주소로 서빙할 수 있습니다. 기본정보 탭의 「공개 자산 스토리지」에서 이 모듈만 다른 디스크를 쓰도록 개별 설정할 수도 있습니다(비우면 코어 설정 따름). 디스크를 바꿔도 기존 이미지는 원래 위치에서 계속 정상 표시·삭제됩니다. (#100 @lyg-kaban 님께서 건의해주셨습니다.)
|
||||
|
||||
### Changed
|
||||
|
||||
- 코어 최소 요구 버전을 7.0.7 로 상향했습니다.
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
@@ -66,16 +66,6 @@ return [
|
||||
'guest_cart_lifetime' => 7 * 24 * 60, // 7일 (분 단위)
|
||||
],
|
||||
|
||||
// 카테고리 설정
|
||||
'category' => [
|
||||
'image_disk' => 'local',
|
||||
],
|
||||
|
||||
// 브랜드 설정
|
||||
'brand' => [
|
||||
'image_disk' => 'local',
|
||||
],
|
||||
|
||||
// 리뷰 설정
|
||||
'review' => [
|
||||
'write_deadline_days' => 90, // 구매확정 후 리뷰 작성 가능 기간 (일)
|
||||
|
||||
@@ -23,7 +23,8 @@
|
||||
"privacy_officer": "",
|
||||
"privacy_officer_email": "",
|
||||
"mail_order_number": "",
|
||||
"telecom_number": ""
|
||||
"telecom_number": "",
|
||||
"public_asset_disk": ""
|
||||
},
|
||||
"language_currency": {
|
||||
"default_currency": "KRW",
|
||||
@@ -339,7 +340,8 @@
|
||||
"privacy_officer": { "expose": false },
|
||||
"privacy_officer_email": { "expose": false },
|
||||
"mail_order_number": { "expose": false },
|
||||
"telecom_number": { "expose": false }
|
||||
"telecom_number": { "expose": false },
|
||||
"public_asset_disk": { "expose": false }
|
||||
}
|
||||
},
|
||||
"language_currency": {
|
||||
|
||||
@@ -54,6 +54,7 @@ _단건 응답: `data` 객체의 필드._
|
||||
| claim | object | `{"refund_reasons":[{"id":1,"type":"refund","code":"order_…` | 클레임 설정 (DB 관리 대상인 환불 사유 목록: 코드·다국어명·귀책 유형·노출/활성 여부) |
|
||||
| available_pg_providers | array | `[{"id":"kginicis","name_key":"sirsoft-pay_kginicis::provi…` | 설치된 PG 플러그인이 훅으로 등록한 PG 제공자 목록 (id·name_key·지원 결제수단) |
|
||||
| available_cash_receipt_providers | array | `[]` | 설치된 플러그인이 훅으로 등록한 현금영수증 발급 제공자 목록 (id·name_key — 미등록 시 빈 배열이며 신청 폼이 노출되지 않음) |
|
||||
| available_public_asset_disks | array | `[{"id":"none","label":{"ko":"사용 안 함 (스트리밍)","en":"Disabl…` | 공개 자산 직접 URL 서빙 디스크 선택지 (코어 DriverRegistryService 카탈로그 — none/public/s3 + 플러그인 훅 등록분). 기본정보 탭의 공개 자산 디스크 Select 옵션 소스 |
|
||||
| abilities | object | `{"can_update":true}` | 현재 사용자가 이 리소스에 수행 가능한 작업 불리언 맵 (can_update, can_delete 등 — 권한 맵 기반) |
|
||||
| _meta | object | `{"limits":{"auto_cancel_days_min":1,"auto_cancel_days_max…` | 설정 화면 전용 메타. `limits` 는 숫자 입력의 경계값 맵(`config('sirsoft-ecommerce.limits')`)으로, 저장 규칙(FormRequest)과 같은 출처다 — 화면이 리터럴 경계를 들면 규칙 변경을 따라가지 못해 "화면은 받는데 저장은 422" 가 되므로 입력 min/max 는 이 값을 바인딩한다 |
|
||||
|
||||
@@ -449,6 +450,7 @@ HTTP/1.1 200
|
||||
| basic_info.privacy_officer_email | body | email | 아니오 | max 255 | 개인정보 보호책임자 E-mail |
|
||||
| basic_info.mail_order_number | body | string | 아니오 | max 100 | 통신판매업 신고번호 |
|
||||
| basic_info.telecom_number | body | string | 아니오 | max 100 | 부가통신 사업자번호 |
|
||||
| basic_info.public_asset_disk | body | string | 아니오 | max 100 | 공개 자산 디스크 오버라이드 (빈값=코어 설정 따름, none=강제 스트리밍, 그 외=카탈로그 디스크 id — 존재하지 않는 디스크는 스트리밍으로 안전 폴백) |
|
||||
| language_currency | body | array | 아니오 | — | 통화 설정 섹션 (기본 통화·통화 목록: 코드·다국어명·환율·반올림 규칙·통화별 로케일) |
|
||||
| language_currency.default_currency | body | string | 아니오 | max 10 | 쇼핑몰 기본(base) 통화 코드. 상품/주문이 1건이라도 생성된 뒤에는 변경 불가 |
|
||||
| language_currency.currencies | body | array | 아니오 | — | 등록 통화 목록. 항목별 `code`(ISO 4217 3자리 대문자, 필수)·`name`(다국어 배열, 필수)·`symbol`·`exchange_rate`·`base_unit`·`rounding_unit`·`rounding_method`(`floor`\|`round`\|`ceil`)·`decimal_places`·`is_default`·`locales` |
|
||||
@@ -667,6 +669,7 @@ _단건 응답: `data` 객체의 필드._
|
||||
| claim | object | `{"refund_reasons":[{"id":1,"type":"refund","code":"order_…` | 클레임 설정 (DB 관리 대상인 환불 사유 목록: 코드·다국어명·귀책 유형·노출/활성 여부) |
|
||||
| available_pg_providers | array | `[{"id":"kginicis","name_key":"sirsoft-pay_kginicis::provi…` | 설치된 PG 플러그인이 훅으로 등록한 PG 제공자 목록 (id·name_key·지원 결제수단) |
|
||||
| available_cash_receipt_providers | array | `[]` | 설치된 플러그인이 훅으로 등록한 현금영수증 발급 제공자 목록 (id·name_key — 미등록 시 빈 배열이며 신청 폼이 노출되지 않음) |
|
||||
| available_public_asset_disks | array | `[{"id":"none","label":{"ko":"사용 안 함 (스트리밍)","en":"Disabl…` | 공개 자산 직접 URL 서빙 디스크 선택지 (코어 DriverRegistryService 카탈로그 — none/public/s3 + 플러그인 훅 등록분). 기본정보 탭의 공개 자산 디스크 Select 옵션 소스 |
|
||||
|
||||
**응답 예시**
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"ko": "그누보드7 이커머스 모듈 - 상품, 주문, 결제 관리",
|
||||
"en": "Gnuboard7 Ecommerce Module - Product, Order, Payment Management"
|
||||
},
|
||||
"g7_version": ">=7.0.6",
|
||||
"g7_version": ">=7.0.7",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
|
||||
@@ -1056,6 +1056,43 @@ class Module extends AbstractModule
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 완전 공개 자산 스토리지 카테고리 목록
|
||||
*
|
||||
* 이 카테고리들만 공개 자산 디스크 설정을 따른다. 권한 검사가 걸린 자산
|
||||
* (회원 전용/비밀 자료 등)은 직접 URL 이 권한을 우회하므로 포함하지 않는다.
|
||||
* 새 공개 자산 카테고리가 생기면 여기에만 추가하면 된다.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private const PUBLIC_ASSET_CATEGORIES = ['images'];
|
||||
|
||||
/**
|
||||
* 카테고리별 스토리지 디스크 이름 반환
|
||||
*
|
||||
* 완전 공개 자산 카테고리만 공개 자산 디스크(모듈 설정 basic_info.public_asset_disk >
|
||||
* 코어 전역 core.storage.public_asset_disk)를 따르고, 설정/캐시 등 나머지
|
||||
* 카테고리는 기본 디스크를 유지합니다. 미설정/고아 디스크는 기본 디스크로
|
||||
* 폴백해 기존 스트리밍 동작을 보존합니다.
|
||||
*
|
||||
* 모듈 설정 조회는 공개 자산 카테고리에서만 수행합니다 — 'settings' 카테고리에서
|
||||
* 조회하면 설정 로드와 재귀 고리가 생깁니다 (AbstractModule 주석 참조).
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @return string 디스크 이름
|
||||
*/
|
||||
public function getStorageDiskFor(string $category): string
|
||||
{
|
||||
if (! in_array($category, self::PUBLIC_ASSET_CATEGORIES, true)) {
|
||||
return $this->getStorageDisk();
|
||||
}
|
||||
|
||||
$override = module_setting('sirsoft-ecommerce', 'basic_info.public_asset_disk', '');
|
||||
|
||||
return $this->resolvePublicAssetDisk(is_string($override) ? $override : '')
|
||||
?? $this->getStorageDisk();
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 설치 시 실행할 시더 목록 반환
|
||||
*
|
||||
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* 이커머스 설정 기본정보 탭 — 공개 자산 디스크 오버라이드 필드 테스트 (공개#100)
|
||||
*
|
||||
* @description
|
||||
* 모듈 오버라이드 필드는 저장 키(basic_info.public_asset_disk)와 설정 응답의
|
||||
* 카탈로그(available_public_asset_disks)를 바인딩해야 한다. 세 지점(defaults.json ·
|
||||
* StoreEcommerceSettingsRequest · 레이아웃 name)이 같은 키를 가리키지 않으면
|
||||
* 저장값이 조용히 버려지거나(whitelist 탈락) 화면만 있고 저장이 없는 상태가 된다.
|
||||
*
|
||||
* 계약 단언에 더해, 실제 카드 서브트리를 createLayoutTest 로 렌더링해
|
||||
* "코어 설정 따름" 선두 옵션 + 카탈로그 $localized 매핑 계산까지 검증한다.
|
||||
*
|
||||
* @effects settings_catalog_includes_plugin_registered_disks
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
|
||||
import { createLayoutTest } from '@core/template-engine/__tests__/utils/layoutTestUtils';
|
||||
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
|
||||
|
||||
import tabBasicInfo from '../../../layouts/admin/partials/admin_ecommerce_settings/_tab_basic_info.json';
|
||||
|
||||
// ─── 테스트용 컴포넌트 ───
|
||||
|
||||
const TestDiv: React.FC<{ className?: string; children?: React.ReactNode; 'data-testid'?: string }> =
|
||||
({ className, children, 'data-testid': testId }) => (
|
||||
<div className={className} data-testid={testId}>{children}</div>
|
||||
);
|
||||
|
||||
const TestH3: React.FC<{ className?: string; children?: React.ReactNode; text?: string }> =
|
||||
({ className, children, text }) => <h3 className={className}>{children || text}</h3>;
|
||||
|
||||
const TestLabel: React.FC<{ className?: string; children?: React.ReactNode; text?: string }> =
|
||||
({ className, children, text }) => <label className={className}>{children || text}</label>;
|
||||
|
||||
const TestSpan: React.FC<{ className?: string; children?: React.ReactNode; text?: string }> =
|
||||
({ className, children, text }) => <span className={className}>{children || text}</span>;
|
||||
|
||||
const TestSelect: React.FC<{
|
||||
name?: string; value?: string; className?: string; options?: any[]; disabled?: boolean;
|
||||
error?: string; onChange?: (e: React.ChangeEvent<HTMLSelectElement>) => void;
|
||||
}> = ({ name, value, className, options, disabled, onChange }) => (
|
||||
<select data-name={name} value={value} className={className} disabled={disabled} onChange={onChange}>
|
||||
{options?.map((o) => <option key={String(o.value)} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
);
|
||||
|
||||
// 렌더러가 컴포넌트 목록을 Fragment 로 감싸므로 반드시 등록해야 한다.
|
||||
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
|
||||
|
||||
function setupTestRegistry(): ComponentRegistry {
|
||||
const registry = ComponentRegistry.getInstance();
|
||||
(registry as any).registry = {
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
H3: { component: TestH3, metadata: { name: 'H3', type: 'basic' } },
|
||||
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
|
||||
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
|
||||
Select: { component: TestSelect, metadata: { name: 'Select', type: 'composite' } },
|
||||
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
|
||||
};
|
||||
return registry;
|
||||
}
|
||||
|
||||
// ─── 다국어 (기본정보 탭 공개 자산 카드가 쓰는 키) ───
|
||||
|
||||
const translations = {
|
||||
'sirsoft-ecommerce': {
|
||||
admin: {
|
||||
settings: {
|
||||
basic_info: {
|
||||
public_asset_storage: {
|
||||
title: '공개 자산 스토리지',
|
||||
description: '이 모듈의 이미지 서빙 디스크를 오버라이드합니다.',
|
||||
disk: '공개 자산 디스크',
|
||||
follow_core: '코어 설정 따름',
|
||||
help: '미설정 시 코어 전역 설정을 따릅니다.',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 모듈 루트(모듈 manifest 기준)를 위로 훑어 찾는다.
|
||||
*
|
||||
* @returns 모듈 루트 절대경로
|
||||
*/
|
||||
function moduleRoot(): string {
|
||||
let current = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
for (let depth = 0; depth < 10; depth++) {
|
||||
if (fs.existsSync(path.join(current, 'module.json'))) {
|
||||
return current;
|
||||
}
|
||||
current = path.dirname(current);
|
||||
}
|
||||
|
||||
throw new Error('module.json 을 가진 모듈 루트를 찾지 못했습니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 트리에서 조건을 만족하는 첫 노드를 찾는다.
|
||||
*
|
||||
* @param node 탐색 시작 노드
|
||||
* @param predicate 노드 판정 함수
|
||||
* @returns 찾은 노드 또는 null
|
||||
*/
|
||||
function findNode(node: any, predicate: (n: any) => boolean): any {
|
||||
if (!node || typeof node !== 'object') return null;
|
||||
if (predicate(node)) return node;
|
||||
|
||||
for (const child of node.children ?? []) {
|
||||
const found = findNode(child, predicate);
|
||||
if (found) return found;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// 실제 카드 서브트리를 그대로 렌더 대상으로 쓴다 — 사본 표현식이 아닌 배포 JSON 자체가 SSoT.
|
||||
const publicAssetCard = findNode(
|
||||
tabBasicInfo,
|
||||
(n) => n.id === 'public_asset_storage_card',
|
||||
);
|
||||
|
||||
const CATALOG = [
|
||||
{ id: 'none', label: { ko: '사용 안 함 (스트리밍)', en: 'None (streaming)' } },
|
||||
{ id: 'fake_cdn', label: { ko: '가짜 CDN', en: 'Fake CDN' } },
|
||||
];
|
||||
|
||||
/**
|
||||
* 카드 렌더링용 테스트 유틸을 생성한다.
|
||||
*
|
||||
* @returns createLayoutTest 유틸
|
||||
*/
|
||||
function makeUtils() {
|
||||
return createLayoutTest(
|
||||
{
|
||||
version: '1.0.0',
|
||||
layout_name: 'test_ecommerce_public_asset_card',
|
||||
components: [publicAssetCard],
|
||||
} as any,
|
||||
{
|
||||
auth: {
|
||||
isAuthenticated: true,
|
||||
user: { id: 1, name: 'Admin', role: 'super_admin' },
|
||||
authType: 'admin',
|
||||
},
|
||||
translations,
|
||||
locale: 'ko',
|
||||
initialState: {
|
||||
_local: {
|
||||
form: {
|
||||
available_public_asset_disks: CATALOG,
|
||||
basic_info: { public_asset_disk: '' },
|
||||
},
|
||||
errors: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe('이커머스 공개 자산 디스크 오버라이드 필드 — 계약', () => {
|
||||
it('Select 가 저장 키와 카탈로그를 바인딩하고 코어 따름 기본 옵션을 갖는다', () => {
|
||||
const select = findNode(
|
||||
publicAssetCard,
|
||||
(n) => n.name === 'Select' && n.props?.name === 'basic_info.public_asset_disk',
|
||||
);
|
||||
|
||||
expect(select).not.toBeNull();
|
||||
expect(select.props.options).toContain('available_public_asset_disks');
|
||||
expect(select.props.options).toContain('follow_core');
|
||||
});
|
||||
|
||||
it('defaults.json 과 저장 규칙이 같은 키를 선언한다', () => {
|
||||
const root = moduleRoot();
|
||||
const defaults = JSON.parse(
|
||||
fs.readFileSync(path.join(root, 'config/settings/defaults.json'), 'utf-8'),
|
||||
);
|
||||
const requestSource = fs.readFileSync(
|
||||
path.join(root, 'src/Http/Requests/Admin/StoreEcommerceSettingsRequest.php'),
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
expect(defaults.defaults.basic_info).toHaveProperty('public_asset_disk');
|
||||
expect(requestSource).toContain("'basic_info.public_asset_disk'");
|
||||
});
|
||||
|
||||
it('module.php 오버라이드가 같은 설정 키를 조회한다', () => {
|
||||
const moduleSource = fs.readFileSync(path.join(moduleRoot(), 'module.php'), 'utf-8');
|
||||
|
||||
expect(moduleSource).toContain("'basic_info.public_asset_disk'");
|
||||
expect(moduleSource).toContain('PUBLIC_ASSET_CATEGORIES');
|
||||
});
|
||||
});
|
||||
|
||||
describe('이커머스 공개 자산 디스크 오버라이드 필드 — 렌더링', () => {
|
||||
let registry: ComponentRegistry;
|
||||
let testUtils: ReturnType<typeof createLayoutTest> | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = setupTestRegistry();
|
||||
// 표현식 내 $t() 는 컨텍스트에 $templateId 가 없으면 __templateApp.getConfig()
|
||||
// 로 회수한다(engine-v1.38.2 폴백). layoutTestUtils 는 이를 세팅하지 않으므로
|
||||
// 테스트에서 동일 폴백 경로를 제공해야 옵션 계산식의 $t() 가 해석된다.
|
||||
(window as any).__templateApp = {
|
||||
getConfig: () => ({ templateId: 'test-template', locale: 'ko' }),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
testUtils?.cleanup();
|
||||
testUtils = null;
|
||||
(registry as any).registry = {};
|
||||
delete (window as any).__templateApp;
|
||||
});
|
||||
|
||||
it('카드 제목/도움말이 다국어 해석되어 렌더된다', async () => {
|
||||
testUtils = makeUtils();
|
||||
const { container } = await testUtils.render();
|
||||
|
||||
expect(container.querySelector('h3.card-title')?.textContent ?? '').toContain(
|
||||
'공개 자산 스토리지',
|
||||
);
|
||||
expect(container.textContent ?? '').toContain('미설정 시 코어 전역 설정을 따릅니다.');
|
||||
expect(() => testUtils!.assertNoValidationErrors()).not.toThrow();
|
||||
});
|
||||
|
||||
it('Select 옵션이 코어 따름 선두 + 카탈로그 $localized 매핑으로 계산된다', async () => {
|
||||
testUtils = makeUtils();
|
||||
const { container } = await testUtils.render();
|
||||
|
||||
const select = container.querySelector('select[data-name="basic_info.public_asset_disk"]');
|
||||
expect(select).not.toBeNull();
|
||||
|
||||
const options = Array.from(select!.querySelectorAll('option'));
|
||||
expect(options.map((o) => o.getAttribute('value'))).toEqual(['', 'none', 'fake_cdn']);
|
||||
expect(options.map((o) => o.textContent)).toEqual([
|
||||
'코어 설정 따름',
|
||||
'사용 안 함 (스트리밍)',
|
||||
'가짜 CDN',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -59,6 +59,13 @@
|
||||
"telecom_number_placeholder": "Telecom business number",
|
||||
"postcode_plugin_required": "Daum Postcode plugin is not installed or inactive. Please activate it in Admin > Plugins."
|
||||
},
|
||||
"public_asset_storage": {
|
||||
"title": "Public Asset Storage",
|
||||
"description": "Configure the storage disk for this module's fully public assets such as product, category, and review images.",
|
||||
"disk": "Public Asset Disk",
|
||||
"follow_core": "Follow core setting",
|
||||
"help": "Select to use a different disk for this module only. Leave empty to follow the public asset storage setting in core system settings."
|
||||
},
|
||||
"inquiry_settings": {
|
||||
"title": "1:1 Inquiry Board Settings",
|
||||
"description": "Configure the product 1:1 inquiry feature.",
|
||||
|
||||
@@ -59,6 +59,13 @@
|
||||
"telecom_number_placeholder": "부가통신 사업자번호",
|
||||
"postcode_plugin_required": "다음 우편번호 플러그인이 설치되지 않았거나 비활성화 상태입니다. 관리자 > 플러그인에서 활성화해주세요."
|
||||
},
|
||||
"public_asset_storage": {
|
||||
"title": "공개 자산 스토리지",
|
||||
"description": "상품·카테고리·리뷰 이미지 등 이 모듈의 완전 공개 자산 저장 디스크를 설정합니다.",
|
||||
"disk": "공개 자산 디스크",
|
||||
"follow_core": "코어 설정 따름",
|
||||
"help": "이 모듈만 다른 디스크를 쓰려면 선택합니다. 비우면 코어 환경설정의 공개 자산 스토리지 설정을 따릅니다."
|
||||
},
|
||||
"inquiry_settings": {
|
||||
"title": "1:1 문의게시판 설정",
|
||||
"description": "상품 1:1 문의 기능을 설정합니다.",
|
||||
|
||||
+83
@@ -1055,6 +1055,89 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "public_asset_storage_card",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
"className": "admin-card"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"id": "public_asset_storage_title",
|
||||
"type": "basic",
|
||||
"name": "H3",
|
||||
"props": {
|
||||
"className": "card-title"
|
||||
},
|
||||
"text": "$t:sirsoft-ecommerce.admin.settings.basic_info.public_asset_storage.title"
|
||||
},
|
||||
{
|
||||
"id": "public_asset_storage_description",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
"className": "card-description"
|
||||
},
|
||||
"text": "$t:sirsoft-ecommerce.admin.settings.basic_info.public_asset_storage.description"
|
||||
},
|
||||
{
|
||||
"id": "field_public_asset_disk",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
"className": "form-group"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Label",
|
||||
"props": {
|
||||
"className": "form-label"
|
||||
},
|
||||
"text": "$t:sirsoft-ecommerce.admin.settings.basic_info.public_asset_storage.disk"
|
||||
},
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
"className": "w-full md:w-64"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"type": "composite",
|
||||
"name": "Select",
|
||||
"props": {
|
||||
"name": "basic_info.public_asset_disk",
|
||||
"disabled": "{{_computed.isReadOnly}}",
|
||||
"className": "w-full",
|
||||
"error": "{{_local.errors?.['basic_info.public_asset_disk']?.[0] ?? ''}}",
|
||||
"options": "{{[{value: '', label: $t('sirsoft-ecommerce.admin.settings.basic_info.public_asset_storage.follow_core')}].concat((_local.form?.available_public_asset_disks ?? []).map(d => ({value: d.id, label: $localized(d.label)})))}}"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Span",
|
||||
"if": "{{_local.errors?.['basic_info.public_asset_disk']}}",
|
||||
"props": {
|
||||
"className": "form-error"
|
||||
},
|
||||
"text": "{{_local.errors?.['basic_info.public_asset_disk']?.[0] ?? ''}}"
|
||||
},
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
"className": "text-sm text-gray-500 dark:text-gray-400 mt-2"
|
||||
},
|
||||
"text": "$t:sirsoft-ecommerce.admin.settings.basic_info.public_asset_storage.help"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "inquiry_settings_card",
|
||||
"type": "basic",
|
||||
|
||||
+7
@@ -7,6 +7,7 @@ use App\Helpers\PermissionHelper;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Seo\Contracts\SeoCacheManagerInterface;
|
||||
use App\Services\DriverRegistryService;
|
||||
use App\Services\NotificationChannelService;
|
||||
use App\Services\NotificationDefinitionService;
|
||||
use Exception;
|
||||
@@ -56,6 +57,9 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
// 현금영수증 발급 프로바이더 후보 — 결제 플러그인이 훅으로 자신을 등록한다.
|
||||
// 발급 PG 와 결제 PG 는 독립 선택이므로 목록도 별도로 내린다 (KG 결제 + 토스 발급 등).
|
||||
$settings['available_cash_receipt_providers'] = $this->settingsService->getRegisteredCashReceiptProviders();
|
||||
// 공개 자산 디스크 선택지 — 카탈로그 SSoT 는 코어 DriverRegistryService 게터 한 곳
|
||||
$settings['available_public_asset_disks'] = app(DriverRegistryService::class)
|
||||
->getAvailableDrivers('public_asset');
|
||||
$settings['abilities'] = [
|
||||
'can_update' => PermissionHelper::check('sirsoft-ecommerce.settings.update', request()->user()),
|
||||
];
|
||||
@@ -171,6 +175,9 @@ class EcommerceSettingsController extends AdminBaseController
|
||||
$updatedSettings = $this->appendMileageNotificationChannelsToSettings($updatedSettings);
|
||||
$updatedSettings['available_pg_providers'] = $this->settingsService->getRegisteredPgProviders();
|
||||
$updatedSettings['available_cash_receipt_providers'] = $this->settingsService->getRegisteredCashReceiptProviders();
|
||||
// 공개 자산 디스크 선택지 — 저장 응답에도 재부착 (관리자 UI 상태 갱신용)
|
||||
$updatedSettings['available_public_asset_disks'] = app(DriverRegistryService::class)
|
||||
->getAvailableDrivers('public_asset');
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
|
||||
+30
-1
@@ -3,9 +3,9 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Rules\LocaleRequiredTranslatable;
|
||||
use App\Services\DriverRegistryService;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ShippingFeeTaxPolicy;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
@@ -206,6 +206,13 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
'basic_info.privacy_officer_email' => ['nullable', 'email', 'max:255'],
|
||||
'basic_info.mail_order_number' => ['nullable', 'string', 'max:100'],
|
||||
'basic_info.telecom_number' => ['nullable', 'string', 'max:100'],
|
||||
// 공개 자산 디스크 — 빈 값은 코어 공개 자산 디스크 설정을 따른다.
|
||||
// 선택지가 코어 카탈로그 + 플러그인 훅 등록 디스크로 동적이라 정적 in 불가 —
|
||||
// 코어 SaveSettingsRequest 와 동일하게 카탈로그 조회 closure 로 검증한다.
|
||||
// (런타임 resolvePublicAssetDisk() 의 스트리밍 폴백은 최후 안전망이지, 저장
|
||||
// 시점의 오타를 성공 응답으로 통과시켜도 된다는 뜻이 아니다 — 운영자에게는
|
||||
// "저장됐는데 CDN 이 안 붙는" 무증상 상태로만 보인다.)
|
||||
'basic_info.public_asset_disk' => ['nullable', 'string', 'max:100', $this->publicAssetDiskRule()],
|
||||
|
||||
'language_currency' => ['sometimes', 'array'],
|
||||
// default_language 제거 (A1-⑤, D-LANG): 사이트 언어는 코어 일반설정으로 일원화. 모듈 orphan 필드.
|
||||
@@ -364,6 +371,28 @@ class StoreEcommerceSettingsRequest extends FormRequest
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 공개 자산 디스크 존재 검증 규칙을 만듭니다.
|
||||
*
|
||||
* 선택지는 코어 3종 + 플러그인이 훅으로 등록한 디스크라 런타임에만 확정되므로
|
||||
* 정적 `Rule::in` 을 쓸 수 없습니다. 코어 `SaveSettingsRequest` 와 동일하게
|
||||
* 카탈로그 게터(SSoT)를 조회하는 closure 로 검증해 두 표면의 강도를 맞춥니다.
|
||||
*
|
||||
* @return \Closure 검증 closure
|
||||
*/
|
||||
protected function publicAssetDiskRule(): \Closure
|
||||
{
|
||||
return function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === null || $value === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! app(DriverRegistryService::class)->isDriverAvailable('public_asset', $value)) {
|
||||
$fail(__('sirsoft-ecommerce::validation.public_asset_disk_invalid'));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 속성명 다국어 처리
|
||||
*
|
||||
|
||||
+2
-1
@@ -67,7 +67,8 @@ class UploadReviewImageRequest extends FormRequest
|
||||
return (int) module_setting(
|
||||
'sirsoft-ecommerce',
|
||||
'review_settings.max_image_size_mb',
|
||||
config('ecommerce.review.max_image_size_mb', 10)
|
||||
// 모듈 config 는 'sirsoft-ecommerce' 네임스페이스로 로드된다 (ModuleManager::loadModuleConfig)
|
||||
config('sirsoft-ecommerce.review.max_image_size_mb', 10)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,14 @@ use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Concerns\HasDirectAssetUrl;
|
||||
|
||||
/**
|
||||
* 카테고리 이미지 모델
|
||||
*/
|
||||
class CategoryImage extends Model
|
||||
{
|
||||
use HasDirectAssetUrl;
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'ecommerce_category_images';
|
||||
@@ -108,11 +110,11 @@ class CategoryImage extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* `download_url` 가상 attribute — hash 기반 카테고리 이미지 서빙 API URL.
|
||||
* hash 기반 카테고리 이미지 서빙 API URL (직접 URL 불가 시 폴백).
|
||||
*
|
||||
* @return string `/api/modules/sirsoft-ecommerce/category-image/{hash}` 형식 URL
|
||||
*/
|
||||
public function getDownloadUrlAttribute(): string
|
||||
protected function apiDownloadUrl(): string
|
||||
{
|
||||
return '/api/modules/sirsoft-ecommerce/category-image/'.$this->hash;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Models\Concerns;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Support\AssetStorage;
|
||||
|
||||
/**
|
||||
* 공개 자산 모델 공용 download_url 해석 trait
|
||||
*
|
||||
* 행에 기록된 disk 로 직접 URL(CDN) 생성을 시도하고, 불가하면(로컬 디스크,
|
||||
* url 미설정 디스크, 훅 차단 등) 기존 API 서빙 경로로 폴백합니다.
|
||||
* 디스크 전환 이전에 업로드된 로컬 행과 이후의 원격 행이 혼재해도
|
||||
* 각 행이 자기 disk 기준으로 올바른 URL 을 얻습니다.
|
||||
*
|
||||
* 스토리지 카테고리는 directUrlCategory() 오버라이드로 바꿀 수 있어(기본 'images')
|
||||
* 이미지 외의 완전 공개 자산 모델도 재사용할 수 있습니다. 단, 권한 검사가 걸린
|
||||
* 첨부파일(비밀글/회원 전용 게시판 등)에는 배선하지 않습니다 — 직접 URL 은
|
||||
* 서버 스트리밍 경로의 권한 검사를 우회합니다.
|
||||
*/
|
||||
trait HasDirectAssetUrl
|
||||
{
|
||||
/**
|
||||
* `download_url` 가상 attribute — 직접 URL 우선, 불가 시 API 서빙 URL.
|
||||
*
|
||||
* @return string 자산 URL
|
||||
*/
|
||||
public function getDownloadUrlAttribute(): string
|
||||
{
|
||||
return $this->resolveDirectUrl() ?? $this->apiDownloadUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 disk 기준 직접 URL 해석을 시도합니다.
|
||||
*
|
||||
* @return string|null 직접 URL (불가하면 null)
|
||||
*/
|
||||
protected function resolveDirectUrl(): ?string
|
||||
{
|
||||
$disk = (string) ($this->disk ?? '');
|
||||
$path = (string) ($this->path ?? '');
|
||||
|
||||
if ($disk === '' || $path === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return AssetStorage::forDisk($disk)->url($this->directUrlCategory(), $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 직접 URL 해석에 쓸 스토리지 카테고리를 반환합니다.
|
||||
*
|
||||
* @return string 스토리지 카테고리 (기본 'images')
|
||||
*/
|
||||
protected function directUrlCategory(): string
|
||||
{
|
||||
return 'images';
|
||||
}
|
||||
|
||||
/**
|
||||
* 기존 API 서빙 경로를 반환합니다 (직접 URL 불가 시 폴백).
|
||||
*
|
||||
* @return string API 서빙 URL
|
||||
*/
|
||||
abstract protected function apiDownloadUrl(): string;
|
||||
}
|
||||
@@ -3,16 +3,19 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductImageCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Concerns\HasDirectAssetUrl;
|
||||
|
||||
/**
|
||||
* 상품 이미지 모델
|
||||
*/
|
||||
class ProductImage extends Model
|
||||
{
|
||||
use HasDirectAssetUrl;
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'ecommerce_product_images';
|
||||
@@ -116,9 +119,9 @@ class ProductImage extends Model
|
||||
/**
|
||||
* 특정 컬렉션(main/gallery/detail 등) 의 이미지만 필터링하는 쿼리 스코프.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @param Builder $query
|
||||
* @param ProductImageCollection $collection 필터링할 이미지 컬렉션 enum
|
||||
* @return \Illuminate\Database\Eloquent\Builder
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeByCollection($query, ProductImageCollection $collection)
|
||||
{
|
||||
@@ -128,8 +131,8 @@ class ProductImage extends Model
|
||||
/**
|
||||
* 대표 이미지만 조회
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder $query
|
||||
* @return \Illuminate\Database\Eloquent\Builder
|
||||
* @param Builder $query
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeThumbnails($query)
|
||||
{
|
||||
@@ -137,11 +140,11 @@ class ProductImage extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* `download_url` 가상 attribute — hash 기반 상품 이미지 서빙 API URL.
|
||||
* hash 기반 상품 이미지 서빙 API URL (직접 URL 불가 시 폴백).
|
||||
*
|
||||
* @return string `/api/modules/sirsoft-ecommerce/product-image/{hash}` 형식 URL
|
||||
*/
|
||||
public function getDownloadUrlAttribute(): string
|
||||
protected function apiDownloadUrl(): string
|
||||
{
|
||||
return '/api/modules/sirsoft-ecommerce/product-image/'.$this->hash;
|
||||
}
|
||||
|
||||
@@ -8,12 +8,14 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\ProductReviewImageFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Concerns\HasDirectAssetUrl;
|
||||
|
||||
/**
|
||||
* 상품 리뷰 이미지 모델
|
||||
*/
|
||||
class ProductReviewImage extends Model
|
||||
{
|
||||
use HasDirectAssetUrl;
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
protected $table = 'ecommerce_product_review_images';
|
||||
@@ -103,11 +105,11 @@ class ProductReviewImage extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* 다운로드 URL 반환 (API 서빙 URL)
|
||||
* hash 기반 리뷰 이미지 서빙 API URL (직접 URL 불가 시 폴백).
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getDownloadUrlAttribute(): string
|
||||
protected function apiDownloadUrl(): string
|
||||
{
|
||||
return '/api/modules/sirsoft-ecommerce/review-image/'.$this->hash;
|
||||
}
|
||||
|
||||
@@ -119,10 +119,21 @@ class EcommerceServiceProvider extends BaseModuleServiceProvider
|
||||
* @var array<int, class-string>
|
||||
*/
|
||||
protected array $storageServices = [
|
||||
CategoryImageService::class,
|
||||
ProductImageService::class,
|
||||
ProductReviewService::class,
|
||||
ProductReviewImageService::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* 카테고리별 StorageInterface가 필요한 서비스 매핑 (클래스 ⇒ 카테고리)
|
||||
*
|
||||
* 이미지 서비스는 getStorageDiskFor('images') 가 결정한 디스크(공개 자산 디스크
|
||||
* 설정 반영)를 주입받아, put/getDisk() 행 기록이 자동으로 카테고리 디스크를 따릅니다.
|
||||
*
|
||||
* @var array<class-string, string>
|
||||
*/
|
||||
protected array $storageCategoryServices = [
|
||||
CategoryImageService::class => 'images',
|
||||
ProductImageService::class => 'images',
|
||||
ProductReviewImageService::class => 'images',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,6 +12,7 @@ use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Sirsoft\Ecommerce\Models\CategoryImage;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CategoryImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Services\Concerns\ResolvesRowStorage;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
@@ -21,6 +22,8 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
*/
|
||||
class CategoryImageService
|
||||
{
|
||||
use ResolvesRowStorage;
|
||||
|
||||
/**
|
||||
* CategoryImageService 생성자
|
||||
*
|
||||
@@ -174,7 +177,7 @@ class CategoryImageService
|
||||
return null;
|
||||
}
|
||||
|
||||
$response = $this->storage->response(
|
||||
$response = $this->storageForRow($image->disk)->response(
|
||||
'images',
|
||||
$image->path,
|
||||
$image->original_filename,
|
||||
@@ -188,7 +191,7 @@ class CategoryImageService
|
||||
Log::error('카테고리 이미지 스토리지에 없음', [
|
||||
'category_image_id' => $image->id,
|
||||
'path' => $image->path,
|
||||
'disk' => $this->storage->getDisk(),
|
||||
'disk' => $image->disk ?: $this->storage->getDisk(),
|
||||
]);
|
||||
|
||||
return null;
|
||||
@@ -218,11 +221,12 @@ class CategoryImageService
|
||||
// Before 훅
|
||||
HookManager::doAction('sirsoft-ecommerce.category-image.before_delete', $image);
|
||||
|
||||
// 스토리지에서 파일 삭제
|
||||
// 스토리지에서 파일 삭제 — 행 disk 기준
|
||||
// DB에 저장된 경로: category/{date}/{filename}
|
||||
// storage->exists/delete에 category를 전달하면 자동으로 images/ 추가됨
|
||||
if ($this->storage->exists('images', $image->path)) {
|
||||
$this->storage->delete('images', $image->path);
|
||||
$rowStorage = $this->storageForRow($image->disk);
|
||||
if ($rowStorage->exists('images', $image->path)) {
|
||||
$rowStorage->delete('images', $image->path);
|
||||
}
|
||||
|
||||
// DB에서 삭제
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Services\Concerns;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
|
||||
/**
|
||||
* 이미지 행 disk 기준 스토리지 해석 trait (서비스 공용)
|
||||
*
|
||||
* 디스크 전환 이후에도 전환 이전 행(구 disk)의 서빙/삭제/이동이 그 행의
|
||||
* 실제 저장 위치를 향하도록, 행에 기록된 disk 의 스토리지를 돌려줍니다.
|
||||
* 사용 서비스는 `protected StorageInterface $storage` 주입을 전제로 합니다.
|
||||
*/
|
||||
trait ResolvesRowStorage
|
||||
{
|
||||
/**
|
||||
* 이미지 행에 기록된 disk 기준 스토리지를 반환합니다.
|
||||
*
|
||||
* @param string|null $disk 이미지 행의 disk 컬럼 값 (비어 있으면 주입 스토리지)
|
||||
* @return StorageInterface 행 disk 의 스토리지
|
||||
*/
|
||||
protected function storageForRow(?string $disk): StorageInterface
|
||||
{
|
||||
if ($disk === null || $disk === '' || $disk === $this->storage->getDisk()) {
|
||||
return $this->storage;
|
||||
}
|
||||
|
||||
// 고아 disk 방어 — 디스크를 제공하던 플러그인이 비활성화되면 그 disk 가
|
||||
// config 에서 사라지는데, 미등록 disk 로 withDisk 를 만들면 이후 exists/response/
|
||||
// delete 가 InvalidArgumentException 을 던져 서빙·삭제가 500 이 된다.
|
||||
// AbstractModule::resolvePublicAssetDisk() 와 동일한 존재 검증으로 주입 스토리지에
|
||||
// 폴백한다 (파일은 도달 불가이므로 404 가 정상 degradation).
|
||||
if (config("filesystems.disks.{$disk}") === null) {
|
||||
return $this->storage;
|
||||
}
|
||||
|
||||
return $this->storage->withDisk($disk);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use Modules\Sirsoft\Ecommerce\Exceptions\ResourceScopeMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductImage;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Services\Concerns\ResolvesRowStorage;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
@@ -25,6 +26,8 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
*/
|
||||
class ProductImageService
|
||||
{
|
||||
use ResolvesRowStorage;
|
||||
|
||||
/**
|
||||
* ProductImageService 생성자
|
||||
*
|
||||
@@ -193,11 +196,12 @@ class ProductImageService
|
||||
// 새 경로 생성: products/{productCode}/{filename}
|
||||
$newPath = "products/{$productCode}/{$image->stored_filename}";
|
||||
|
||||
// 파일 이동 (get + put + delete)
|
||||
$content = $this->storage->get('images', $image->path);
|
||||
// 파일 이동 (get + put + delete) — 행 disk 기준 (이동 후에도 행 disk 불변)
|
||||
$rowStorage = $this->storageForRow($image->disk);
|
||||
$content = $rowStorage->get('images', $image->path);
|
||||
if ($content) {
|
||||
$this->storage->put('images', $newPath, $content);
|
||||
$this->storage->delete('images', $image->path);
|
||||
$rowStorage->put('images', $newPath, $content);
|
||||
$rowStorage->delete('images', $image->path);
|
||||
}
|
||||
|
||||
// DB 업데이트: product_id 설정, temp_key 제거, path 변경, sort_order 재배치, is_thumbnail 해제
|
||||
@@ -212,7 +216,10 @@ class ProductImageService
|
||||
$linkedCount++;
|
||||
}
|
||||
|
||||
// 빈 임시 디렉토리 정리
|
||||
// 빈 임시 디렉토리 정리 — 임시 행이 여러 disk 에 걸칠 수 있어 disk 별로 정리
|
||||
foreach ($tempImages->pluck('disk')->filter()->unique() as $tempDisk) {
|
||||
$this->storageForRow($tempDisk)->deleteDirectory('images', "products/temp/{$tempKey}");
|
||||
}
|
||||
$this->storage->deleteDirectory('images', "products/temp/{$tempKey}");
|
||||
|
||||
return $linkedCount;
|
||||
@@ -262,9 +269,10 @@ class ProductImageService
|
||||
// Before 훅
|
||||
HookManager::doAction('sirsoft-ecommerce.product-image.before_delete', $image);
|
||||
|
||||
// 스토리지에서 파일 삭제
|
||||
if ($this->storage->exists('images', $image->path)) {
|
||||
$this->storage->delete('images', $image->path);
|
||||
// 스토리지에서 파일 삭제 — 행 disk 기준
|
||||
$rowStorage = $this->storageForRow($image->disk);
|
||||
if ($rowStorage->exists('images', $image->path)) {
|
||||
$rowStorage->delete('images', $image->path);
|
||||
}
|
||||
|
||||
// DB에서 삭제
|
||||
@@ -350,7 +358,7 @@ class ProductImageService
|
||||
return null;
|
||||
}
|
||||
|
||||
$response = $this->storage->response(
|
||||
$response = $this->storageForRow($image->disk)->response(
|
||||
'images',
|
||||
$image->path,
|
||||
$image->original_filename,
|
||||
@@ -364,7 +372,7 @@ class ProductImageService
|
||||
Log::error('상품 이미지 스토리지에 없음', [
|
||||
'product_image_id' => $image->id,
|
||||
'path' => $image->path,
|
||||
'disk' => $this->storage->getDisk(),
|
||||
'disk' => $image->disk ?: $this->storage->getDisk(),
|
||||
]);
|
||||
|
||||
return null;
|
||||
@@ -406,10 +414,11 @@ class ProductImageService
|
||||
$newStoredFilename = Str::uuid().'.'.$extension;
|
||||
$newPath = "products/{$targetProductCode}/{$newStoredFilename}";
|
||||
|
||||
// 파일 복사
|
||||
$content = $this->storage->get('images', $source->path);
|
||||
// 파일 복사 — 원본 행 disk 기준 (신규 행도 원본과 같은 disk 로 기록됨)
|
||||
$sourceStorage = $this->storageForRow($source->disk);
|
||||
$content = $sourceStorage->get('images', $source->path);
|
||||
if ($content) {
|
||||
$this->storage->put('images', $newPath, $content);
|
||||
$sourceStorage->put('images', $newPath, $content);
|
||||
} else {
|
||||
Log::warning('상품 이미지 복사 실패: 원본 파일 없음', [
|
||||
'hash' => $sourceHash,
|
||||
@@ -445,18 +454,42 @@ class ProductImageService
|
||||
* 실제 경로: storage/app/modules/sirsoft-ecommerce/images/products/{productCode}/
|
||||
*
|
||||
* @param int $productId 상품 ID
|
||||
* @return bool 삭제 성공 여부
|
||||
* @return bool 삭제 성공 여부 (대상 디스크 전체 기준)
|
||||
*/
|
||||
public function deleteByProductId(int $productId): bool
|
||||
{
|
||||
$product = $this->productRepository->find($productId);
|
||||
|
||||
if ($product) {
|
||||
return $this->storage->deleteDirectory('images', "products/{$product->product_code}");
|
||||
// 행이 여러 disk 에 걸칠 수 있어(디스크 전환 후 혼재) disk 별로 디렉토리 삭제.
|
||||
// 빈 disk(디스크 컬럼 도입 전 구 데이터)는 주입 스토리지 소속으로 정규화한다.
|
||||
$rowDisks = $this->repository->getByProductId($productId)
|
||||
->pluck('disk')
|
||||
->map(fn ($disk) => ($disk === null || $disk === '') ? $this->storage->getDisk() : $disk)
|
||||
->unique();
|
||||
|
||||
$directory = $product
|
||||
? "products/{$product->product_code}"
|
||||
// 폴백: product_id 기반 (기존 데이터 호환)
|
||||
: "products/{$productId}";
|
||||
|
||||
if ($rowDisks->isEmpty()) {
|
||||
// 행이 없으면 주입 스토리지의 잔여 디렉토리만 정리 (기존 동작 보존)
|
||||
return $this->storage->deleteDirectory('images', $directory);
|
||||
}
|
||||
|
||||
// 폴백: product_id 기반 (기존 데이터 호환)
|
||||
return $this->storage->deleteDirectory('images', "products/{$productId}");
|
||||
$results = [];
|
||||
foreach ($rowDisks as $rowDisk) {
|
||||
$results[] = $this->storageForRow($rowDisk)->deleteDirectory('images', $directory);
|
||||
}
|
||||
|
||||
// 행이 실리지 않은 주입 스토리지의 잔여 파일도 정리 시도하되 반환값에는
|
||||
// 반영하지 않는다 — 행 기준으로는 지울 것이 없는 디스크의 실패가 혼재 행
|
||||
// 삭제 성공을 false 로 오염시키면 안 된다 (반환값 = 행이 실린 디스크 전체 기준)
|
||||
if (! $rowDisks->contains($this->storage->getDisk())) {
|
||||
$this->storage->deleteDirectory('images', $directory);
|
||||
}
|
||||
|
||||
return ! in_array(false, $results, true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,6 +13,7 @@ use Modules\Sirsoft\Ecommerce\Exceptions\ReviewImageUploadLimitException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductReview;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductReviewImage;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Services\Concerns\ResolvesRowStorage;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
@@ -22,6 +23,8 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
*/
|
||||
class ProductReviewImageService
|
||||
{
|
||||
use ResolvesRowStorage;
|
||||
|
||||
/**
|
||||
* ProductReviewImageService 생성자
|
||||
*
|
||||
@@ -48,7 +51,8 @@ class ProductReviewImageService
|
||||
{
|
||||
$maxImages = (int) $this->settingsService->getSetting(
|
||||
'review_settings.max_images',
|
||||
config('ecommerce.review.max_images', 5)
|
||||
// 모듈 config 는 'sirsoft-ecommerce' 네임스페이스로 로드된다 (ModuleManager::loadModuleConfig)
|
||||
config('sirsoft-ecommerce.review.max_images', 5)
|
||||
);
|
||||
|
||||
$currentCount = $review->images()->count();
|
||||
@@ -121,8 +125,10 @@ class ProductReviewImageService
|
||||
{
|
||||
HookManager::doAction('sirsoft-ecommerce.review-image.before_delete', $image);
|
||||
|
||||
if ($this->storage->exists('images', $image->path)) {
|
||||
$this->storage->delete('images', $image->path);
|
||||
// 스토리지에서 파일 삭제 — 행 disk 기준
|
||||
$rowStorage = $this->storageForRow($image->disk);
|
||||
if ($rowStorage->exists('images', $image->path)) {
|
||||
$rowStorage->delete('images', $image->path);
|
||||
}
|
||||
|
||||
$result = $this->repository->delete($image);
|
||||
@@ -159,7 +165,7 @@ class ProductReviewImageService
|
||||
return null;
|
||||
}
|
||||
|
||||
$response = $this->storage->response(
|
||||
$response = $this->storageForRow($image->disk)->response(
|
||||
'images',
|
||||
$image->path,
|
||||
$image->original_filename,
|
||||
|
||||
@@ -15,6 +15,7 @@ use Modules\Sirsoft\Ecommerce\Models\ProductReview;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderOptionRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Services\Concerns\ResolvesRowStorage;
|
||||
use Modules\Sirsoft\Ecommerce\Support\ReviewWritePolicy;
|
||||
|
||||
/**
|
||||
@@ -24,6 +25,8 @@ use Modules\Sirsoft\Ecommerce\Support\ReviewWritePolicy;
|
||||
*/
|
||||
class ProductReviewService
|
||||
{
|
||||
use ResolvesRowStorage;
|
||||
|
||||
/**
|
||||
* ProductReviewService 생성자
|
||||
*
|
||||
@@ -217,10 +220,11 @@ class ProductReviewService
|
||||
HookManager::doAction('sirsoft-ecommerce.product-review.before_delete', $review);
|
||||
|
||||
return DB::transaction(function () use ($review) {
|
||||
// 이미지 파일 삭제 (StorageInterface 사용)
|
||||
// 이미지 파일 삭제 (StorageInterface 사용) — 행 disk 기준
|
||||
foreach ($review->images as $image) {
|
||||
if ($this->storage->exists('images', $image->path)) {
|
||||
$this->storage->delete('images', $image->path);
|
||||
$rowStorage = $this->storageForRow($image->disk);
|
||||
if ($rowStorage->exists('images', $image->path)) {
|
||||
$rowStorage->delete('images', $image->path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,11 +270,12 @@ class ProductReviewService
|
||||
HookManager::doAction('sirsoft-ecommerce.product-review.before_bulk_delete', $ids, $reviews);
|
||||
|
||||
return DB::transaction(function () use ($reviews, $ids, $snapshots) {
|
||||
// 이미지 파일 일괄 삭제
|
||||
// 이미지 파일 일괄 삭제 — 행 disk 기준
|
||||
foreach ($reviews as $review) {
|
||||
foreach ($review->images as $image) {
|
||||
if ($this->storage->exists('images', $image->path)) {
|
||||
$this->storage->delete('images', $image->path);
|
||||
$rowStorage = $this->storageForRow($image->disk);
|
||||
if ($rowStorage->exists('images', $image->path)) {
|
||||
$rowStorage->delete('images', $image->path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1616,7 +1616,7 @@ class ProductService
|
||||
'hash' => $img->hash,
|
||||
'url' => $img->url,
|
||||
'original_filename' => $img->original_filename,
|
||||
'download_url' => '/api/modules/sirsoft-ecommerce/product-image/'.$img->hash,
|
||||
'download_url' => $img->download_url,
|
||||
'file_size' => $img->file_size,
|
||||
'size' => $img->file_size,
|
||||
'size_formatted' => $this->formatFileSize($img->file_size),
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Support;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Extension\Storage\ModuleStorageDriver;
|
||||
|
||||
/**
|
||||
* 자산 행 disk 기준 스토리지 드라이버 팩토리
|
||||
*
|
||||
* 자산 행마다 기록된 disk 가 다를 수 있어(디스크 전환 후 혼재 운용),
|
||||
* 행 disk 별 ModuleStorageDriver 인스턴스를 memoize 하여 제공합니다.
|
||||
* 모델 accessor(HasDirectAssetUrl)가 직렬화 루프에서 반복 호출하므로
|
||||
* 드라이버 생성 비용을 요청 단위 1회로 고정합니다.
|
||||
*/
|
||||
class AssetStorage
|
||||
{
|
||||
/**
|
||||
* 디스크명 키 드라이버 캐시
|
||||
*
|
||||
* @var array<string, StorageInterface>
|
||||
*/
|
||||
private static array $drivers = [];
|
||||
|
||||
/**
|
||||
* 지정 디스크의 ecommerce 모듈 스토리지 드라이버를 반환합니다.
|
||||
*
|
||||
* @param string $disk 디스크 이름 (자산 행의 disk 컬럼 값)
|
||||
* @return StorageInterface 해당 디스크의 스토리지 드라이버
|
||||
*/
|
||||
public static function forDisk(string $disk): StorageInterface
|
||||
{
|
||||
return self::$drivers[$disk] ??= new ModuleStorageDriver('sirsoft-ecommerce', $disk);
|
||||
}
|
||||
|
||||
/**
|
||||
* memoize 캐시를 비웁니다 (테스트 격리용).
|
||||
*/
|
||||
public static function flush(): void
|
||||
{
|
||||
self::$drivers = [];
|
||||
}
|
||||
}
|
||||
@@ -1327,8 +1327,14 @@ return [
|
||||
],
|
||||
],
|
||||
|
||||
// Public asset disk (validated against the core catalog)
|
||||
'public_asset_disk_invalid' => 'Please select a valid public asset disk.',
|
||||
|
||||
// Field name translations (Laravel standard)
|
||||
'attributes' => [
|
||||
// Public asset storage
|
||||
'basic_info.public_asset_disk' => 'Public asset disk',
|
||||
|
||||
// Shipping policy country settings
|
||||
'country_settings' => 'Country settings',
|
||||
'country_settings.*.country_code' => 'Country',
|
||||
|
||||
@@ -1327,8 +1327,14 @@ return [
|
||||
],
|
||||
],
|
||||
|
||||
// 공개 자산 디스크 (코어 카탈로그 조회 검증)
|
||||
'public_asset_disk_invalid' => '올바른 공개 자산 디스크를 선택해주세요.',
|
||||
|
||||
// 필드명 한국어 변환 (Laravel 표준)
|
||||
'attributes' => [
|
||||
// 공개 자산 스토리지
|
||||
'basic_info.public_asset_disk' => '공개 자산 디스크',
|
||||
|
||||
// 배송정책 국가별 설정
|
||||
'country_settings' => '국가별 설정',
|
||||
'country_settings.*.country_code' => '국가',
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* E2E: 이커머스 공개 자산 디스크 오버라이드 필드 (공개#100)
|
||||
*
|
||||
* 시나리오 매니페스트: `tests/scenarios/public-asset-cdn.yaml`
|
||||
* (케이스 마킹은 각 test 의 라인 주석에 있다 — 축 구분자는 쉼표)
|
||||
*
|
||||
* 기본정보 탭의 "공개 자산 디스크" Select 가 [코어 설정 따름('')] + 코어 카탈로그를
|
||||
* 그리는지, 그리고 선택→저장→재진입 왕복에서 값이 유지되는지 검증한다.
|
||||
* 코어 드라이버 탭 카드는 admin_basic 템플릿 spec 이 담당한다 — 여기서는 모듈이
|
||||
* 소유한 오버라이드 표면만 본다.
|
||||
*
|
||||
* composite Select 는 네이티브 select 가 아니라 커스텀 드롭다운(root div 에 name 속성,
|
||||
* Button 토글, portal listbox role=option)이다 — 상호작용은 그 구조를 따른다.
|
||||
* 저장 후에는 반드시 원값으로 되돌려 사이트 설정을 바꾸지 않는다.
|
||||
*
|
||||
* @effects settings_catalog_includes_plugin_registered_disks,
|
||||
* none_override_forces_streaming_over_global
|
||||
*/
|
||||
import { test, expect, authenticatePage } from '../../fixtures/ecommerce-auth';
|
||||
import type { Page } from '@playwright/test';
|
||||
|
||||
const ECOMMERCE_BASIC_TAB = '/admin/ecommerce/settings?tab=basic_info';
|
||||
const MODULE_SELECT_ROOT = '[name="basic_info.public_asset_disk"]';
|
||||
|
||||
/**
|
||||
* 기본정보 탭 진입 — 카탈로그 적재를 엔진 상태로 확인한다.
|
||||
*
|
||||
* DOM attach 만 기다리면 바인딩 전 빈 Select 를 카탈로그 누락으로 오인한다.
|
||||
*
|
||||
* @param page Playwright 페이지
|
||||
*/
|
||||
async function gotoBasicInfoTab(page: Page): Promise<void> {
|
||||
await page.goto(ECOMMERCE_BASIC_TAB);
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
await page.evaluate(() => {
|
||||
const local = (window as any).G7Core?.state?.getLocal?.();
|
||||
return Array.isArray(local?.form?.available_public_asset_disks);
|
||||
}),
|
||||
{ timeout: 20_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 드롭다운을 열고 옵션 라벨 목록을 읽는다 (읽은 뒤 드롭다운은 닫지 않음).
|
||||
*
|
||||
* @param page Playwright 페이지
|
||||
* @returns 옵션 라벨 배열
|
||||
*/
|
||||
async function openAndReadOptions(page: Page): Promise<string[]> {
|
||||
await page.locator(`${MODULE_SELECT_ROOT} button`).first().click();
|
||||
const listbox = page.locator('[role="listbox"]');
|
||||
await expect(listbox).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
return listbox.locator('[role="option"]').allInnerTexts();
|
||||
}
|
||||
|
||||
/**
|
||||
* 엔진 로컬 상태에서 오버라이드 필드 값을 읽는다.
|
||||
*
|
||||
* @param page Playwright 페이지
|
||||
* @returns 현재 폼 값 (미설정이면 '')
|
||||
*/
|
||||
async function readOverrideValue(page: Page): Promise<unknown> {
|
||||
return page.evaluate(() => {
|
||||
const form = (window as any).G7Core?.state?.getLocal?.()?.form;
|
||||
return form?.basic_info?.public_asset_disk ?? '';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 드롭다운에서 라벨로 옵션을 고른다.
|
||||
*
|
||||
* @param page Playwright 페이지
|
||||
* @param label 고를 옵션 라벨(부분 일치)
|
||||
*/
|
||||
async function selectOptionByLabel(page: Page, label: string): Promise<void> {
|
||||
await openAndReadOptions(page);
|
||||
await page.locator('[role="listbox"] [role="option"]', { hasText: label }).first().click();
|
||||
}
|
||||
|
||||
/** 저장 버튼을 눌러 성공 토스트를 기다린다. */
|
||||
async function save(page: Page): Promise<void> {
|
||||
await page.locator('#save_button button, button#save_button, [data-testid="settings-save-button"]').first().click();
|
||||
await expect(page.getByText('설정이 저장되었습니다')).toBeVisible({ timeout: 20_000 });
|
||||
}
|
||||
|
||||
test.describe('이커머스 공개 자산 디스크 오버라이드', () => {
|
||||
// @scenario consumer=product, disk_setting=none, e2e=ecommerce_settings_field, hook=unregistered, override=follow_core, row_state=legacy_local_row
|
||||
// @effects settings_catalog_includes_plugin_registered_disks
|
||||
test('코어 따름 기본 옵션 + 코어 카탈로그를 그린다', async ({ page, settingsToken }) => {
|
||||
await authenticatePage(page, settingsToken);
|
||||
await gotoBasicInfoTab(page);
|
||||
|
||||
await expect(page.locator(MODULE_SELECT_ROOT)).toBeVisible({ timeout: 20_000 });
|
||||
|
||||
const labels = await openAndReadOptions(page);
|
||||
// 첫 옵션 = 코어 설정 따름('') + 카탈로그(none 포함 — 강제 스트리밍 오버라이드)
|
||||
expect(labels[0]).toContain('코어 설정 따름');
|
||||
expect(labels.join('|')).toContain('사용 안 함');
|
||||
expect(labels.join('|')).toContain('Amazon S3');
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
});
|
||||
|
||||
// @scenario consumer=product, disk_setting=public, e2e=save_roundtrip, hook=unregistered, override=module_override, row_state=new_remote_row
|
||||
// @effects none_override_forces_streaming_over_global
|
||||
test('선택-저장-재진입 왕복에서 오버라이드 값이 유지되고 원복된다', async ({ page, settingsToken }) => {
|
||||
test.setTimeout(150_000);
|
||||
await authenticatePage(page, settingsToken);
|
||||
await gotoBasicInfoTab(page);
|
||||
|
||||
const original = (await readOverrideValue(page)) as string;
|
||||
|
||||
// 모듈 개별 오버라이드로 Public 디스크 지정 → 저장
|
||||
await selectOptionByLabel(page, 'Public');
|
||||
await expect.poll(() => readOverrideValue(page)).toBe('public');
|
||||
await save(page);
|
||||
|
||||
// 재진입 — 서버 저장값이 폼으로 복원되는지 (저장 응답의 카탈로그 재부착 포함)
|
||||
await gotoBasicInfoTab(page);
|
||||
await expect.poll(() => readOverrideValue(page), { timeout: 20_000 }).toBe('public');
|
||||
|
||||
// 원복 (사이트 설정 보존)
|
||||
const restoreLabel =
|
||||
original === 'public' ? 'Public' : original === 's3' ? 'Amazon S3' : original === 'none' ? '사용 안 함' : '코어 설정 따름';
|
||||
await selectOptionByLabel(page, restoreLabel);
|
||||
await save(page);
|
||||
|
||||
await gotoBasicInfoTab(page);
|
||||
await expect.poll(() => readOverrideValue(page), { timeout: 20_000 }).toBe(original || '');
|
||||
});
|
||||
});
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Http\Requests;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreEcommerceSettingsRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 이커머스 공개 자산 디스크 저장 검증 테스트 (공개#100)
|
||||
*
|
||||
* 모듈 오버라이드 필드도 코어 환경설정(SaveSettingsRequest)과 같은 강도로 검증한다.
|
||||
* 이 게이트가 없으면 오타 디스크명이 200 으로 저장된 뒤 런타임 폴백만 남아,
|
||||
* 운영자에게는 "저장은 됐는데 CDN 이 안 붙는" 무증상 상태로만 보인다.
|
||||
*
|
||||
* 선택지는 코어 3종 + 플러그인 훅 등록 디스크라 정적 in 으로 고정할 수 없으므로,
|
||||
* 카탈로그 게터(SSoT)를 조회하는 closure 가 실제로 걸려 있는지를 고정한다.
|
||||
*
|
||||
* @effects invalid_disk_rejected_with_422, settings_catalog_includes_plugin_registered_disks
|
||||
*/
|
||||
class StoreEcommerceSettingsRequestPublicAssetDiskTest extends ModuleTestCase
|
||||
{
|
||||
protected function tearDown(): void
|
||||
{
|
||||
HookManager::resetAll();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* basic_info 탭 저장 요청을 해석합니다.
|
||||
*
|
||||
* @param string $disk public_asset_disk 값
|
||||
*/
|
||||
private function resolve(string $disk): StoreEcommerceSettingsRequest
|
||||
{
|
||||
$request = StoreEcommerceSettingsRequest::create('/', 'POST', [
|
||||
'_tab' => 'basic_info',
|
||||
'basic_info' => [
|
||||
// 같은 탭의 필수 형제 필드 — 이 축과 무관하지만 없으면 탭 전체가 422 라
|
||||
// 디스크 규칙만 분리해 보기 위해 채운다.
|
||||
'shop_name' => '테스트 상점',
|
||||
'route_path' => 'shop',
|
||||
'public_asset_disk' => $disk,
|
||||
],
|
||||
]);
|
||||
$request->setContainer($this->app)->setRedirector($this->app['redirect']);
|
||||
$request->validateResolved();
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
public function test_core_catalog_disk_is_accepted(): void
|
||||
{
|
||||
$request = $this->resolve('public');
|
||||
|
||||
$this->assertSame('public', $request->validated()['basic_info']['public_asset_disk']);
|
||||
}
|
||||
|
||||
public function test_empty_value_is_accepted_as_follow_core(): void
|
||||
{
|
||||
$request = $this->resolve('');
|
||||
|
||||
// 빈 값 = "코어 설정 따름" 이므로 검증을 통과해야 한다.
|
||||
$this->assertSame('', $request->validated()['basic_info']['public_asset_disk'] ?? '');
|
||||
}
|
||||
|
||||
public function test_unknown_disk_is_rejected(): void
|
||||
{
|
||||
$this->expectException(ValidationException::class);
|
||||
|
||||
try {
|
||||
$this->resolve('nonexistent_disk');
|
||||
} catch (ValidationException $e) {
|
||||
$this->assertArrayHasKey(
|
||||
'basic_info.public_asset_disk',
|
||||
$e->validator->errors()->toArray(),
|
||||
'카탈로그에 없는 디스크는 basic_info.public_asset_disk 오류를 내야 한다'
|
||||
);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function test_plugin_registered_disk_is_accepted(): void
|
||||
{
|
||||
// 플러그인이 훅으로 등록한 디스크도 통과해야 한다 — 정적 in 이었다면 여기서 깨진다.
|
||||
Config::set('filesystems.disks.plugin_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/plugin_cdn'),
|
||||
'url' => 'https://plugin-cdn.test/assets',
|
||||
]);
|
||||
|
||||
HookManager::addFilter(
|
||||
'core.settings.available_public_asset_drivers',
|
||||
function (array $drivers): array {
|
||||
$drivers[] = [
|
||||
'id' => 'plugin_cdn',
|
||||
'label' => ['ko' => '플러그인 CDN', 'en' => 'Plugin CDN'],
|
||||
'provider' => 'test-plugin',
|
||||
];
|
||||
|
||||
return $drivers;
|
||||
}
|
||||
);
|
||||
|
||||
$request = $this->resolve('plugin_cdn');
|
||||
|
||||
$this->assertSame('plugin_cdn', $request->validated()['basic_info']['public_asset_disk']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Models;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Modules\Sirsoft\Ecommerce\Models\CategoryImage;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductImage;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductReviewImage;
|
||||
use Modules\Sirsoft\Ecommerce\Support\AssetStorage;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* HasDirectAssetUrl(download_url 직접 URL/폴백) 단위 테스트
|
||||
*
|
||||
* 행 disk 가 직접 URL 지원 디스크(fake_cdn)면 CDN URL, 아니면 기존 API 경로 폴백을
|
||||
* 3개 이미지 모델(상품/카테고리/리뷰)에서 검증합니다. 혼재 운용(구 로컬 행 + 신규
|
||||
* 원격 행)과 훅 차단 폴백도 함께 고정합니다.
|
||||
*/
|
||||
class HasDirectAssetUrlTest extends ModuleTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
AssetStorage::flush();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
AssetStorage::flush();
|
||||
HookManager::resetAll();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function product_image_falls_back_to_api_url_for_local_disk_row(): void
|
||||
{
|
||||
$image = new ProductImage([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'disk' => 'modules',
|
||||
'path' => 'products/P001/a.jpg',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'/api/modules/sirsoft-ecommerce/product-image/aaaabbbbcccc',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function product_image_returns_direct_url_for_cdn_disk_row(): void
|
||||
{
|
||||
$image = new ProductImage([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'disk' => 'fake_cdn',
|
||||
'path' => 'products/P001/a.jpg',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'https://cdn.test/assets/sirsoft-ecommerce/images/products/P001/a.jpg',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario consumer=category, disk_setting=public, e2e=ecommerce_settings_field, hook=supply, override=module_override, row_state=new_remote_row
|
||||
*
|
||||
* @effects download_url_falls_back_to_api_path_when_direct_unavailable
|
||||
*/
|
||||
#[Test]
|
||||
public function category_and_review_images_resolve_direct_url_and_fallback(): void
|
||||
{
|
||||
$cdnCategory = new CategoryImage([
|
||||
'hash' => 'ccc111222333',
|
||||
'disk' => 'fake_cdn',
|
||||
'path' => 'category/2026/01/01/c.jpg',
|
||||
]);
|
||||
$localReview = new ProductReviewImage([
|
||||
'hash' => 'rrr111222333',
|
||||
'disk' => 'modules',
|
||||
'path' => 'reviews/1/r.jpg',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'https://cdn.test/assets/sirsoft-ecommerce/images/category/2026/01/01/c.jpg',
|
||||
$cdnCategory->download_url
|
||||
);
|
||||
$this->assertSame(
|
||||
'/api/modules/sirsoft-ecommerce/review-image/rrr111222333',
|
||||
$localReview->download_url
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function mixed_rows_resolve_urls_per_row_disk(): void
|
||||
{
|
||||
// 혼재 운용 — 디스크 전환 이전 로컬 행과 이후 원격 행이 각자 disk 기준으로 해석
|
||||
$localRow = new ProductImage(['hash' => 'llllllllllll', 'disk' => 'modules', 'path' => 'products/P001/old.jpg']);
|
||||
$remoteRow = new ProductImage(['hash' => 'rrrrrrrrrrrr', 'disk' => 'fake_cdn', 'path' => 'products/P001/new.jpg']);
|
||||
|
||||
$this->assertStringStartsWith('/api/modules/sirsoft-ecommerce/product-image/', $localRow->download_url);
|
||||
$this->assertStringStartsWith('https://cdn.test/assets/', $remoteRow->download_url);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario consumer=review, disk_setting=s3_without_url, e2e=ecommerce_settings_field, hook=unregistered, override=follow_core, row_state=new_remote_row
|
||||
*
|
||||
* @effects download_url_falls_back_to_api_path_when_direct_unavailable
|
||||
*/
|
||||
#[Test]
|
||||
public function blank_disk_or_path_falls_back_to_api_url(): void
|
||||
{
|
||||
$noDisk = new ProductImage(['hash' => 'aaaabbbbcccc', 'disk' => '', 'path' => 'products/P001/a.jpg']);
|
||||
$noPath = new ProductImage(['hash' => 'aaaabbbbcccc', 'disk' => 'fake_cdn', 'path' => '']);
|
||||
|
||||
$this->assertSame('/api/modules/sirsoft-ecommerce/product-image/aaaabbbbcccc', $noDisk->download_url);
|
||||
$this->assertSame('/api/modules/sirsoft-ecommerce/product-image/aaaabbbbcccc', $noPath->download_url);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario consumer=category, disk_setting=none, e2e=ecommerce_settings_field, hook=block, override=follow_core, row_state=legacy_local_row
|
||||
*
|
||||
* @effects download_url_falls_back_to_api_path_when_direct_unavailable
|
||||
*/
|
||||
#[Test]
|
||||
public function hook_block_falls_back_to_api_url(): void
|
||||
{
|
||||
HookManager::addFilter('core.storage.filter_url', fn ($url) => '');
|
||||
|
||||
$image = new ProductImage([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'disk' => 'fake_cdn',
|
||||
'path' => 'products/P001/a.jpg',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'/api/modules/sirsoft-ecommerce/product-image/aaaabbbbcccc',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Services;
|
||||
|
||||
use App\Extension\Storage\ModuleStorageDriver;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Modules\Sirsoft\Ecommerce\Models\CategoryImage;
|
||||
use Modules\Sirsoft\Ecommerce\Services\CategoryImageService;
|
||||
use Modules\Sirsoft\Ecommerce\Support\AssetStorage;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* CategoryImageService 행 disk 기준 서빙/삭제 테스트
|
||||
*
|
||||
* 공개 자산 디스크 전환 이후에도 전환 이전 행(구 disk)의 서빙이 404 가 되지 않고,
|
||||
* 삭제가 그 행의 실제 저장 위치를 향하는지(혼재 운용 정합) 검증합니다.
|
||||
*
|
||||
* CategoryImageServiceTest 는 StorageInterface 를 Mock 으로 대체하므로
|
||||
* 실제 디스크 해석(withDisk) 회귀를 검출할 수 없어 별도 파일로 둡니다.
|
||||
*/
|
||||
class CategoryImageServiceRowDiskTest extends ModuleTestCase
|
||||
{
|
||||
private CategoryImageService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
AssetStorage::flush();
|
||||
|
||||
$this->service = app(CategoryImageService::class);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
AssetStorage::flush();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정 disk 에 파일과 카테고리 이미지 행을 함께 생성합니다.
|
||||
*
|
||||
* @param string $disk 행 disk
|
||||
* @param string $path 이미지 경로 (images/ 하위 상대 경로)
|
||||
* @return CategoryImage 생성된 행
|
||||
*/
|
||||
private function makeRowOnDisk(string $disk, string $path): CategoryImage
|
||||
{
|
||||
(new ModuleStorageDriver('sirsoft-ecommerce', $disk))->put('images', $path, 'image-bytes');
|
||||
|
||||
return CategoryImage::create([
|
||||
'temp_key' => 'category-row-disk-test',
|
||||
'original_filename' => 'category.jpg',
|
||||
'stored_filename' => basename($path),
|
||||
'disk' => $disk,
|
||||
'path' => $path,
|
||||
'mime_type' => 'image/jpeg',
|
||||
'file_size' => 11,
|
||||
'collection' => 'main',
|
||||
'sort_order' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects serve_and_delete_follow_row_disk, mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function download_serves_row_from_its_recorded_disk(): void
|
||||
{
|
||||
// 혼재 운용 — 주입 스토리지 disk 와 다른 disk 의 행도 서빙 가능해야 한다
|
||||
$cdnRow = $this->makeRowOnDisk('fake_cdn', 'category/row-disk-test/cdn.jpg');
|
||||
$localRow = $this->makeRowOnDisk('modules', 'category/row-disk-test/local.jpg');
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->download($cdnRow->hash));
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->download($localRow->hash));
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects serve_and_delete_follow_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_removes_file_on_row_disk(): void
|
||||
{
|
||||
$cdnRow = $this->makeRowOnDisk('fake_cdn', 'category/row-disk-test/del.jpg');
|
||||
$cdnDriver = new ModuleStorageDriver('sirsoft-ecommerce', 'fake_cdn');
|
||||
$this->assertTrue($cdnDriver->exists('images', $cdnRow->path));
|
||||
|
||||
$this->assertTrue($this->service->delete($cdnRow->id));
|
||||
|
||||
$this->assertFalse($cdnDriver->exists('images', $cdnRow->path));
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 disk 를 제공하던 플러그인이 비활성화되어 config 에서 사라진 상태를 만듭니다.
|
||||
*
|
||||
* @param string $disk 사라지게 할 디스크명
|
||||
*/
|
||||
private function vanishDisk(string $disk): void
|
||||
{
|
||||
Config::set("filesystems.disks.{$disk}", null);
|
||||
Storage::forgetDisk($disk);
|
||||
AssetStorage::flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* 고아 disk 행의 서빙은 500 이 아니라 스트리밍 폴백이어야 한다.
|
||||
*
|
||||
* 디스크를 제공하던 플러그인을 비활성화하면 행 disk 가 config 에서 사라진다.
|
||||
* 이때 withDisk 로 미등록 디스크를 만들면 Laravel 이 InvalidArgumentException 을
|
||||
* 던져 서빙이 500 이 된다 — 접근자는 정상적으로 API 경로를 내주므로 사용자에게는
|
||||
* 이미지 링크가 살아 있는데 열면 500 인 상태가 된다.
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function download_falls_back_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'category/row-disk-test/orphan.jpg');
|
||||
$this->vanishDisk('fake_cdn');
|
||||
|
||||
// 예외 없이 폴백 — 파일은 도달 불가이므로 null(404) 이 정상 degradation
|
||||
$this->assertNull($this->service->download($row->hash));
|
||||
}
|
||||
|
||||
/**
|
||||
* 고아 disk 행의 삭제도 예외 없이 완료되어야 한다(카테고리 삭제 자체가 막히면 안 됨).
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_succeeds_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'category/row-disk-test/orphan-del.jpg');
|
||||
$this->vanishDisk('fake_cdn');
|
||||
|
||||
$this->assertTrue($this->service->delete($row->id));
|
||||
$this->assertNull(CategoryImage::find($row->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — SP 카테고리 배선을 실제로 경유해 공개 자산 디스크 설정값이
|
||||
* 신규 행의 disk 컬럼에 기록되는지 단언합니다(배선 회귀 검출).
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_configured_public_asset_disk_on_row(): void
|
||||
{
|
||||
Config::set('core.storage.public_asset_disk', 'fake_cdn');
|
||||
|
||||
$service = app(CategoryImageService::class);
|
||||
$image = $service->upload(UploadedFile::fake()->image('cdn-category.jpg', 40, 40));
|
||||
|
||||
$this->assertSame('fake_cdn', $image->disk);
|
||||
$this->assertTrue(
|
||||
(new ModuleStorageDriver('sirsoft-ecommerce', 'fake_cdn'))->exists('images', $image->path)
|
||||
);
|
||||
|
||||
$this->assertTrue($service->delete($image->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — 공개 자산 디스크 미설정이면 신규 행이 기본 디스크로 기록(현행 보존).
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_base_disk_when_public_asset_disk_unset(): void
|
||||
{
|
||||
Config::set('core.storage.public_asset_disk', '');
|
||||
|
||||
$service = app(CategoryImageService::class);
|
||||
$image = $service->upload(UploadedFile::fake()->image('local-category.jpg', 40, 40));
|
||||
|
||||
$this->assertSame('modules', $image->disk);
|
||||
|
||||
$this->assertTrue($service->delete($image->id));
|
||||
}
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Services;
|
||||
|
||||
use App\Extension\Storage\ModuleStorageDriver;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductImage;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductImageService;
|
||||
use Modules\Sirsoft\Ecommerce\Support\AssetStorage;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* ProductImageService 행 disk 기준 서빙/삭제 테스트
|
||||
*
|
||||
* 디스크 전환 이후에도 전환 이전 행(구 disk)의 서빙이 404 가 되지 않고,
|
||||
* 삭제가 그 행의 실제 저장 위치를 향하는지(혼재 운용 정합) 검증합니다.
|
||||
*/
|
||||
class ProductImageServiceRowDiskTest extends ModuleTestCase
|
||||
{
|
||||
private ProductImageService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
AssetStorage::flush();
|
||||
|
||||
$this->service = app(ProductImageService::class);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
AssetStorage::flush();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정 disk 에 파일과 이미지 행을 함께 생성합니다.
|
||||
*
|
||||
* @param string $disk 행 disk
|
||||
* @param string $path 이미지 경로
|
||||
* @return ProductImage 생성된 행
|
||||
*/
|
||||
private function makeRowOnDisk(string $disk, string $path): ProductImage
|
||||
{
|
||||
(new ModuleStorageDriver('sirsoft-ecommerce', $disk))->put('images', $path, 'image-bytes');
|
||||
|
||||
return ProductImage::create([
|
||||
'temp_key' => 'row-disk-test',
|
||||
'original_filename' => 'a.jpg',
|
||||
'stored_filename' => basename($path),
|
||||
'disk' => $disk,
|
||||
'path' => $path,
|
||||
'mime_type' => 'image/jpeg',
|
||||
'file_size' => 11,
|
||||
'collection' => 'main',
|
||||
'is_thumbnail' => false,
|
||||
'sort_order' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects serve_and_delete_follow_row_disk, mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function download_serves_row_from_its_recorded_disk(): void
|
||||
{
|
||||
// 혼재 운용 — 주입 스토리지 disk 와 다른 disk 의 행도 서빙 가능해야 한다
|
||||
$cdnRow = $this->makeRowOnDisk('fake_cdn', 'products/temp/row-disk-test/cdn.jpg');
|
||||
$localRow = $this->makeRowOnDisk('modules', 'products/temp/row-disk-test/local.jpg');
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->download($cdnRow->hash));
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->download($localRow->hash));
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects serve_and_delete_follow_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_removes_file_on_row_disk(): void
|
||||
{
|
||||
$cdnRow = $this->makeRowOnDisk('fake_cdn', 'products/temp/row-disk-test/del.jpg');
|
||||
$cdnDriver = new ModuleStorageDriver('sirsoft-ecommerce', 'fake_cdn');
|
||||
$this->assertTrue($cdnDriver->exists('images', $cdnRow->path));
|
||||
|
||||
$this->assertTrue($this->service->delete($cdnRow->id));
|
||||
|
||||
$this->assertFalse($cdnDriver->exists('images', $cdnRow->path));
|
||||
}
|
||||
|
||||
/**
|
||||
* deleteByProductId 반환값 — 행이 CDN 디스크에만 있어도 행 disk 삭제 결과를
|
||||
* 반환해야 한다 (기본 디스크의 빈 디렉토리 결과로 오염 금지).
|
||||
*
|
||||
* @effects serve_and_delete_follow_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_by_product_id_returns_row_disk_result_for_cdn_only_rows(): void
|
||||
{
|
||||
$product = Product::create([
|
||||
'product_code' => 'ROWDEL-'.Str::random(6),
|
||||
'name' => ['ko' => '행 disk 삭제 테스트'],
|
||||
'selling_price' => 1000,
|
||||
'stock_quantity' => 1,
|
||||
'sales_status' => 'on_sale',
|
||||
'display_status' => 'visible',
|
||||
]);
|
||||
|
||||
$path = "products/{$product->product_code}/cdn-only.jpg";
|
||||
$cdnDriver = new ModuleStorageDriver('sirsoft-ecommerce', 'fake_cdn');
|
||||
$cdnDriver->put('images', $path, 'image-bytes');
|
||||
ProductImage::create([
|
||||
'product_id' => $product->id,
|
||||
'original_filename' => 'cdn-only.jpg',
|
||||
'stored_filename' => 'cdn-only.jpg',
|
||||
'disk' => 'fake_cdn',
|
||||
'path' => $path,
|
||||
'mime_type' => 'image/jpeg',
|
||||
'file_size' => 11,
|
||||
'collection' => 'main',
|
||||
'is_thumbnail' => false,
|
||||
'sort_order' => 0,
|
||||
]);
|
||||
|
||||
$this->assertTrue($this->service->deleteByProductId($product->id));
|
||||
$this->assertFalse($cdnDriver->exists('images', $path));
|
||||
}
|
||||
|
||||
/**
|
||||
* deleteByProductId — disk 컬럼이 빈 구 데이터 행은 주입 스토리지 소속으로
|
||||
* 정규화되어 함께 삭제된다.
|
||||
*
|
||||
* @effects serve_and_delete_follow_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_by_product_id_normalizes_blank_disk_rows_to_base_storage(): void
|
||||
{
|
||||
$product = Product::create([
|
||||
'product_code' => 'ROWDEL-'.Str::random(6),
|
||||
'name' => ['ko' => '구 데이터 삭제 테스트'],
|
||||
'selling_price' => 1000,
|
||||
'stock_quantity' => 1,
|
||||
'sales_status' => 'on_sale',
|
||||
'display_status' => 'visible',
|
||||
]);
|
||||
|
||||
$path = "products/{$product->product_code}/legacy.jpg";
|
||||
$baseDriver = new ModuleStorageDriver('sirsoft-ecommerce', 'modules');
|
||||
$baseDriver->put('images', $path, 'image-bytes');
|
||||
ProductImage::create([
|
||||
'product_id' => $product->id,
|
||||
'original_filename' => 'legacy.jpg',
|
||||
'stored_filename' => 'legacy.jpg',
|
||||
'disk' => '',
|
||||
'path' => $path,
|
||||
'mime_type' => 'image/jpeg',
|
||||
'file_size' => 11,
|
||||
'collection' => 'main',
|
||||
'is_thumbnail' => false,
|
||||
'sort_order' => 0,
|
||||
]);
|
||||
|
||||
$this->assertTrue($this->service->deleteByProductId($product->id));
|
||||
$this->assertFalse($baseDriver->exists('images', $path));
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — SP 카테고리 배선(storageCategoryServices)을 실제로 경유해
|
||||
* 공개 자산 디스크 설정값이 신규 행의 disk 컬럼에 기록되는지 단언합니다.
|
||||
* (픽스처 disk 직접 주입이 아니라 실제 업로드 경로 — 배선 회귀 검출)
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_configured_public_asset_disk_on_row(): void
|
||||
{
|
||||
Config::set('core.storage.public_asset_disk', 'fake_cdn');
|
||||
|
||||
// 컨테이너에서 새로 해석 — contextual binding 이 getStorageFor('images') 를 평가
|
||||
$service = app(ProductImageService::class);
|
||||
|
||||
$image = $service->upload(
|
||||
UploadedFile::fake()->image('cdn-upload.jpg', 40, 40)
|
||||
);
|
||||
|
||||
$this->assertSame('fake_cdn', $image->disk);
|
||||
$this->assertTrue(
|
||||
(new ModuleStorageDriver('sirsoft-ecommerce', 'fake_cdn'))->exists('images', $image->path)
|
||||
);
|
||||
|
||||
// 뒷정리 — 업로드 파일 제거 (행 disk 기준 삭제)
|
||||
$this->assertTrue($service->delete($image->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — 공개 자산 디스크 미설정이면 신규 행이 기본 디스크로 기록 (현행 보존)
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_base_disk_when_public_asset_disk_unset(): void
|
||||
{
|
||||
Config::set('core.storage.public_asset_disk', '');
|
||||
|
||||
$service = app(ProductImageService::class);
|
||||
|
||||
$image = $service->upload(
|
||||
UploadedFile::fake()->image('local-upload.jpg', 40, 40)
|
||||
);
|
||||
|
||||
$this->assertSame('modules', $image->disk);
|
||||
|
||||
$this->assertTrue($service->delete($image->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 disk 를 제공하던 플러그인이 비활성화되어 config 에서 사라진 상태를 만듭니다.
|
||||
*
|
||||
* @param string $disk 사라지게 할 디스크명
|
||||
*/
|
||||
private function vanishDisk(string $disk): void
|
||||
{
|
||||
Config::set("filesystems.disks.{$disk}", null);
|
||||
Storage::forgetDisk($disk);
|
||||
AssetStorage::flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* 고아 disk 행의 서빙은 500 이 아니라 스트리밍 폴백이어야 한다.
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function download_falls_back_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'products/row-disk-test/orphan.jpg');
|
||||
$this->vanishDisk('fake_cdn');
|
||||
|
||||
$this->assertNull($this->service->download($row->hash));
|
||||
}
|
||||
|
||||
/**
|
||||
* 고아 disk 행의 삭제도 예외 없이 완료되어야 한다.
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_succeeds_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'products/row-disk-test/orphan-del.jpg');
|
||||
$this->vanishDisk('fake_cdn');
|
||||
|
||||
$this->assertTrue($this->service->delete($row->id));
|
||||
$this->assertNull(ProductImage::find($row->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 삭제(이미지 일괄 삭제)도 고아 disk 행 때문에 막히면 안 된다.
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_by_product_id_succeeds_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$product = Product::factory()->create();
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'products/row-disk-test/orphan-bulk.jpg');
|
||||
$row->update(['product_id' => $product->id, 'temp_key' => null]);
|
||||
|
||||
$this->vanishDisk('fake_cdn');
|
||||
|
||||
$this->assertTrue($this->service->deleteByProductId($product->id));
|
||||
}
|
||||
}
|
||||
@@ -434,6 +434,11 @@ class ProductImageServiceTest extends ModuleTestCase
|
||||
->with($sourceHash)
|
||||
->andReturn($sourceImage);
|
||||
|
||||
// 복사는 원본 행 disk 기준으로 스토리지를 해석한다 (혼재 운용, 공개#100)
|
||||
$this->storage
|
||||
->shouldReceive('getDisk')
|
||||
->andReturn('local');
|
||||
|
||||
$this->storage
|
||||
->shouldReceive('get')
|
||||
->once()
|
||||
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Services;
|
||||
|
||||
use App\Extension\Storage\ModuleStorageDriver;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ReviewStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductReview;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductReviewImage;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductReviewImageService;
|
||||
use Modules\Sirsoft\Ecommerce\Support\AssetStorage;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* ProductReviewImageService 행 disk 기준 서빙/삭제 테스트
|
||||
*
|
||||
* 공개 자산 디스크 전환 이후에도 전환 이전 행(구 disk)의 서빙이 404 가 되지 않고,
|
||||
* 삭제가 그 행의 실제 저장 위치를 향하는지(혼재 운용 정합) 검증합니다.
|
||||
*
|
||||
* ProductReviewImageServiceTest 는 StorageInterface 를 Mock 으로 대체하므로
|
||||
* 실제 디스크 해석(withDisk) 회귀를 검출할 수 없어 별도 파일로 둡니다.
|
||||
*/
|
||||
class ProductReviewImageServiceRowDiskTest extends ModuleTestCase
|
||||
{
|
||||
private ProductReviewImageService $service;
|
||||
|
||||
private ProductReview $review;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
AssetStorage::flush();
|
||||
|
||||
Auth::login($this->createUser());
|
||||
|
||||
$product = Product::factory()->onSale()->create();
|
||||
$orderOption = OrderOption::factory()->create(['product_id' => $product->id]);
|
||||
|
||||
$this->review = ProductReview::factory()->create([
|
||||
'product_id' => $product->id,
|
||||
'order_option_id' => $orderOption->id,
|
||||
'user_id' => Auth::id(),
|
||||
'status' => ReviewStatus::VISIBLE->value,
|
||||
]);
|
||||
|
||||
$this->service = app(ProductReviewImageService::class);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
AssetStorage::flush();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정 disk 에 파일과 리뷰 이미지 행을 함께 생성합니다.
|
||||
*
|
||||
* @param string $disk 행 disk
|
||||
* @param string $path 이미지 경로 (images/ 하위 상대 경로)
|
||||
* @return ProductReviewImage 생성된 행
|
||||
*/
|
||||
private function makeRowOnDisk(string $disk, string $path): ProductReviewImage
|
||||
{
|
||||
(new ModuleStorageDriver('sirsoft-ecommerce', $disk))->put('images', $path, 'image-bytes');
|
||||
|
||||
return ProductReviewImage::create([
|
||||
'review_id' => $this->review->id,
|
||||
'original_filename' => 'review.jpg',
|
||||
'stored_filename' => basename($path),
|
||||
'disk' => $disk,
|
||||
'path' => $path,
|
||||
'mime_type' => 'image/jpeg',
|
||||
'file_size' => 11,
|
||||
'collection' => 'main',
|
||||
'is_thumbnail' => false,
|
||||
'sort_order' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects serve_and_delete_follow_row_disk, mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function download_serves_row_from_its_recorded_disk(): void
|
||||
{
|
||||
// 혼재 운용 — 주입 스토리지 disk 와 다른 disk 의 행도 서빙 가능해야 한다
|
||||
$cdnRow = $this->makeRowOnDisk('fake_cdn', 'reviews/row-disk-test/cdn.jpg');
|
||||
$localRow = $this->makeRowOnDisk('modules', 'reviews/row-disk-test/local.jpg');
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->download($cdnRow->hash));
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->download($localRow->hash));
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects serve_and_delete_follow_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_removes_file_on_row_disk(): void
|
||||
{
|
||||
$cdnRow = $this->makeRowOnDisk('fake_cdn', 'reviews/row-disk-test/del.jpg');
|
||||
$cdnDriver = new ModuleStorageDriver('sirsoft-ecommerce', 'fake_cdn');
|
||||
$this->assertTrue($cdnDriver->exists('images', $cdnRow->path));
|
||||
|
||||
$this->assertTrue($this->service->delete($cdnRow));
|
||||
|
||||
$this->assertFalse($cdnDriver->exists('images', $cdnRow->path));
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 disk 를 제공하던 플러그인이 비활성화되어 config 에서 사라진 상태를 만듭니다.
|
||||
*
|
||||
* @param string $disk 사라지게 할 디스크명
|
||||
*/
|
||||
private function vanishDisk(string $disk): void
|
||||
{
|
||||
Config::set("filesystems.disks.{$disk}", null);
|
||||
Storage::forgetDisk($disk);
|
||||
AssetStorage::flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* 고아 disk 행의 서빙은 500 이 아니라 스트리밍 폴백이어야 한다.
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function download_falls_back_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'reviews/row-disk-test/orphan.jpg');
|
||||
$this->vanishDisk('fake_cdn');
|
||||
|
||||
$this->assertNull($this->service->download($row->hash));
|
||||
}
|
||||
|
||||
/**
|
||||
* 고아 disk 행의 삭제도 예외 없이 완료되어야 한다(리뷰 삭제 자체가 막히면 안 됨).
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function delete_succeeds_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'reviews/row-disk-test/orphan-del.jpg');
|
||||
$this->vanishDisk('fake_cdn');
|
||||
|
||||
$this->assertTrue($this->service->delete($row));
|
||||
$this->assertNull(ProductReviewImage::find($row->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — SP 카테고리 배선을 실제로 경유해 공개 자산 디스크 설정값이
|
||||
* 신규 행의 disk 컬럼에 기록되는지 단언합니다(배선 회귀 검출).
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_configured_public_asset_disk_on_row(): void
|
||||
{
|
||||
Config::set('core.storage.public_asset_disk', 'fake_cdn');
|
||||
|
||||
$service = app(ProductReviewImageService::class);
|
||||
$image = $service->upload(
|
||||
UploadedFile::fake()->image('cdn-review.jpg', 40, 40),
|
||||
$this->review
|
||||
);
|
||||
|
||||
$this->assertSame('fake_cdn', $image->disk);
|
||||
$this->assertTrue(
|
||||
(new ModuleStorageDriver('sirsoft-ecommerce', 'fake_cdn'))->exists('images', $image->path)
|
||||
);
|
||||
|
||||
$this->assertTrue($service->delete($image));
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — 공개 자산 디스크 미설정이면 신규 행이 기본 디스크로 기록(현행 보존).
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_base_disk_when_public_asset_disk_unset(): void
|
||||
{
|
||||
Config::set('core.storage.public_asset_disk', '');
|
||||
|
||||
$service = app(ProductReviewImageService::class);
|
||||
$image = $service->upload(
|
||||
UploadedFile::fake()->image('local-review.jpg', 40, 40),
|
||||
$this->review
|
||||
);
|
||||
|
||||
$this->assertSame('modules', $image->disk);
|
||||
|
||||
$this->assertTrue($service->delete($image));
|
||||
}
|
||||
}
|
||||
+15
@@ -235,6 +235,11 @@ class ProductReviewImageServiceTest extends ModuleTestCase
|
||||
'path' => 'reviews/1/test.jpg',
|
||||
]);
|
||||
|
||||
// 삭제는 행 disk 기준으로 스토리지를 해석한다 (혼재 운용, 공개#100)
|
||||
$this->storage
|
||||
->shouldReceive('getDisk')
|
||||
->andReturn('local');
|
||||
|
||||
$this->storage
|
||||
->shouldReceive('exists')
|
||||
->with('images', 'reviews/1/test.jpg')
|
||||
@@ -261,6 +266,11 @@ class ProductReviewImageServiceTest extends ModuleTestCase
|
||||
'path' => 'reviews/1/missing.jpg',
|
||||
]);
|
||||
|
||||
// 삭제는 행 disk 기준으로 스토리지를 해석한다 (혼재 운용, 공개#100)
|
||||
$this->storage
|
||||
->shouldReceive('getDisk')
|
||||
->andReturn('local');
|
||||
|
||||
$this->storage
|
||||
->shouldReceive('exists')
|
||||
->with('images', 'reviews/1/missing.jpg')
|
||||
@@ -322,6 +332,11 @@ class ProductReviewImageServiceTest extends ModuleTestCase
|
||||
'original_filename' => 'test.jpg',
|
||||
]);
|
||||
|
||||
// 서빙은 행 disk 기준으로 스토리지를 해석한다 (혼재 운용, 공개#100)
|
||||
$this->storage
|
||||
->shouldReceive('getDisk')
|
||||
->andReturn('local');
|
||||
|
||||
$this->storage
|
||||
->shouldReceive('response')
|
||||
->once()
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductImage;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductService;
|
||||
use Modules\Sirsoft\Ecommerce\Support\AssetStorage;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* 상품 상세 폼 직렬화 이미지 URL 호출측 회귀 테스트 (#100 URL 조립 단일화)
|
||||
*
|
||||
* accessor(download_url) 자체가 아니라 **호출측**(ProductService getDetailForForm)이
|
||||
* accessor 에 위임해 직렬화하는지 고정합니다 — 손조립 문자열로 회귀하면 행 disk
|
||||
* 기준 직접 URL(혼재 운용)이 화면에서 사라집니다.
|
||||
*/
|
||||
class ProductServiceDetailImageUrlTest extends ModuleTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
AssetStorage::flush();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
AssetStorage::flush();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function detail_form_serializes_download_url_per_row_disk(): void
|
||||
{
|
||||
$product = Product::create([
|
||||
'product_code' => 'URLDELEG-'.Str::random(6),
|
||||
'name' => ['ko' => 'URL 위임 테스트 상품'],
|
||||
'selling_price' => 1000,
|
||||
'stock_quantity' => 1,
|
||||
'sales_status' => 'on_sale',
|
||||
'display_status' => 'visible',
|
||||
]);
|
||||
|
||||
$localImage = ProductImage::create([
|
||||
'product_id' => $product->id,
|
||||
'original_filename' => 'old.jpg',
|
||||
'stored_filename' => 'old.jpg',
|
||||
'disk' => 'modules',
|
||||
'path' => 'products/'.$product->id.'/old.jpg',
|
||||
'mime_type' => 'image/jpeg',
|
||||
'file_size' => 10,
|
||||
'collection' => 'main',
|
||||
'is_thumbnail' => true,
|
||||
'sort_order' => 0,
|
||||
]);
|
||||
$cdnImage = ProductImage::create([
|
||||
'product_id' => $product->id,
|
||||
'original_filename' => 'new.jpg',
|
||||
'stored_filename' => 'new.jpg',
|
||||
'disk' => 'fake_cdn',
|
||||
'path' => 'products/'.$product->id.'/new.jpg',
|
||||
'mime_type' => 'image/jpeg',
|
||||
'file_size' => 10,
|
||||
'collection' => 'main',
|
||||
'is_thumbnail' => false,
|
||||
'sort_order' => 1,
|
||||
]);
|
||||
|
||||
$detail = app(ProductService::class)->getDetailForForm($product->id);
|
||||
|
||||
$this->assertNotNull($detail);
|
||||
$byHash = collect($detail['images'])->keyBy('hash');
|
||||
|
||||
// 혼재 운용 — 구 로컬 행은 API 폴백, 신규 원격 행은 직접 URL 로 직렬화
|
||||
$this->assertSame(
|
||||
'/api/modules/sirsoft-ecommerce/product-image/'.$localImage->hash,
|
||||
$byHash[$localImage->hash]['download_url'],
|
||||
);
|
||||
$this->assertSame(
|
||||
'https://cdn.test/assets/sirsoft-ecommerce/images/products/'.$product->id.'/new.jpg',
|
||||
$byHash[$cdnImage->hash]['download_url'],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit;
|
||||
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Services\ModuleSettingsService;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Modules\Sirsoft\Ecommerce\Module;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* getStorageDiskFor 설정 로드 순환 참조 회귀 테스트 (실제 설정 로드 경로)
|
||||
*
|
||||
* 실제 모듈 인스턴스의 getStorageDiskFor 가 module_setting() 을 경유할 때,
|
||||
* 설정 로드 자신이 스토리지('settings' 카테고리)를 다시 요구하는 상황을
|
||||
* 컨테이너 스파이로 재현합니다. PUBLIC_ASSET_CATEGORIES 게이트가 제거되면
|
||||
* 'settings' 해석이 설정 서비스를 재호출해 호출 횟수 단언이 깨집니다.
|
||||
*/
|
||||
class StorageDiskRecursionTest extends ModuleTestCase
|
||||
{
|
||||
private Module $module;
|
||||
|
||||
/**
|
||||
* 설정 로드가 스토리지를 경유하는 경로를 재현하는 스파이
|
||||
*/
|
||||
private object $settingsSpy;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
Config::set('core.storage.public_asset_disk', '');
|
||||
|
||||
$this->module = app(ModuleManager::class)->getModule('sirsoft-ecommerce')
|
||||
?? new Module(base_path('modules/sirsoft-ecommerce'));
|
||||
|
||||
// 실제 설정 로드처럼 get() 내부에서 모듈 스토리지('settings')를 재요구하는 스파이.
|
||||
// 재진입(= getStorageDiskFor('settings') 가 다시 설정을 조회하는 회귀) 발생 시
|
||||
// reentered 플래그 + 호출 횟수 증가로 검출됩니다.
|
||||
$this->settingsSpy = new class extends ModuleSettingsService
|
||||
{
|
||||
public ?Module $module = null;
|
||||
|
||||
public int $calls = 0;
|
||||
|
||||
public bool $reentered = false;
|
||||
|
||||
public ?string $nestedDisk = null;
|
||||
|
||||
private bool $inGet = false;
|
||||
|
||||
public function __construct() {}
|
||||
|
||||
public function get(string $identifier, ?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
$this->calls++;
|
||||
|
||||
if ($this->inGet) {
|
||||
// 설정 로드 중 설정 재조회 = 순환 고리. 무한 재귀 대신 폭로.
|
||||
$this->reentered = true;
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
$this->inGet = true;
|
||||
|
||||
try {
|
||||
// 설정 로드가 스토리지를 경유하는 실제 경로 재현 —
|
||||
// 이 호출이 getStorageDiskFor('settings') 를 타고 되돌아온다.
|
||||
$this->nestedDisk = $this->module->getStorageFor('settings')->getDisk();
|
||||
|
||||
if ($key === 'basic_info.public_asset_disk') {
|
||||
return 'fake_cdn';
|
||||
}
|
||||
|
||||
return $default;
|
||||
} finally {
|
||||
$this->inGet = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
$this->settingsSpy->module = $this->module;
|
||||
$this->app->instance(ModuleSettingsService::class, $this->settingsSpy);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->app->forgetInstance(ModuleSettingsService::class);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects settings_load_recursion_free
|
||||
*/
|
||||
#[Test]
|
||||
public function settings_category_never_consults_module_settings(): void
|
||||
{
|
||||
// 'settings' 카테고리 해석은 설정 서비스를 한 번도 거치지 않아야 한다 —
|
||||
// 거치는 순간 설정 로드 ↔ 디스크 해석의 순환 고리가 열린다.
|
||||
$this->assertSame($this->module->getStorageDisk(), $this->module->getStorageDiskFor('settings'));
|
||||
$this->assertSame(0, $this->settingsSpy->calls);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects settings_load_recursion_free
|
||||
*/
|
||||
#[Test]
|
||||
public function images_resolution_survives_settings_load_that_uses_storage(): void
|
||||
{
|
||||
// 공개 자산 카테고리 해석 → 설정 조회 → (설정 로드가 'settings' 스토리지 재요구)
|
||||
// 전체 사슬이 유한 종료하고, 설정 조회는 정확히 1회만 발생해야 한다.
|
||||
$this->assertSame('fake_cdn', $this->module->getStorageDiskFor('images'));
|
||||
|
||||
$this->assertSame(1, $this->settingsSpy->calls);
|
||||
$this->assertFalse($this->settingsSpy->reentered, '설정 로드 중 설정 재조회(순환) 발생');
|
||||
// 설정 로드가 요구한 'settings' 스토리지는 공개 자산 디스크가 아닌 기본 디스크
|
||||
$this->assertSame($this->module->getStorageDisk(), $this->settingsSpy->nestedDisk);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user