feat(seo): 사이트맵 스트리밍 생성 + SEO 캐시 설정 정합화

대용량 사이트에서 사이트맵 생성이 메모리 부족으로 반복 실패하던 문제(공개 )의
1단계로, 전체 URL을 메모리에 적재하던 구조를 스트리밍 분할 생성으로 교체한다.

사이트맵 스트리밍 코어:
- SitemapWriter — 자식 파일 1개 분량만 버퍼링하고 임계 도달 시 flush.
 StorageInterface가 append를 제공하지 않아(put이 전체 덮어쓰기) 택한 구조이며,
 최대 메모리가 "자식 파일 1개 크기"로 유계가 된다. URL 수(50,000)와
 바이트(45MB) 두 임계로 분할해 sitemaps.org 프로토콜을 지킨다.
- 커밋은 _tmp 전량 기록 → live 재배치 → manifest 마지막 기록 순. manifest 존재가
 커밋 완료 신호다. 기존 manifest를 먼저 지우지 않아 스왑 중 봇에게 503이 나가지 않는다.
- SitemapFileStore — 읽기측 + 파일 경로 SSoT. SitemapXmlRenderer — escape 단일 출처.

데이터 접근 계층 정리:
- contributor 3종이 쿼리를 직접 조립하던 것을 Repository 위임으로 전환.
 MySQL 버퍼드 쿼리에서 cursor는 결과셋 전체를 적재하므로 lazyById를 쓴다.
- SeoCacheStatsService → SeoCacheStatRepository 신설 (집계 4쿼리 → 1쿼리).
- audit 룰 service-direct-data-access의 사각 2건 수정 — 확장 디렉토리 정규식이
 상대경로를 매칭하지 못해 *Contributor처럼 접미사 없는 클래스가 전부 미검출이었다.

SEO 캐시 설정 정합화:
- SEO 설정의 캐시 3키가 cache 카테고리 형제 키에 항상 져서 운영자 입력이 조용히
 무시되고 있었다(설정을 cache 카테고리로 이관하며 SEO 탭 옛 칸을 미제거).
 고급 탭을 기준값으로 두되 SEO 탭에 지정이 있으면 오버라이드하도록 SeoCacheSettings
 단일 출처로 정리. "지정 여부"는 null로 판정하므로 기본값을 비웠다.
- 기존 설치는 Upgrade_7_1_0이 이행 — 옛 기본값과 같으면 미설정으로 비우고, 다르면
 운영자 의도로 보아 보존한다.

코어 버전 bump와 루트 CHANGELOG는 계획서 결정(D20)에 따라 마감 단계에서 일괄 수행한다.
This commit is contained in:
HeuJung committed 2026-07-17 19:59:40 +09:00
1 parent fcaacad8d1
commit 21f666e4b5
75 files changed
+4767 -951

No files matched your search

