Files
Gnuboard7/tests/Unit/Resources/NotificationDefinitionResourceTest.php
HeuJung b5c0ec1178 fix(core,ecommerce,board,page,admin_basic,basic): 목록 응답의 하위 컬렉션 전량 직렬화 해소
관리자 상품목록을 한 페이지 여는 것만으로 그 페이지 모든 상품의 옵션이 응답에 실렸다.
같은 패턴을 저장소 전역에서 찾아 14개 목록 엔드포인트를 함께 정리했다.

근본 원인은 둘이다. Resource 가 whenLoaded 로 방어하는데 Repository 가 목록 쿼리에서
관계를 무조건 로드해 가드가 항상 참이 되는 가짜 가드, 그리고 toListArray 경량 표현을
정의해 두고도 컬렉션이 toArray 를 부르는 목록/상세 미분리다. 둘 다 응답만 보면
정상이라 오류도 경고도 없이 페이로드만 불어난다.

목록은 화면이 실제로 그리는 것만 싣는다. 개수·합계는 PHP 컬렉션 연산이 아니라 DB
집계로, 대표 1건이 필요한 곳은 관계 자체를 oldestOfMany 로 좁힌다. eager load 의
limit(1) 은 부모별이 아니라 배치 쿼리 전체에 걸려 첫 행만 값을 갖게 되므로 쓸 수 없다.

뺀 값에는 대체 경로를 먼저 만들었다. 상품 옵션은 행을 펼칠 때 배치로 불러오고(상품 수와
무관하게 쿼리 상수), 종전 동작이 필요한 호출자를 위해 ?with_options=1 등 opt-in 을 남겼다.
배송정책 국가설정과 리뷰 첨부 이미지는 소비처를 실측한 결과 화면이 실제로 그리고 있어
제거하지 않았다 — 그 소비 사실을 회귀 테스트로 고정했다.

재발 방지로 정적 검사 룰 4종과 규정 문서 항목을 함께 넣었다.
2026-08-05 21:20:05 +09:00

123 lines
4.6 KiB
PHP

<?php
namespace Tests\Unit\Resources;
use App\Http\Resources\NotificationDefinitionResource;
use App\Models\NotificationDefinition;
use App\Models\NotificationTemplate;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Tests\TestCase;
/**
* NotificationDefinitionResource 단위 테스트
*/
class NotificationDefinitionResourceTest extends TestCase
{
use RefreshDatabase;
/**
* templates 관계 미로드 시 키 자체가 빠진다 (json 직렬화 에러 없음)
*
* 종전에는 `relationLoaded ? ... : null` 로 null 을 내보냈다. 그 형태는 Repository 가 목록에서
* 관계를 무조건 로드하면 가드가 항상 참이 되어 무력화되는 "가짜 가드" 라 `whenLoaded` 로
* 바꿨고, 미로드 시에는 MissingValue 가 되어 응답에서 키가 빠진다. 소비 화면은
* `def.templates ?? []` / `def.templates?.[0]` 로 읽어 null 과 부재를 동일하게 다룬다.
*/
public function test_templates_key_is_omitted_when_relation_not_loaded(): void
{
$definition = NotificationDefinition::create([
'type' => 'welcome',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '환영'],
'channels' => ['mail'],
'hooks' => [],
]);
$request = Request::create('/test');
$resource = new NotificationDefinitionResource($definition);
$array = $resource->toArray($request);
// 컬렉션이 이 배열을 그대로 응답에 싣기 때문에 MissingValue 가 남아 있으면 `{}` 로
// 직렬화된다 — Resource 가 직접 걸러내야 한다.
$this->assertArrayNotHasKey('templates', $array);
// json_encode 시 에러 없음 검증
$json = json_encode($array);
$this->assertNotFalse($json);
$this->assertEquals(JSON_ERROR_NONE, json_last_error());
}
/**
* templates 관계 로드 시 배열 반환
*/
public function test_templates_returns_array_when_relation_loaded(): void
{
$definition = NotificationDefinition::create([
'type' => 'welcome',
'hook_prefix' => 'core.auth',
'extension_type' => 'core',
'extension_identifier' => 'core',
'name' => ['ko' => '환영'],
'channels' => ['mail'],
'hooks' => [],
]);
NotificationTemplate::create([
'definition_id' => $definition->id,
'channel' => 'mail',
'subject' => ['ko' => '제목'],
'body' => ['ko' => '본문'],
]);
$definition->load('templates');
$request = Request::create('/test');
$resource = new NotificationDefinitionResource($definition);
$array = $resource->toArray($request);
$this->assertNotNull($array['templates']);
// Resource::collection()은 AnonymousResourceCollection을 반환
// json_encode 시 배열로 직렬화됨
$json = json_encode($array);
$decoded = json_decode($json, true);
$this->assertIsArray($decoded['templates']);
$this->assertCount(1, $decoded['templates']);
// json_encode 시 에러 없음 검증
$json = json_encode($array);
$this->assertNotFalse($json);
}
/**
* 기본 필드가 올바르게 반환됨
*/
public function test_basic_fields_returned(): void
{
$definition = NotificationDefinition::create([
'type' => 'order_confirmed',
'hook_prefix' => 'sirsoft-ecommerce',
'extension_type' => 'module',
'extension_identifier' => 'sirsoft-ecommerce',
'name' => ['ko' => '주문 확인', 'en' => 'Order Confirmed'],
'channels' => ['mail', 'database'],
'hooks' => ['sirsoft-ecommerce.order.after_confirm'],
'variables' => [['key' => 'name', 'description' => '이름']],
'is_active' => true,
]);
$request = Request::create('/test');
$array = (new NotificationDefinitionResource($definition))->toArray($request);
$this->assertEquals('order_confirmed', $array['type']);
$this->assertEquals('sirsoft-ecommerce', $array['hook_prefix']);
$this->assertEquals('module', $array['extension_type']);
$this->assertEquals(['mail', 'database'], $array['channels']);
$this->assertTrue($array['is_active']);
$this->assertArrayHasKey('name', $array);
$this->assertArrayHasKey('variables', $array);
}
}