Files
Gnuboard7/app/Http/Resources/LayoutExtensionResource.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

172 lines
7.0 KiB
PHP

<?php
namespace App\Http\Resources;
use App\Extension\Traits\ComputesLayoutContentHash;
use Illuminate\Http\Request;
/**
* 레이아웃 확장 리소스
*
* 관리자 레이아웃 편집 화면에서 사용하는 레이아웃 확장 직렬화 리소스입니다.
*/
class LayoutExtensionResource extends BaseApiResource
{
use ComputesLayoutContentHash;
/**
* 리소스를 배열로 변환
*
* @param Request $request 요청 객체
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$content = $this->getValue('content', []);
$contentJson = is_array($content) ? json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) : '{}';
$extensionType = $this->getValue('extension_type');
$sourceType = $this->getValue('source_type');
return [
'id' => $this->getValue('id'),
'template_id' => $this->getValue('template_id'),
'extension_type' => $extensionType?->value ?? $extensionType,
'target_name' => $this->getValue('target_name'),
'source_type' => $sourceType?->value ?? $sourceType,
'source_identifier' => $this->getValue('source_identifier'),
'source_label' => $this->getValue('source_label', $this->getValue('source_identifier')),
'override_target' => $this->getValue('override_target'),
// 템플릿 오버라이드 여부 — index 에서 부착되며, 미부착 시 source_type 으로 폴백
'is_override' => (bool) $this->getValue(
'is_override',
($sourceType?->value ?? $sourceType) === 'template'
),
'priority' => $this->getValue('priority'),
'is_active' => (bool) $this->getValue('is_active'),
// 호스트 레이아웃 목록 — 이 확장이 주입되는 레이아웃명들.
// overlay = [target_layout], extension_point = 그 확장점을 포함하는 레이아웃 전체.
// index 에서 부착되며, 라우트 트리가 layoutName 매칭으로 화면별 연결 목록을 구성한다.
'host_layouts' => $this->getValue('host_layouts', []),
// 레이아웃 편집 페이지용 필드
'content' => $contentJson,
'size' => strlen($contentJson),
'size_formatted' => $this->formatFileSize(strlen($contentJson)),
'is_modified' => $this->resolveIsModified($content),
// 낙관적 잠금 — 다음 저장 요청에 expected_lock_version 으로 전달
'lock_version' => (int) $this->getValue('lock_version', 0),
// 현재(최신) 저장 버전 번호 — index(목록 부착)/update(저장
// 경로 transient)에서만 채워짐. 이력 없는 확장/그 외 응답은 null (배지 미표시).
'current_version' => $this->getValue('current_version') !== null
? (int) $this->getValue('current_version')
: null,
...$this->formatTimestamps(),
...$this->resourceMeta($request),
];
}
/**
* 목록용 경량 배열로 변환합니다.
*
* 확장 목록은 라우트 트리에 "어느 화면에 어떤 확장이 붙어 있는가" 를 그리는 데 쓰입니다.
* 편집 본문(`content`)은 그 화면이 쓰지 않고 단건 조회가 공급하는데, 목록에 실리면 템플릿에
* 등록된 **모든 확장의 JSON 전문**이 한 응답에 담깁니다.
*
* 수정 여부(`is_modified`)와 크기(`size`/`size_formatted`)는 본문에서 계산하므로 값은 그대로
* 유지합니다 — 본문을 직렬화하지 않을 뿐, 계산은 서버에서 수행해 결과만 내려줍니다.
* (목록 화면이 확장마다 크기를 표시하므로 빼면 전 행이 `0 B` 로 보인다.)
*
* @param Request $request 요청 객체
* @return array<string, mixed> 목록용 직렬화 결과
*/
public function toListArray(Request $request): array
{
$content = $this->getValue('content', []);
$contentJson = is_array($content) ? json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) : '{}';
$extensionType = $this->getValue('extension_type');
$sourceType = $this->getValue('source_type');
// 이 배열은 컨트롤러가 그대로 응답에 싣는다 — Laravel 의 MissingValue 제거 단계를 거치지
// 않으므로 조건부 필드를 직접 걸러낸다.
return $this->withoutMissing([
'id' => $this->getValue('id'),
'extension_type' => $extensionType?->value ?? $extensionType,
'target_name' => $this->getValue('target_name'),
'source_type' => $sourceType?->value ?? $sourceType,
'source_identifier' => $this->getValue('source_identifier'),
'source_label' => $this->getValue('source_label', $this->getValue('source_identifier')),
'is_override' => (bool) $this->getValue(
'is_override',
($sourceType?->value ?? $sourceType) === 'template'
),
'priority' => $this->getValue('priority'),
'is_active' => (bool) $this->getValue('is_active'),
'is_modified' => $this->resolveIsModified($content),
'size' => strlen($contentJson),
'size_formatted' => $this->formatFileSize(strlen($contentJson)),
'host_layouts' => $this->getValue('host_layouts', []),
'current_version' => $this->getValue('current_version') !== null
? (int) $this->getValue('current_version')
: null,
...$this->formatTimestamps(),
...$this->resourceMeta($request),
]);
}
/**
* 리소스별 권한 매핑을 반환합니다.
*
* @return array<string, string>
*/
protected function abilityMap(): array
{
return [
'can_update' => 'core.templates.layouts.edit',
];
}
/**
* 관리자 수정 여부를 판단합니다.
*
* 현재 content 해시가 original_content_hash 와 다르면 수정된 것으로 간주합니다.
*
* @param array $content 현재 확장 content
* @return bool 수정 여부
*/
private function resolveIsModified(array $content): bool
{
$originalHash = $this->getValue('original_content_hash');
if (! $originalHash || empty($content)) {
return false;
}
return $this->computeContentHash($content) !== $originalHash;
}
/**
* 파일 크기를 사람이 읽기 쉬운 형태로 변환
*
* @param int $bytes 바이트 크기
* @return string 포맷된 크기 (예: "12.5 KB")
*/
private function formatFileSize(int $bytes): string
{
if ($bytes < 1024) {
return $bytes.' B';
}
if ($bytes < 1048576) {
return round($bytes / 1024, 1).' KB';
}
return round($bytes / 1048576, 1).' MB';
}
}