@@ -4,6 +4,16 @@
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [1.0.3] - 2026-07-16
### Added
- 사이트맵에 담을 게시판·게시글 수의 안전 상한을 지원합니다. 상한을 설정하면 게시판 목록·게시판·게시글 어느 항목이든 그 수를 넘지 않으며, 상한에 걸려 일부가 빠진 경우 기록으로 남습니다.
### Changed
- 사이트맵을 만들 때 게시판과 게시글을 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 게시글이 많은 사이트에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
## [1.0.2] - 2026-07-14
### Fixed
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "modules/sirsoft-board",
"description": "Board module for Gnuboard7",
"type": "library",
"version": "1.0.2",
"version": "1.0.3",
"license": "MIT",
"autoload": {
"psr-4": {
+1 -1
View File
@@ -5,7 +5,7 @@
"ko": "게시판",
"en": "Board"
},
"version": "1.0.2",
"version": "1.0.3",
"license": "MIT",
"description": {
"ko": "게시판 관리를 위한 모듈",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@g7/sirsoft-board",
"version": "1.0.2",
"version": "1.0.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@g7/sirsoft-board",
"version": "1.0.2",
"version": "1.0.3",
"devDependencies": {
"jsdom": "^27.4.0",
"typescript": "^5.3.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@g7/sirsoft-board",
"version": "1.0.2",
"version": "1.0.3",
"description": "그누보드7 게시판 모듈 프론트엔드 에셋",
"private": true,
"type": "module",
@@ -105,8 +105,9 @@ class BoardServiceProvider extends BaseModuleServiceProvider
// Sitemap 기여자 등록
$this->app->booted(function () {
if ($this->app->bound(SitemapGenerator::class)) {
// Repository 주입을 위해 컨테이너로 해석합니다.
$this->app->make(SitemapGenerator::class)->registerContributor(
new BoardSitemapContributor
$this->app->make(BoardSitemapContributor::class)
);
}
});
@@ -2,10 +2,12 @@
namespace Modules\Sirsoft\Board\Repositories;
use App\Enums\UserStatus;
use App\Helpers\PermissionHelper;
use App\Helpers\TimezoneHelper;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
@@ -32,7 +34,7 @@ class BoardRepository implements BoardRepositoryInterface
*/
public function create(array $data): Board
{
$board = new Board();
$board = new Board;
$board->fill($data);
// created_by/updated_by는 guarded이므로 직접 할당
@@ -63,7 +65,7 @@ class BoardRepository implements BoardRepositoryInterface
* @param int $id 게시판 ID
* @return Board 게시판 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(int $id): Board
{
@@ -88,7 +90,7 @@ class BoardRepository implements BoardRepositoryInterface
* @param array $data 수정할 데이터
* @return Board 수정된 게시판 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(int $id, array $data): Board
{
@@ -113,7 +115,7 @@ class BoardRepository implements BoardRepositoryInterface
* @param int $id 게시판 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(int $id): bool
{
@@ -179,7 +181,7 @@ class BoardRepository implements BoardRepositoryInterface
/**
* 쿼리 빌더를 반환합니다. (체이닝 가능)
*
* @return \Illuminate\Database\Eloquent\Builder<Board>
* @return Builder<Board>
*/
public function query()
{
@@ -243,7 +245,7 @@ class BoardRepository implements BoardRepositoryInterface
'board_name' => $post->board?->getLocalizedName(),
'title' => $post->title,
'author_name' => $post->author_name,
'created_at' => $this->formatCreatedAt($post->created_at),
'created_at' => $this->formatCreatedAt($post->created_at),
'created_at_formatted' => $this->formatCreatedAtFormat($post->created_at, g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')),
'view_count' => $post->view_count,
'comment_count' => $post->comments_count ?? 0,
@@ -295,7 +297,7 @@ class BoardRepository implements BoardRepositoryInterface
'id' => $post->id,
'title' => $post->title,
'author_name' => $post->author_name,
'created_at' => $this->formatCreatedAt($post->created_at),
'created_at' => $this->formatCreatedAt($post->created_at),
'created_at_formatted' => $this->formatCreatedAtFormat($post->created_at, g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')),
'view_count' => $post->view_count,
'comment_count' => $post->comments_count ?? 0,
@@ -481,8 +483,8 @@ class BoardRepository implements BoardRepositoryInterface
}
// 사용자 상태 처리 (탈퇴한 사용자는 익명화)
$userStatus = $post->user_id ? \App\Enums\UserStatus::tryFrom($post->user_status) : null;
$isWithdrawn = $userStatus === \App\Enums\UserStatus::Withdrawn;
$userStatus = $post->user_id ? UserStatus::tryFrom($post->user_status) : null;
$isWithdrawn = $userStatus === UserStatus::Withdrawn;
$authorName = $post->user_id
? ($isWithdrawn ? __('user.withdrawn_user') : $post->user_name)
: $post->guest_author_name;
@@ -504,7 +506,7 @@ class BoardRepository implements BoardRepositoryInterface
],
'view_count' => $viewCount,
'comment_count' => $commentCount,
'created_at' => $this->formatCreatedAt(Carbon::parse($post->created_at)),
'created_at' => $this->formatCreatedAt(Carbon::parse($post->created_at)),
'created_at_formatted' => $this->formatCreatedAtFormat($post->created_at, g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')),
];
})->toArray();
@@ -513,20 +515,34 @@ class BoardRepository implements BoardRepositoryInterface
/**
* 활성화된 게시판 목록을 조회합니다.
*
* @param string|null $slug 특정 게시판 슬러그 (null이면 전체)
* @param string|null $slug 특정 게시판 슬러그 (null이면 전체)
* @return Collection 활성 게시판 컬렉션
*/
public function getActiveBoards(?string $slug = null): Collection
{
$query = Board::where('is_active', true);
if (!empty($slug)) {
if (! empty($slug)) {
$query->where('slug', $slug);
}
return $query->get();
}
/**
* Sitemap 생성용으로 활성 게시판을 순회자로 조회합니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Board> 활성 게시판 순회자 (id, slug, updated_at 만 조회)
*/
public function streamActiveForSitemap(int $chunkSize = 500): iterable
{
return Board::where('is_active', true)
->select(['id', 'slug', 'updated_at'])
->orderBy('id')
->lazyById($chunkSize);
}
/**
* 필터용 전체 활성 게시판 목록을 반환합니다.
*
@@ -542,9 +558,9 @@ class BoardRepository implements BoardRepositoryInterface
/**
* 게시판을 일괄 업데이트합니다.
*
* @param array<string, mixed> $data 업데이트할 데이터
* @param bool $applyAll 전체 적용 여부
* @param array<int> $boardIds 특정 게시판 ID 목록 (applyAll=false일 때 사용)
* @param array<string, mixed> $data 업데이트할 데이터
* @param bool $applyAll 전체 적용 여부
* @param array<int> $boardIds 특정 게시판 ID 목록 (applyAll=false일 때 사용)
* @return int 업데이트된 게시판 수
*/
public function bulkUpdate(array $data, bool $applyAll = true, array $boardIds = []): int
@@ -590,9 +606,9 @@ class BoardRepository implements BoardRepositoryInterface
*
* @param string $orderBy 정렬 기준 컬럼
* @param string $orderDirection 정렬 방향 (asc/desc)
* @return \Illuminate\Database\Eloquent\Collection 활성 게시판 컬렉션
* @return Collection 활성 게시판 컬렉션
*/
public function getActiveBoardsOrdered(string $orderBy = 'created_at', string $orderDirection = 'desc'): \Illuminate\Database\Eloquent\Collection
public function getActiveBoardsOrdered(string $orderBy = 'created_at', string $orderDirection = 'desc'): Collection
{
return Board::where('is_active', true)
->orderBy($orderBy, $orderDirection)
@@ -618,9 +634,9 @@ class BoardRepository implements BoardRepositoryInterface
*
* id, name, slug 컬럼만 조회하여 메뉴 렌더링에 필요한 최소 데이터만 반환합니다.
*
* @return \Illuminate\Database\Eloquent\Collection 활성 게시판 컬렉션 (id, name, slug만 포함)
* @return Collection 활성 게시판 컬렉션 (id, name, slug만 포함)
*/
public function getActiveBoardsForMenu(): \Illuminate\Database\Eloquent\Collection
public function getActiveBoardsForMenu(): Collection
{
return Board::where('is_active', true)
->select(['id', 'name', 'slug'])
@@ -2,7 +2,9 @@
namespace Modules\Sirsoft\Board\Repositories\Contracts;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Sirsoft\Board\Models\Board;
@@ -14,7 +16,7 @@ interface BoardRepositoryInterface
/**
* 게시판을 생성합니다.
*
* @param array $data 게시판 생성 데이터
* @param array $data 게시판 생성 데이터
* @return Board 생성된 게시판 모델
*/
public function create(array $data): Board;
@@ -22,7 +24,7 @@ interface BoardRepositoryInterface
/**
* ID로 게시판을 조회합니다.
*
* @param int $id 게시판 ID
* @param int $id 게시판 ID
* @return Board|null 게시판 모델 또는 null
*/
public function find(int $id): ?Board;
@@ -30,17 +32,17 @@ interface BoardRepositoryInterface
/**
* ID로 게시판을 조회하며, 없으면 예외를 발생시킵니다.
*
* @param int $id 게시판 ID
* @param int $id 게시판 ID
* @return Board 게시판 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(int $id): Board;
/**
* 슬러그로 게시판을 조회합니다.
*
* @param string $slug 게시판 슬러그
* @param string $slug 게시판 슬러그
* @return Board|null 게시판 모델 또는 null
*/
public function findBySlug(string $slug): ?Board;
@@ -48,21 +50,21 @@ interface BoardRepositoryInterface
/**
* 게시판을 수정합니다.
*
* @param int $id 게시판 ID
* @param array $data 수정할 데이터
* @param int $id 게시판 ID
* @param array $data 수정할 데이터
* @return Board 수정된 게시판 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(int $id, array $data): Board;
/**
* 게시판을 삭제합니다.
*
* @param int $id 게시판 ID
* @param int $id 게시판 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(int $id): bool;
@@ -76,7 +78,7 @@ interface BoardRepositoryInterface
/**
* 게시판 목록을 페이지네이션하여 조회합니다.
*
* @param int $perPage 페이지당 개수
* @param int $perPage 페이지당 개수
* @return LengthAwarePaginator 페이지네이션된 게시판 목록
*/
public function paginate(int $perPage = 15): LengthAwarePaginator;
@@ -84,7 +86,7 @@ interface BoardRepositoryInterface
/**
* 키워드로 게시판을 검색합니다.
*
* @param string $keyword 검색 키워드
* @param string $keyword 검색 키워드
* @return Collection 검색 결과 컬렉션
*/
public function search(string $keyword): Collection;
@@ -92,7 +94,7 @@ interface BoardRepositoryInterface
/**
* 타입으로 게시판을 필터링합니다.
*
* @param string $type 게시판 타입
* @param string $type 게시판 타입
* @return Collection 필터링된 게시판 컬렉션
*/
public function filterByType(string $type): Collection;
@@ -100,7 +102,7 @@ interface BoardRepositoryInterface
/**
* 쿼리 빌더를 반환합니다.
*
* @return \Illuminate\Database\Eloquent\Builder<Board>
* @return Builder<Board>
*/
public function query();
@@ -164,11 +166,22 @@ interface BoardRepositoryInterface
/**
* 활성화된 게시판 목록을 조회합니다.
*
* @param string|null $slug 특정 게시판 슬러그 (null이면 전체)
* @param string|null $slug 특정 게시판 슬러그 (null이면 전체)
* @return Collection 활성 게시판 컬렉션
*/
public function getActiveBoards(?string $slug = null): Collection;
/**
* Sitemap 생성용으로 활성 게시판을 순회자로 조회합니다.
*
* 전체 결과를 메모리에 적재하지 않도록 lazyById 로 청크 단위 조회하며,
* sitemap 에 필요한 컬럼만 select 합니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Board> 활성 게시판 순회자 (id, slug, updated_at 만 조회)
*/
public function streamActiveForSitemap(int $chunkSize = 500): iterable;
/**
* 필터용 전체 활성 게시판 목록을 반환합니다.
*
@@ -179,9 +192,9 @@ interface BoardRepositoryInterface
/**
* 게시판을 일괄 업데이트합니다.
*
* @param array<string, mixed> $data 업데이트할 데이터
* @param bool $applyAll 전체 적용 여부
* @param array<int> $boardIds 특정 게시판 ID 목록 (applyAll=false일 때 사용)
* @param array<string, mixed> $data 업데이트할 데이터
* @param bool $applyAll 전체 적용 여부
* @param array<int> $boardIds 특정 게시판 ID 목록 (applyAll=false일 때 사용)
* @return int 업데이트된 게시판 수
*/
public function bulkUpdate(array $data, bool $applyAll = true, array $boardIds = []): int;
@@ -189,7 +202,7 @@ interface BoardRepositoryInterface
/**
* 게시판 ID 목록별 게시글 개수를 조회합니다.
*
* @param array<int> $boardIds 게시판 ID 목록
* @param array<int> $boardIds 게시판 ID 목록
* @return array<int, int> board_id => count 매핑
*/
public function getPostsCountByBoardIds(array $boardIds): array;
@@ -197,8 +210,8 @@ interface BoardRepositoryInterface
/**
* 활성화된 게시판 목록을 정렬 옵션과 함께 조회합니다.
*
* @param string $orderBy 정렬 기준 컬럼
* @param string $orderDirection 정렬 방향 (asc/desc)
* @param string $orderBy 정렬 기준 컬럼
* @param string $orderDirection 정렬 방향 (asc/desc)
* @return Collection 활성 게시판 컬렉션
*/
public function getActiveBoardsOrdered(string $orderBy = 'created_at', string $orderDirection = 'desc'): Collection;
@@ -222,7 +235,7 @@ interface BoardRepositoryInterface
/**
* 특정 유형의 게시판 개수를 반환합니다.
*
* @param string $type 게시판 유형 slug
* @param string $type 게시판 유형 slug
* @return int 해당 유형의 게시판 개수
*/
public function countByType(string $type): int;
@@ -244,4 +257,4 @@ interface BoardRepositoryInterface
* @return int 갱신된 카운트 값
*/
public function recalculateCommentsCount(int $boardId): int;
}
}
@@ -22,6 +22,7 @@ interface PostRepositoryInterface
* @param int $perPage 페이지당 항목 수
* @param bool $withTrashed 삭제된 게시글 포함 여부
* @param Board|null $board 게시판 모델 (이미 조회된 경우 전달하여 중복 쿼리 방지)
* @return Paginator 게시글 페이지네이터
*/
public function paginate(string $slug, array $filters = [], int $perPage = 15, bool $withTrashed = false, ?Board $board = null): Paginator;
@@ -96,6 +97,7 @@ interface PostRepositoryInterface
* @param string $status 변경할 상태 (blinded/deleted)
* @param array $actionLog 작업 이력 데이터
* @param string|null $triggerType 트리거 유형 (admin, report 등)
* @return Post 상태가 변경된 게시글 모델
*
* @throws ModelNotFoundException
*/
@@ -263,6 +265,18 @@ interface PostRepositoryInterface
*/
public function findByBoardId(int $boardId, int $id): ?Post;
/**
* Sitemap 용으로 게시판의 공개 게시글을 스트리밍 조회합니다.
*
* 공개 게시글 = 게시 상태 + 비밀글 아님. 전체 적재를 피하기 위해
* id 기준으로 청크 단위 지연 조회합니다.
*
* @param int $boardId 게시판 ID
* @param int $chunkSize 청크 크기
* @return iterable<Post> 공개 게시글 순회자 (id, updated_at 만 조회)
*/
public function streamPublishedForSitemap(int $boardId, int $chunkSize = 500): iterable;
/**
* 게시판 ID 기준으로 게시글을 일괄 소프트 삭제합니다.
*
@@ -44,6 +44,7 @@ class PostRepository implements PostRepositoryInterface
* @param array $filters 필터 조건
* @param int $perPage 페이지당 항목 수 (일반 게시글 기준)
* @param bool $withTrashed 삭제된 게시글 포함 여부
* @param Board|null $board 게시판 모델 (이미 조회된 경우 전달하여 중복 쿼리 방지)
* @return Paginator 페이지네이션된 게시글 목록 (simplePaginate — COUNT 쿼리 제거)
*/
public function paginate(string $slug, array $filters = [], int $perPage = 15, bool $withTrashed = false, ?Board $board = null): Paginator
@@ -176,6 +177,7 @@ class PostRepository implements PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return Post|null 게시글 모델 (없으면 null)
*/
public function find(string $slug, int $id): ?Post
{
@@ -189,6 +191,7 @@ class PostRepository implements PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return Post 게시글 모델
*
* @throws ModelNotFoundException
*/
@@ -205,6 +208,7 @@ class PostRepository implements PostRepositoryInterface
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @param array $data 수정할 데이터
* @return Post 수정된 게시글 모델
*
* @throws ModelNotFoundException
*/
@@ -221,6 +225,7 @@ class PostRepository implements PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return bool 삭제 성공 여부
*
* @throws ModelNotFoundException
*/
@@ -236,6 +241,7 @@ class PostRepository implements PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return bool 영구 삭제 성공 여부
*
* @throws ModelNotFoundException
*/
@@ -253,6 +259,8 @@ class PostRepository implements PostRepositoryInterface
* @param int $id 게시글 ID
* @param string $status 변경할 상태 (published/blinded/deleted)
* @param array $actionLog 작업 이력 데이터
* @param string|null $triggerType 트리거 유형 (admin, report 등)
* @return Post 상태가 변경된 게시글 모델
*
* @throws ModelNotFoundException
*/
@@ -406,6 +414,7 @@ class PostRepository implements PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @param int|null $boardId 게시판 ID (전달 시 Board 재조회 생략)
* @return Post|null 게시글 모델 (카운트 포함)
*/
public function findWithCounts(string $slug, int $id, ?int $boardId = null): ?Post
@@ -554,6 +563,7 @@ class PostRepository implements PostRepositoryInterface
* @param int $id 현재 게시글 ID
* @param array $filters 정렬 파라미터 (order_by, order_direction)
* @param bool $withTrashed 삭제된 게시글 포함 여부 (기본: false)
* @param int|null $boardId 게시판 ID (전달 시 Board 재조회 생략)
* @return array{prev: Post|null, next: Post|null} 이전/다음 게시글
*/
public function getAdjacentPosts(string $slug, int $id, array $filters = [], bool $withTrashed = false, ?int $boardId = null): array
@@ -1391,6 +1401,27 @@ class PostRepository implements PostRepositoryInterface
->find($id);
}
/**
* Sitemap 용으로 게시판의 공개 게시글을 스트리밍 조회합니다.
*
* lazyById 는 id 기준 키셋 페이징으로 청크를 순차 조회하므로,
* 결과셋 전체가 메모리(및 DB 드라이버 버퍼)에 적재되지 않습니다.
*
* @param int $boardId 게시판 ID
* @param int $chunkSize 청크 크기
* @return iterable<Post> 공개 게시글 순회자 (id, updated_at 만 조회)
*/
public function streamPublishedForSitemap(int $boardId, int $chunkSize = 500): iterable
{
return Post::query()
->where('board_id', $boardId)
->where('status', PostStatus::Published)
->where('is_secret', false)
->select(['id', 'updated_at'])
->orderBy('id')
->lazyById($chunkSize);
}
/**
* 게시판 ID 기준으로 게시글을 일괄 소프트 삭제합니다.
*
@@ -3,17 +3,29 @@
namespace Modules\Sirsoft\Board\Seo;
use App\Seo\Contracts\SitemapContributorInterface;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Post;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Board\Repositories\Contracts\BoardRepositoryInterface;
use Modules\Sirsoft\Board\Repositories\Contracts\PostRepositoryInterface;
/**
* Board 모듈 Sitemap 기여자
*
* 게시판 및 게시글 URL을 sitemap에 제공합니다.
* 데이터 접근은 Repository 인터페이스에 위임합니다.
*/
class BoardSitemapContributor implements SitemapContributorInterface
{
/**
* BoardSitemapContributor 생성자
*
* @param BoardRepositoryInterface $boardRepository 게시판 Repository
* @param PostRepositoryInterface $postRepository 게시글 Repository
*/
public function __construct(
private readonly BoardRepositoryInterface $boardRepository,
private readonly PostRepositoryInterface $postRepository,
) {}
/**
* 확장 식별자를 반환합니다.
*
@@ -35,6 +47,11 @@ class BoardSitemapContributor implements SitemapContributorInterface
{
$urls = [];
// 기여자당 URL 안전 상한 (0 = 무제한). 상한은 이 기여자가 내보내는 모든 URL 유형에
// 적용된다 — 특정 루프에만 걸면 다른 유형이 상한을 넘겨버린다.
$maxUrls = (int) g7_core_settings('seo.sitemap_max_urls_per_contributor', 0);
$truncated = false;
// 'SEO 제공 페이지' 토글 — OFF 시 해당 URL 유형 제외 (기본 노출)
$seoBoards = (bool) g7_module_settings('sirsoft-board', 'seo.seo_boards', true);
$seoBoard = (bool) g7_module_settings('sirsoft-board', 'seo.seo_board', true);
@@ -42,11 +59,11 @@ class BoardSitemapContributor implements SitemapContributorInterface
// 게시판 목록 페이지
if ($seoBoards) {
$urls[] = [
$truncated = ! $this->appendUrl($urls, [
'url' => '/boards',
'changefreq' => 'weekly',
'priority' => 0.5,
];
], $maxUrls);
}
// 개별 게시판/게시글 URL이 모두 OFF면 게시판 조회 자체를 생략
@@ -55,15 +72,19 @@ class BoardSitemapContributor implements SitemapContributorInterface
}
// 게시판별 페이지
$boards = Board::where('is_active', true)->get(['id', 'slug', 'updated_at']);
foreach ($boards as $board) {
if ($seoBoard) {
$urls[] = [
'url' => "/board/{$board->slug}",
'lastmod' => $board->updated_at?->toW3cString(),
'changefreq' => 'daily',
'priority' => 0.6,
];
foreach ($this->boardRepository->streamActiveForSitemap() as $board) {
if ($truncated) {
break;
}
if ($seoBoard && ! $this->appendUrl($urls, [
'url' => "/board/{$board->slug}",
'lastmod' => $board->updated_at?->toW3cString(),
'changefreq' => 'daily',
'priority' => 0.6,
], $maxUrls)) {
$truncated = true;
break;
}
if (! $seoPostDetail) {
@@ -71,20 +92,45 @@ class BoardSitemapContributor implements SitemapContributorInterface
}
// 각 게시판의 공개된 게시글 (비밀글 제외, 게시 상태만)
$posts = Post::where('board_id', $board->id)
->where('status', PostStatus::Published)
->where('is_secret', false)
->get(['id', 'updated_at']);
foreach ($posts as $post) {
$urls[] = [
foreach ($this->postRepository->streamPublishedForSitemap($board->id) as $post) {
if (! $this->appendUrl($urls, [
'url' => "/board/{$board->slug}/{$post->id}",
'lastmod' => $post->updated_at?->toW3cString(),
'changefreq' => 'monthly',
'priority' => 0.5,
];
], $maxUrls)) {
$truncated = true;
break;
}
}
}
if ($truncated) {
Log::warning('[SEO] Sitemap 기여자 URL 상한 초과로 잘렸습니다.', [
'contributor' => $this->getIdentifier(),
'max_urls' => $maxUrls,
]);
}
return $urls;
}
/**
* 안전 상한을 지키며 URL 항목을 추가합니다.
*
* @param array<int, array<string, mixed>> $urls 누적 URL 배열 (참조)
* @param array<string, mixed> $entry 추가할 URL 항목
* @param int $maxUrls 기여자당 URL 상한 (0 = 무제한)
* @return bool 추가되면 true, 상한 도달로 추가하지 못하면 false
*/
private function appendUrl(array &$urls, array $entry, int $maxUrls): bool
{
if ($maxUrls > 0 && count($urls) >= $maxUrls) {
return false;
}
$urls[] = $entry;
return true;
}
}
@@ -0,0 +1,140 @@
<?php
namespace Modules\Sirsoft\Board\Tests\Unit\Repositories;
require_once __DIR__.'/../../ModuleTestCase.php';
use Illuminate\Support\LazyCollection;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Repositories\Contracts\BoardRepositoryInterface;
use Modules\Sirsoft\Board\Tests\BoardTestCase;
/**
* BoardRepository::streamActiveForSitemap 단위 테스트
*
* 검증 목적:
* - 순회자(LazyCollection) 를 반환한다 (전체 적재 금지)
* - sitemap 에 필요한 컬럼만 적재한다 (전컬럼 적재 회귀 차단)
* - 활성 게시판만 반환한다
*
* @group board
* @group unit
* @group seo
*/
class BoardRepositorySitemapTest extends BoardTestCase
{
private BoardRepositoryInterface $repository;
protected function getTestBoardSlug(): string
{
return 'repo-sitemap-test';
}
protected function getDefaultBoardAttributes(string $slug): array
{
return [
'slug' => $slug,
'name' => ['ko' => '레포지토리 사이트맵 테스트', 'en' => 'Repository Sitemap Test'],
'is_active' => true,
];
}
protected function setUp(): void
{
parent::setUp();
$this->repository = $this->app->make(BoardRepositoryInterface::class);
}
/**
* 테스트 정리 - 이 클래스가 생성한 게시판을 제거합니다.
*
* BoardTestCase 는 트랜잭션 롤백 대신 수동 삭제 전략을 쓰며 게시판 자체는
* 지우지 않는다. 추가 게시판을 만든 쪽이 정리하지 않으면 활성 게시판이
* 다른 테스트 클래스로 누출되어 게시판 목록 단언을 깨뜨린다.
*/
protected function tearDown(): void
{
Board::where('slug', 'like', 'repo-sitemap-%')->forceDelete();
parent::tearDown();
}
/**
* streamActiveForSitemap: 전체 적재가 아닌 순회자를 반환한다
*/
public function test_stream_active_for_sitemap_returns_lazy_collection(): void
{
$this->assertInstanceOf(
LazyCollection::class,
$this->repository->streamActiveForSitemap(),
'lazyById 순회자여야 전체 적재를 피할 수 있습니다.'
);
}
/**
* streamActiveForSitemap: sitemap 에 필요한 컬럼만 적재한다 (회귀)
*
* 범용 getActiveBoards() 는 전컬럼을 적재하므로 sitemap 경로가 그것을 재사용하면
* 메모리가 후퇴한다. select 가 유지되는지 속성 키로 검증한다.
*/
public function test_stream_active_for_sitemap_selects_only_sitemap_columns(): void
{
$board = $this->repository->streamActiveForSitemap()->first();
$this->assertNotNull($board);
$this->assertSame(
['id', 'slug', 'updated_at'],
array_keys($board->getAttributes()),
'sitemap 조회는 id/slug/updated_at 만 적재해야 합니다.'
);
}
/**
* streamActiveForSitemap: 비활성 게시판은 반환하지 않는다
*/
public function test_stream_active_for_sitemap_excludes_inactive_boards(): void
{
$this->updateBoardSettings(['is_active' => false]);
$slugs = collect($this->repository->streamActiveForSitemap())
->pluck('slug')
->all();
$this->assertNotContains($this->board->slug, $slugs);
}
/**
* streamActiveForSitemap: 활성 게시판이 포함된다
*/
public function test_stream_active_for_sitemap_includes_active_boards(): void
{
$slugs = collect($this->repository->streamActiveForSitemap())
->pluck('slug')
->all();
$this->assertContains($this->board->slug, $slugs);
}
/**
* streamActiveForSitemap: 청크 크기보다 많은 게시판도 전부 순회한다
*/
public function test_stream_active_for_sitemap_traverses_beyond_chunk_size(): void
{
foreach (range(1, 3) as $i) {
Board::create([
'slug' => "repo-sitemap-extra-{$i}",
'name' => ['ko' => "추가 게시판 {$i}", 'en' => "Extra Board {$i}"],
'is_active' => true,
]);
}
// 청크 크기 1 → 여러 번 쿼리해도 누락 없이 전부 순회해야 한다
$slugs = collect($this->repository->streamActiveForSitemap(1))
->pluck('slug')
->all();
foreach (range(1, 3) as $i) {
$this->assertContains("repo-sitemap-extra-{$i}", $slugs);
}
}
}
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Board\Tests\Unit\Seo;
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Seo\Contracts\SitemapContributorInterface;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Board\Seo\BoardSitemapContributor;
@@ -47,7 +48,16 @@ class BoardSitemapContributorTest extends BoardTestCase
protected function setUp(): void
{
parent::setUp();
$this->contributor = new BoardSitemapContributor;
// Repository 주입이 필요하므로 컨테이너로 해석합니다.
$this->contributor = $this->app->make(BoardSitemapContributor::class);
}
/**
* SitemapContributorInterface 를 구현한다
*/
public function test_implements_sitemap_contributor_interface(): void
{
$this->assertInstanceOf(SitemapContributorInterface::class, $this->contributor);
}
/**
@@ -58,6 +68,51 @@ class BoardSitemapContributorTest extends BoardTestCase
$this->assertSame('sirsoft-board', $this->contributor->getIdentifier());
}
/**
* getUrls: 활성 게시판이 없으면 정적 목록 URL만 반환한다
*/
public function test_get_urls_returns_only_static_url_when_no_active_boards(): void
{
$this->updateBoardSettings(['is_active' => false]);
$urls = $this->contributor->getUrls();
$this->assertSame(['/boards'], array_column($urls, 'url'));
}
/**
* getUrls: 기여자당 URL 안전 상한을 초과하면 게시글 URL이 잘린다
*/
public function test_get_urls_truncates_at_max_urls_per_contributor(): void
{
$this->createTestPost(['status' => 'published', 'is_secret' => false]);
$this->createTestPost(['status' => 'published', 'is_secret' => false]);
// /boards + /board/{slug} 로 이미 2건이므로 게시글은 1건까지만 담긴다.
// g7_core_settings 는 Config 파사드 기반이므로 Config::set 으로 주입합니다.
Config::set('g7_settings.core.seo.sitemap_max_urls_per_contributor', 3);
$this->assertCount(3, $this->contributor->getUrls());
}
/**
* getUrls: 상한이 게시판 루프에도 적용된다 (회귀)
*
* 상한 검사가 게시글 루프에만 있으면, 게시판 URL 만으로 상한을 초과해도 잘리지 않는다.
*/
public function test_get_urls_truncates_within_board_loop(): void
{
$this->createTestPost(['status' => 'published', 'is_secret' => false]);
// /boards 1건만 담기면 상한 도달 → 게시판/게시글 URL 은 하나도 담기지 않아야 한다.
Config::set('g7_settings.core.seo.sitemap_max_urls_per_contributor', 1);
$urls = $this->contributor->getUrls();
$this->assertCount(1, $urls, '게시판 루프에서도 상한이 지켜져야 합니다.');
$this->assertSame('/boards', $urls[0]['url']);
}
/**
* getUrls: /boards 항목이 반드시 포함된다
*/
@@ -4,6 +4,16 @@
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [1.0.5] - 2026-07-16
### Added
- 사이트맵에 담을 상품·카테고리 수의 안전 상한을 지원합니다. 상한을 설정하면 상품 목록·카테고리·상품 어느 항목이든 그 수를 넘지 않으며, 상한에 걸려 일부가 빠진 경우 기록으로 남습니다.
### Changed
- 사이트맵을 만들 때 상품과 카테고리를 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 상품이 많은 쇼핑몰에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
## [1.0.4] - 2026-07-16
### Fixed
@@ -2,7 +2,7 @@
"name": "modules/sirsoft-ecommerce",
"description": "Ecommerce module for Gnuboard7",
"type": "library",
"version": "1.0.4",
"version": "1.0.5",
"license": "MIT",
"autoload": {
"psr-4": {
@@ -5,7 +5,7 @@
"ko": "이커머스",
"en": "Ecommerce"
},
"version": "1.0.4",
"version": "1.0.5",
"license": "MIT",
"description": {
"ko": "그누보드7 이커머스 모듈 - 상품, 주문, 결제 관리",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@g7/sirsoft-ecommerce",
"version": "1.0.4",
"version": "1.0.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@g7/sirsoft-ecommerce",
"version": "1.0.4",
"version": "1.0.5",
"devDependencies": {
"jsdom": "^27.4.0",
"typescript": "^5.3.3",
@@ -1,6 +1,6 @@
{
"name": "@g7/sirsoft-ecommerce",
"version": "1.0.4",
"version": "1.0.5",
"description": "그누보드7 이커머스 모듈 프론트엔드 에셋",
"private": true,
"type": "module",
@@ -218,8 +218,9 @@ class EcommerceServiceProvider extends BaseModuleServiceProvider
// Sitemap 기여자 등록
$this->app->booted(function () {
if ($this->app->bound(SitemapGenerator::class)) {
// Repository 주입을 위해 컨테이너로 해석합니다.
$this->app->make(SitemapGenerator::class)->registerContributor(
new EcommerceSitemapContributor
$this->app->make(EcommerceSitemapContributor::class)
);
}
});
@@ -15,6 +15,24 @@ class CategoryRepository implements CategoryRepositoryInterface
protected Category $model
) {}
/**
* Sitemap 용으로 활성 카테고리를 스트리밍 조회합니다.
*
* lazyById 는 id 기준 키셋 페이징으로 청크를 순차 조회하므로,
* 결과셋 전체가 메모리(및 DB 드라이버 버퍼)에 적재되지 않습니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Category> 활성 카테고리 순회자 (id, slug, updated_at 만 조회)
*/
public function streamActiveForSitemap(int $chunkSize = 500): iterable
{
return $this->model->newQuery()
->where('is_active', true)
->select(['id', 'slug', 'updated_at'])
->orderBy('id')
->lazyById($chunkSize);
}
/**
* {@inheritDoc}
*/
@@ -76,7 +94,7 @@ class CategoryRepository implements CategoryRepositoryInterface
{
$query = $this->model->newQuery();
if (!empty($with)) {
if (! empty($with)) {
$query->with($with);
}
@@ -101,6 +119,7 @@ class CategoryRepository implements CategoryRepositoryInterface
{
$category = $this->findById($id);
$category->update($data);
return $category->fresh();
}
@@ -110,6 +129,7 @@ class CategoryRepository implements CategoryRepositoryInterface
public function delete(int $id): bool
{
$category = $this->findById($id);
return $category->delete();
}
@@ -127,6 +147,7 @@ class CategoryRepository implements CategoryRepositoryInterface
public function getProductCount(int $id): int
{
$category = $this->findById($id);
return $category->products()->count();
}
@@ -13,94 +13,104 @@ interface CategoryRepositoryInterface
/**
* 계층형 카테고리 목록 조회
*
* @param array $filters 필터 조건
* @param array $with Eager loading 관계
* @return Collection
* @param array $filters 필터 조건
* @param array $with Eager loading 관계
* @return Collection 계층형 카테고리 목록
*/
public function getHierarchical(array $filters = [], array $with = []): Collection;
/**
* ID로 카테고리 조회
*
* @param int $id 카테고리 ID
* @param array $with Eager loading 관계
* @return Category|null
* @param int $id 카테고리 ID
* @param array $with Eager loading 관계
* @return Category|null 카테고리 모델 (없으면 null)
*/
public function findById(int $id, array $with = []): ?Category;
/**
* 카테고리 생성
*
* @param array $data 카테고리 데이터
* @return Category
* @param array $data 카테고리 데이터
* @return Category 생성된 카테고리 모델
*/
public function create(array $data): Category;
/**
* 카테고리 수정
*
* @param int $id 카테고리 ID
* @param array $data 수정 데이터
* @return Category
* @param int $id 카테고리 ID
* @param array $data 수정 데이터
* @return Category 수정된 카테고리 모델
*/
public function update(int $id, array $data): Category;
/**
* 카테고리 삭제
*
* @param int $id 카테고리 ID
* @return bool
* @param int $id 카테고리 ID
* @return bool 삭제 성공 여부
*/
public function delete(int $id): bool;
/**
* 하위 카테고리 존재 여부 확인
*
* @param int $id 카테고리 ID
* @return bool
* @param int $id 카테고리 ID
* @return bool 하위 카테고리 존재 여부
*/
public function hasChildren(int $id): bool;
/**
* 연결된 상품 수 조회
*
* @param int $id 카테고리 ID
* @return int
* @param int $id 카테고리 ID
* @return int 연결된 상품 수
*/
public function getProductCount(int $id): int;
/**
* 다음 정렬 순서 값 조회
*
* @param int|null $parentId 부모 카테고리 ID
* @return int
* @param int|null $parentId 부모 카테고리 ID
* @return int 다음 정렬 순서 값
*/
public function getNextSortOrder(?int $parentId = null): int;
/**
* 슬러그 중복 확인
*
* @param string $slug 슬러그
* @param int|null $excludeId 제외할 카테고리 ID
* @return bool
* @param string $slug 슬러그
* @param int|null $excludeId 제외할 카테고리 ID
* @return bool 슬러그 중복 여부
*/
public function existsBySlug(string $slug, ?int $excludeId = null): bool;
/**
* slug로 카테고리 조회
*
* @param string $slug 카테고리 slug
* @param array $with Eager loading 관계
* @return Category|null
* @param string $slug 카테고리 slug
* @param array $with Eager loading 관계
* @return Category|null 카테고리 모델 (없으면 null)
*/
public function findBySlug(string $slug, array $with = []): ?Category;
/**
* 평면 리스트로 카테고리 목록 조회 (TagInput 등에 사용)
*
* @param array $filters 필터 조건
* @param array $with Eager loading 관계
* @return Collection
* @param array $filters 필터 조건
* @param array $with Eager loading 관계
* @return Collection 평면 카테고리 목록
*/
public function getFlatList(array $filters = [], array $with = []): Collection;
/**
* Sitemap 용으로 활성 카테고리를 스트리밍 조회합니다.
*
* 전체 적재를 피하기 위해 id 기준으로 청크 단위 지연 조회합니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Category> 활성 카테고리 순회자 (id, slug, updated_at 만 조회)
*/
public function streamActiveForSitemap(int $chunkSize = 500): iterable;
}
@@ -29,6 +29,16 @@ interface ProductRepositoryInterface
*/
public function existsAny(): bool;
/**
* Sitemap 용으로 전시 중인 상품을 스트리밍 조회합니다.
*
* 전체 적재를 피하기 위해 id 기준으로 청크 단위 지연 조회합니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Product> 전시 중인 상품 순회자 (id, updated_at 만 조회)
*/
public function streamVisibleForSitemap(int $chunkSize = 500): iterable;
/**
* 필터링된 상품 목록 조회 (페이지네이션)
*
@@ -32,6 +32,24 @@ class ProductRepository implements ProductRepositoryInterface
return $this->model->newQuery()->withTrashed()->exists();
}
/**
* Sitemap 용으로 전시 중인 상품을 스트리밍 조회합니다.
*
* lazyById 는 id 기준 키셋 페이징으로 청크를 순차 조회하므로,
* 결과셋 전체가 메모리(및 DB 드라이버 버퍼)에 적재되지 않습니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Product> 전시 중인 상품 순회자 (id, updated_at 만 조회)
*/
public function streamVisibleForSitemap(int $chunkSize = 500): iterable
{
return $this->model->newQuery()
->where('display_status', ProductDisplayStatus::VISIBLE->value)
->select(['id', 'updated_at'])
->orderBy('id')
->lazyById($chunkSize);
}
/**
* {@inheritDoc}
*/
@@ -3,17 +3,29 @@
namespace Modules\Sirsoft\Ecommerce\Seo;
use App\Seo\Contracts\SitemapContributorInterface;
use Modules\Sirsoft\Ecommerce\Enums\ProductDisplayStatus;
use Modules\Sirsoft\Ecommerce\Models\Category;
use Modules\Sirsoft\Ecommerce\Models\Product;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CategoryRepositoryInterface;
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
/**
* Ecommerce 모듈 Sitemap 기여자
*
* 상품 및 카테고리 URL을 sitemap에 제공합니다.
* 데이터 접근은 Repository 인터페이스에 위임합니다.
*/
class EcommerceSitemapContributor implements SitemapContributorInterface
{
/**
* EcommerceSitemapContributor 생성자
*
* @param CategoryRepositoryInterface $categoryRepository 카테고리 Repository
* @param ProductRepositoryInterface $productRepository 상품 Repository
*/
public function __construct(
private readonly CategoryRepositoryInterface $categoryRepository,
private readonly ProductRepositoryInterface $productRepository,
) {}
/**
* 확장 식별자를 반환합니다.
*
@@ -36,42 +48,76 @@ class EcommerceSitemapContributor implements SitemapContributorInterface
$urls = [];
$routePath = g7_module_settings('sirsoft-ecommerce', 'basic_info.route_path') ?? 'shop';
// 기여자당 URL 안전 상한 (0 = 무제한). 상한은 이 기여자가 내보내는 모든 URL 유형에
// 적용된다 — 특정 루프에만 걸면 다른 유형이 상한을 넘겨버린다.
$maxUrls = (int) g7_core_settings('seo.sitemap_max_urls_per_contributor', 0);
$truncated = false;
// 상품 목록 페이지 — 'SEO 제공 페이지' 토글 OFF 시 제외
if ((bool) g7_module_settings('sirsoft-ecommerce', 'seo.seo_shop_index', true)) {
$urls[] = [
$truncated = ! $this->appendUrl($urls, [
'url' => "/{$routePath}/products",
'changefreq' => 'daily',
'priority' => 0.7,
];
], $maxUrls);
}
// 카테고리별 페이지 — 토글 OFF 시 제외
if ((bool) g7_module_settings('sirsoft-ecommerce', 'seo.seo_category', true)) {
$categories = Category::where('is_active', true)->get(['id', 'slug', 'updated_at']);
foreach ($categories as $category) {
$urls[] = [
if (! $truncated && (bool) g7_module_settings('sirsoft-ecommerce', 'seo.seo_category', true)) {
foreach ($this->categoryRepository->streamActiveForSitemap() as $category) {
if (! $this->appendUrl($urls, [
'url' => "/{$routePath}/category/{$category->slug}",
'lastmod' => $category->updated_at?->toW3cString(),
'changefreq' => 'weekly',
'priority' => 0.6,
];
], $maxUrls)) {
$truncated = true;
break;
}
}
}
// 개별 상품 페이지 (전시 상태가 '전시'인 상품만) — 토글 OFF 시 제외
if ((bool) g7_module_settings('sirsoft-ecommerce', 'seo.seo_product_detail', true)) {
$products = Product::where('display_status', ProductDisplayStatus::VISIBLE)
->get(['id', 'updated_at']);
foreach ($products as $product) {
$urls[] = [
if (! $truncated && (bool) g7_module_settings('sirsoft-ecommerce', 'seo.seo_product_detail', true)) {
foreach ($this->productRepository->streamVisibleForSitemap() as $product) {
if (! $this->appendUrl($urls, [
'url' => "/{$routePath}/products/{$product->id}",
'lastmod' => $product->updated_at?->toW3cString(),
'changefreq' => 'weekly',
'priority' => 0.8,
];
], $maxUrls)) {
$truncated = true;
break;
}
}
}
if ($truncated) {
Log::warning('[SEO] Sitemap 기여자 URL 상한 초과로 잘렸습니다.', [
'contributor' => $this->getIdentifier(),
'max_urls' => $maxUrls,
]);
}
return $urls;
}
/**
* 안전 상한을 지키며 URL 항목을 추가합니다.
*
* @param array<int, array<string, mixed>> $urls 누적 URL 배열 (참조)
* @param array<string, mixed> $entry 추가할 URL 항목
* @param int $maxUrls 기여자당 URL 상한 (0 = 무제한)
* @return bool 추가되면 true, 상한 도달로 추가하지 못하면 false
*/
private function appendUrl(array &$urls, array $entry, int $maxUrls): bool
{
if ($maxUrls > 0 && count($urls) >= $maxUrls) {
return false;
}
$urls[] = $entry;
return true;
}
}
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Seo;
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Seo\Contracts\SitemapContributorInterface;
use Illuminate\Support\Facades\Config;
use Modules\Sirsoft\Ecommerce\Models\Category;
use Modules\Sirsoft\Ecommerce\Models\Product;
@@ -31,7 +32,8 @@ class EcommerceSitemapContributorTest extends ModuleTestCase
protected function setUp(): void
{
parent::setUp();
$this->contributor = new EcommerceSitemapContributor;
// Repository 주입이 필요하므로 컨테이너로 해석합니다.
$this->contributor = $this->app->make(EcommerceSitemapContributor::class);
$this->routePath = g7_module_settings('sirsoft-ecommerce', 'basic_info.route_path') ?? 'shop';
}
@@ -50,6 +52,14 @@ class EcommerceSitemapContributorTest extends ModuleTestCase
]);
}
/**
* SitemapContributorInterface 를 구현한다
*/
public function test_implements_sitemap_contributor_interface(): void
{
$this->assertInstanceOf(SitemapContributorInterface::class, $this->contributor);
}
/**
* getIdentifier: 'sirsoft-ecommerce' 반환
*/
@@ -58,6 +68,96 @@ class EcommerceSitemapContributorTest extends ModuleTestCase
$this->assertSame('sirsoft-ecommerce', $this->contributor->getIdentifier());
}
/**
* getUrls: route_path 미설정 시 기본값 'shop' 을 사용한다
*/
public function test_get_urls_uses_default_route_path_when_not_configured(): void
{
Config::set('g7_settings.modules.sirsoft-ecommerce.basic_info.route_path', null);
$contributor = $this->app->make(EcommerceSitemapContributor::class);
$urlPaths = array_column($contributor->getUrls(), 'url');
$this->assertContains('/shop/products', $urlPaths);
}
/**
* getUrls: 정적/카테고리/상품 URL 항목이 각각 올바른 키 구조를 가진다
*/
public function test_url_entries_have_correct_structure(): void
{
$category = $this->createTestCategory();
$product = Product::factory()->create();
$urls = collect($this->contributor->getUrls());
// 정적 목록 URL — lastmod 없음
$index = $urls->firstWhere('url', "/{$this->routePath}/products");
$this->assertNotNull($index);
$this->assertSame('daily', $index['changefreq']);
$this->assertSame(0.7, $index['priority']);
$this->assertArrayNotHasKey('lastmod', $index);
// 카테고리 URL — lastmod 있음
$categoryEntry = $urls->firstWhere('url', "/{$this->routePath}/category/{$category->slug}");
$this->assertNotNull($categoryEntry);
$this->assertArrayHasKey('lastmod', $categoryEntry);
$this->assertSame('weekly', $categoryEntry['changefreq']);
$this->assertSame(0.6, $categoryEntry['priority']);
// 상품 URL — lastmod 있음
$productEntry = $urls->firstWhere('url', "/{$this->routePath}/products/{$product->id}");
$this->assertNotNull($productEntry);
$this->assertArrayHasKey('lastmod', $productEntry);
$this->assertSame('weekly', $productEntry['changefreq']);
$this->assertSame(0.8, $productEntry['priority']);
}
/**
* getUrls: 기여자당 URL 안전 상한을 초과하면 상품 URL이 잘린다
*/
public function test_get_urls_truncates_at_max_urls_per_contributor(): void
{
Product::factory()->count(3)->create();
// 정적 목록 URL 1건이 이미 담기므로 상품은 1건까지만 담긴다.
// g7_core_settings 는 Config 파사드 기반이므로 Config::set 으로 주입합니다.
Config::set('g7_settings.core.seo.sitemap_max_urls_per_contributor', 2);
$this->assertCount(2, $this->contributor->getUrls());
}
/**
* getUrls: 상한이 카테고리 루프에도 적용된다 (회귀)
*
* 상한 검사가 상품 루프에만 있으면, 카테고리만으로 상한을 초과해도 잘리지 않는다.
*/
public function test_get_urls_truncates_within_category_loop(): void
{
$this->createTestCategory();
Category::create([
'name' => ['ko' => '사이트맵 카테고리2', 'en' => 'Sitemap Category 2'],
'slug' => 'sitemap-cat-2',
'is_active' => true,
'path' => '/',
'depth' => 0,
'sort_order' => 1,
]);
Product::factory()->count(2)->create();
// 정적 목록 1건 + 카테고리 2건 = 3건이지만 상한은 2건.
Config::set('g7_settings.core.seo.sitemap_max_urls_per_contributor', 2);
$urls = $this->contributor->getUrls();
$this->assertCount(2, $urls, '카테고리 루프에서도 상한이 지켜져야 합니다.');
// 상한 도달 후에는 상품 URL 이 하나도 담기지 않아야 한다
$this->assertEmpty(
array_filter($urls, fn (array $u): bool => str_contains($u['url'], '/products/')),
'상한 도달 후 상품 URL 이 추가되면 안 됩니다.'
);
}
/**
* getUrls: 기본(토글 ON) 상태에서 목록/카테고리/상품 URL이 모두 포함된다 (비파괴 회귀)
*/
@@ -1,15 +1,15 @@
{
"schema_version": "1.0",
"generated_at": "2026-07-14T14:08:36+00:00",
"generated_at": "2026-07-16T15:36:56+00:00",
"generator": "g7 vendor-bundle:build",
"target": "module:sirsoft-ecommerce",
"composer_json_sha256": "a90f1bb9cceeb9542e84ca09a0945f31089879fdbb566044364058332627998a",
"composer_json_sha256": "892a78a4c180c410eeb2cafbdec3ee1ff87ea066db94dea7e1340678e91759f6",
"composer_lock_sha256": "876ca9c2273a33baff878d25050a567018a946412db053930a7f548c4add595d",
"zip_sha256": "ffc7123cd61c7ca13a6dc29325aa31454005affd59fe97acf372d30ab016475d",
"zip_sha256": "e222da279ba452bd155fb68f06d6bcdd0c2f29041f231eeea3ef6229912e9dcc",
"zip_size": 435549,
"package_count": 1,
"php_requirement": "^8.2",
"g7_version": "7.0.4",
"g7_version": "7.0.5",
"packages": [
{
"name": "ezyang/htmlpurifier",
Binary file not shown.
@@ -4,6 +4,16 @@
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
## [1.0.2] - 2026-07-16
### Added
- 사이트맵에 담을 페이지 수의 안전 상한을 지원합니다. 상한을 설정하면 그 수를 넘지 않으며, 상한에 걸려 일부가 빠진 경우 기록으로 남습니다.
### Changed
- 사이트맵을 만들 때 페이지를 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 페이지가 많은 사이트에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
## [1.0.1] - 2026-07-08
### Fixed
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "modules/sirsoft-page",
"description": "Page module for Gnuboard7",
"type": "library",
"version": "1.0.1",
"version": "1.0.2",
"license": "MIT",
"autoload": {
"psr-4": {
+1 -1
View File
@@ -5,7 +5,7 @@
"ko": "페이지",
"en": "Page"
},
"version": "1.0.1",
"version": "1.0.2",
"license": "MIT",
"description": {
"ko": "정적 페이지(정보/정책/안내) 관리 모듈",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@g7/sirsoft-page",
"version": "1.0.1",
"version": "1.0.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@g7/sirsoft-page",
"version": "1.0.1",
"version": "1.0.2",
"devDependencies": {
"jsdom": "^27.4.0",
"typescript": "^5.3.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@g7/sirsoft-page",
"version": "1.0.1",
"version": "1.0.2",
"description": "그누보드7 페이지 모듈 프론트엔드 에셋",
"private": true,
"type": "module",
@@ -63,8 +63,9 @@ class PageServiceProvider extends BaseModuleServiceProvider
// Sitemap 기여자 등록
$this->app->booted(function () {
if ($this->app->bound(SitemapGenerator::class)) {
// Repository 주입을 위해 컨테이너로 해석합니다.
$this->app->make(SitemapGenerator::class)->registerContributor(
new PageSitemapContributor
$this->app->make(PageSitemapContributor::class)
);
}
});
@@ -2,6 +2,8 @@
namespace Modules\Sirsoft\Page\Repositories\Contracts;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Sirsoft\Page\Models\Page;
@@ -35,13 +37,23 @@ interface PageRepositoryInterface
*/
public function findBySlug(string $slug): ?Page;
/**
* Sitemap 용으로 발행된 페이지를 스트리밍 조회합니다.
*
* 전체 적재를 피하기 위해 id 기준으로 청크 단위 지연 조회합니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Page> 발행된 페이지 순회자 (id, slug, updated_at 만 조회)
*/
public function streamPublishedForSitemap(int $chunkSize = 500): iterable;
/**
* ID로 페이지를 조회하며, 없으면 예외를 발생시킵니다.
*
* @param int $id 페이지 ID
* @return Page 페이지 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(int $id): Page;
@@ -86,7 +98,7 @@ interface PageRepositoryInterface
* @param string $orderBy 정렬 컬럼
* @param string $direction 정렬 방향 (asc, desc)
* @param int $limit 조회할 최대 항목 수
* @return array{total: int, items: \Illuminate\Database\Eloquent\Collection}
* @return array{total: int, items: Collection}
*/
public function searchByKeyword(string $keyword, string $orderBy = 'created_at', string $direction = 'desc', int $limit = 10): array;
@@ -72,6 +72,24 @@ class PageRepository implements PageRepositoryInterface
return Page::where('slug', $slug)->first();
}
/**
* Sitemap 용으로 발행된 페이지를 스트리밍 조회합니다.
*
* lazyById 는 id 기준 키셋 페이징으로 청크를 순차 조회하므로,
* 결과셋 전체가 메모리(및 DB 드라이버 버퍼)에 적재되지 않습니다.
*
* @param int $chunkSize 청크 크기
* @return iterable<Page> 발행된 페이지 순회자 (id, slug, updated_at 만 조회)
*/
public function streamPublishedForSitemap(int $chunkSize = 500): iterable
{
return Page::query()
->where('published', true)
->select(['id', 'slug', 'updated_at'])
->orderBy('id')
->lazyById($chunkSize);
}
/**
* ID로 페이지를 조회하며, 없으면 예외를 발생시킵니다.
*
@@ -3,15 +3,26 @@
namespace Modules\Sirsoft\Page\Seo;
use App\Seo\Contracts\SitemapContributorInterface;
use Modules\Sirsoft\Page\Models\Page;
use Illuminate\Support\Facades\Log;
use Modules\Sirsoft\Page\Repositories\Contracts\PageRepositoryInterface;
/**
* Page 모듈 Sitemap 기여자
*
* 발행된 페이지 URL을 sitemap에 제공합니다.
* 데이터 접근은 Repository 인터페이스에 위임합니다.
*/
class PageSitemapContributor implements SitemapContributorInterface
{
/**
* PageSitemapContributor 생성자
*
* @param PageRepositoryInterface $pageRepository 페이지 Repository
*/
public function __construct(
private readonly PageRepositoryInterface $pageRepository,
) {}
/**
* 확장 식별자를 반환합니다.
*
@@ -33,16 +44,48 @@ class PageSitemapContributor implements SitemapContributorInterface
{
$urls = [];
$pages = Page::where('published', true)->get(['slug', 'updated_at']);
foreach ($pages as $page) {
$urls[] = [
// 기여자당 URL 안전 상한 (0 = 무제한). 상한은 이 기여자가 내보내는 모든 URL 유형에 적용된다.
$maxUrls = (int) g7_core_settings('seo.sitemap_max_urls_per_contributor', 0);
$truncated = false;
foreach ($this->pageRepository->streamPublishedForSitemap() as $page) {
if (! $this->appendUrl($urls, [
'url' => "/page/{$page->slug}",
'lastmod' => $page->updated_at?->toW3cString(),
'changefreq' => 'monthly',
'priority' => 0.5,
];
], $maxUrls)) {
$truncated = true;
break;
}
}
if ($truncated) {
Log::warning('[SEO] Sitemap 기여자 URL 상한 초과로 잘렸습니다.', [
'contributor' => $this->getIdentifier(),
'max_urls' => $maxUrls,
]);
}
return $urls;
}
/**
* 안전 상한을 지키며 URL 항목을 추가합니다.
*
* @param array<int, array<string, mixed>> $urls 누적 URL 배열 (참조)
* @param array<string, mixed> $entry 추가할 URL 항목
* @param int $maxUrls 기여자당 URL 상한 (0 = 무제한)
* @return bool 추가되면 true, 상한 도달로 추가하지 못하면 false
*/
private function appendUrl(array &$urls, array $entry, int $maxUrls): bool
{
if ($maxUrls > 0 && count($urls) >= $maxUrls) {
return false;
}
$urls[] = $entry;
return true;
}
}
@@ -0,0 +1,120 @@
<?php
namespace Modules\Sirsoft\Page\Tests\Unit\Seo;
require_once __DIR__.'/../../ModuleTestCase.php';
use App\Seo\Contracts\SitemapContributorInterface;
use Illuminate\Support\Facades\Config;
use Modules\Sirsoft\Page\Models\Page;
use Modules\Sirsoft\Page\Seo\PageSitemapContributor;
use Modules\Sirsoft\Page\Tests\ModuleTestCase;
/**
* PageSitemapContributor 단위 테스트
*
* 검증 목적:
* - getIdentifier: 'sirsoft-page' 반환
* - getUrls: 발행된 페이지 URL 포함
* - getUrls: 미발행 페이지 URL 미포함
* - getUrls: URL 항목 구조 (url/lastmod/changefreq/priority)
* - getUrls: 기여자당 URL 안전 상한 초과 시 절단
*
* @group page
* @group unit
* @group seo
*/
class PageSitemapContributorTest extends ModuleTestCase
{
private PageSitemapContributor $contributor;
/**
* 테스트 초기화 - 기여자를 컨테이너로 해석합니다.
*/
protected function setUp(): void
{
parent::setUp();
// Repository 주입이 필요하므로 컨테이너로 해석합니다.
$this->contributor = $this->app->make(PageSitemapContributor::class);
}
/**
* SitemapContributorInterface 를 구현한다
*/
public function test_implements_sitemap_contributor_interface(): void
{
$this->assertInstanceOf(SitemapContributorInterface::class, $this->contributor);
}
/**
* getIdentifier: 'sirsoft-page' 반환
*/
public function test_get_identifier_returns_sirsoft_page(): void
{
$this->assertSame('sirsoft-page', $this->contributor->getIdentifier());
}
/**
* getUrls: 발행된 페이지 URL이 포함된다
*/
public function test_get_urls_includes_published_page(): void
{
$page = Page::factory()->published()->create();
$urlPaths = array_column($this->contributor->getUrls(), 'url');
$this->assertContains("/page/{$page->slug}", $urlPaths);
}
/**
* getUrls: 미발행 페이지는 포함되지 않는다
*/
public function test_get_urls_excludes_unpublished_page(): void
{
$page = Page::factory()->create(['published' => false]);
$urlPaths = array_column($this->contributor->getUrls(), 'url');
$this->assertNotContains("/page/{$page->slug}", $urlPaths);
}
/**
* getUrls: URL 항목이 올바른 키 구조를 가진다
*/
public function test_url_entries_have_correct_structure(): void
{
$page = Page::factory()->published()->create();
$urls = $this->contributor->getUrls();
$entry = collect($urls)->firstWhere('url', "/page/{$page->slug}");
$this->assertNotNull($entry);
$this->assertArrayHasKey('lastmod', $entry);
$this->assertSame('monthly', $entry['changefreq']);
$this->assertSame(0.5, $entry['priority']);
}
/**
* getUrls: 발행된 페이지가 없으면 빈 배열을 반환한다
*/
public function test_get_urls_returns_empty_array_when_no_published_pages(): void
{
Page::factory()->count(2)->create(['published' => false]);
$this->assertSame([], $this->contributor->getUrls());
}
/**
* getUrls: 기여자당 URL 안전 상한을 초과하면 잘린다
*/
public function test_get_urls_truncates_at_max_urls_per_contributor(): void
{
Page::factory()->count(3)->published()->create();
// g7_core_settings 는 Config 파사드 기반이므로 Config::set 으로 주입합니다.
Config::set('g7_settings.core.seo.sitemap_max_urls_per_contributor', 2);
$this->assertCount(2, $this->contributor->getUrls());
}
}