v7.0.0-beta.2 release

This commit is contained in:
HeuJung committed 2026-04-20 20:37:49 +09:00
1 parent 6595fd0eb5
commit fa8eba7a0d
1165 files changed
+107118 -762127

No files matched your search

@@ -3,8 +3,12 @@
namespace Modules\Sirsoft\Board\Repositories;
use App\Helpers\PermissionHelper;
use App\Helpers\TimezoneHelper;
use App\Search\Engines\DatabaseFulltextEngine;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Board\Enums\PostStatus;
use Modules\Sirsoft\Board\Models\Board;
@@ -24,6 +28,11 @@ class PostRepository implements PostRepositoryInterface
use ChecksBoardPermission;
use FormatsBoardDate;
/**
* PostRepository 생성자
*/
public function __construct() {}
/**
* 게시판의 게시글 목록을 페이지네이션하여 조회합니다.
*
@@ -31,29 +40,41 @@ class PostRepository implements PostRepositoryInterface
* @param array $filters 필터 조건
* @param int $perPage 페이지당 항목 수 (일반 게시글 기준)
* @param bool $withTrashed 삭제된 게시글 포함 여부
* @return LengthAwarePaginator 페이지네이션된 게시글 목록
* @return Paginator 페이지네이션된 게시글 목록 (simplePaginate — COUNT 쿼리 제거)
*/
public function paginate(string $slug, array $filters = [], int $perPage = 15, bool $withTrashed = false): LengthAwarePaginator
public function paginate(string $slug, array $filters = [], int $perPage = 15, bool $withTrashed = false, ?Board $board = null): Paginator
{
$currentPage = $filters['page'] ?? request()->input('page', 1);
// 목록 전용 컬럼: content(본문 HTML) 제외 → content_preview로 대체
$listColumns = [
'id', 'board_id', 'user_id', 'parent_id', 'category',
'title', 'author_name', 'content_mode',
'is_notice', 'is_secret', 'status', 'depth',
'view_count', 'comments_count', 'replies_count', 'attachments_count',
'trigger_type', 'ip_address', 'created_at', 'updated_at', 'deleted_at',
DB::raw('SUBSTRING(content, 1, 200) as content_preview_raw'),
];
// buildSortedPostList를 사용하여 페이지네이션된 목록 조회
// attachments, board 제거 — 목록에서는 has_attachment(attachments_count) 사용, board는 Controller에서 전달
return $this->buildSortedPostList(
slug: $slug,
columns: ['*'],
columns: $listColumns,
withTrashed: $withTrashed,
relations: ['user', 'attachments'],
withCount: ['comments', 'attachments', 'replies'],
relations: ['user', 'user.avatarAttachment', 'thumbnailAttachment'],
withCount: [],
filters: $filters,
perPage: $perPage,
currentPage: $currentPage
currentPage: $currentPage,
board: $board,
);
}
/**
* 쿼리에 필터를 적용합니다.
*
* @param \Illuminate\Database\Eloquent\Builder $query 쿼리 빌더
* @param Builder $query 쿼리 빌더
* @param array $filters 필터 조건
*/
private function applyFilters($query, array $filters): void
@@ -64,14 +85,17 @@ class PostRepository implements PostRepositoryInterface
$searchField = $filters['search_field'] ?? 'all';
$query->where(function ($q) use ($keyword, $searchField) {
if ($searchField === 'all' || $searchField === 'title') {
$q->orWhere('title', 'like', "%{$keyword}%");
}
if ($searchField === 'all' || $searchField === 'content') {
$q->orWhere('content', 'like', "%{$keyword}%");
// 제목+내용 검색: FULLTEXT 활용 (all, title_content)
if ($searchField === 'all' || $searchField === 'title_content') {
if (DatabaseFulltextEngine::supportsFulltext()) {
$q->orWhereRaw('MATCH(`title`, `content`) AGAINST(? IN BOOLEAN MODE)', [$keyword]);
} else {
$q->orWhere('title', 'like', "%{$keyword}%")
->orWhere('content', 'like', "%{$keyword}%");
}
}
// 작성자 검색
if ($searchField === 'all' || $searchField === 'author' || $searchField === 'author_name') {
$q->orWhere('author_name', 'like', "%{$keyword}%")
->orWhereHas('user', function ($uq) use ($keyword) {
@@ -162,7 +186,7 @@ class PostRepository implements PostRepositoryInterface
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(string $slug, int $id): Post
{
@@ -178,7 +202,7 @@ class PostRepository implements PostRepositoryInterface
* @param int $id 게시글 ID
* @param array $data 수정할 데이터
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(string $slug, int $id, array $data): Post
{
@@ -194,7 +218,7 @@ class PostRepository implements PostRepositoryInterface
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(string $slug, int $id): bool
{
@@ -209,7 +233,7 @@ class PostRepository implements PostRepositoryInterface
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function forceDelete(string $slug, int $id): bool
{
@@ -226,7 +250,7 @@ class PostRepository implements PostRepositoryInterface
* @param string $status 변경할 상태 (published/blinded/deleted)
* @param array $actionLog 작업 이력 데이터
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function updateStatus(string $slug, int $id, string $status, array $actionLog, ?string $triggerType = null): Post
{
@@ -286,7 +310,7 @@ class PostRepository implements PostRepositoryInterface
* @param array $updates 업데이트할 데이터 (status, trigger_type, deleted_at, action_log)
* @return Post 수정된 게시글
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function updateStatusBulk(string $slug, int $id, array $updates): Post
{
@@ -334,43 +358,20 @@ class PostRepository implements PostRepositoryInterface
* @param int $id 게시글 ID
* @return Post|null 게시글 모델 (카운트 포함)
*/
public function findWithCounts(string $slug, int $id): ?Post
public function findWithCounts(string $slug, int $id, ?int $boardId = null): ?Post
{
$board = Board::where('slug', $slug)->first();
$boardId = $board?->id;
// boardId가 전달되면 Board 모델 재조회 없이 직접 사용
if (! $boardId) {
$board = Board::where('slug', $slug)->first();
$boardId = $board?->id;
}
$post = Post::withTrashed()
->where('board_id', $boardId)
->with([
'user',
'comments' => function ($query) use ($slug, $boardId) {
// Eager loading에서 board_id 조건 명시적 바인딩
$query->where('board_id', $boardId);
// 삭제된 댓글은 관리자 권한(control/manage)이 있을 때만 포함
$hasDeletePermission = $this->checkBoardPermission($slug, 'admin.control')
|| $this->checkBoardPermission($slug, 'admin.manage');
if ($hasDeletePermission) {
$query->withTrashed();
}
$query->with('user')
->withCount([
'replies' => function ($q) use ($hasDeletePermission, $boardId) {
$q->where('board_id', $boardId);
// 관리자 권한이 있으면 삭제된 답글도 카운트에 포함
if ($hasDeletePermission) {
$q->withTrashed();
} else {
// 일반 사용자는 삭제되지 않은 답글만 카운트
$q->whereNull('deleted_at');
}
},
])
->orderBy('id', 'ASC');
},
'user.avatarAttachment',
'board',
'parent' => function ($query) {
$query->withTrashed()
->with('user');
@@ -379,26 +380,14 @@ class PostRepository implements PostRepositoryInterface
$query->where('board_id', $boardId);
},
])
->withCount([
'comments' => function ($query) use ($boardId) {
$query->where('board_id', $boardId);
},
'attachments' => function ($query) use ($boardId) {
$query->where('board_id', $boardId);
},
])
->find($id);
// 댓글을 트리 구조로 정렬
if ($post && $post->comments) {
$post->setRelation('comments', $this->buildCommentTree($post->comments));
}
// 모든 하위 답글을 재귀적으로 로드하여 트리 구조로 설정
if ($post) {
// 삭제된 답글은 관리자 권한(control/manage)이 있을 때만 포함
$hasDeletePermission = $this->checkBoardPermission($slug, 'admin.control')
|| $this->checkBoardPermission($slug, 'admin.manage');
// loadAllDescendantReplies는 board_id만 필요하므로 Board 모델 대신 조회된 board 사용
$board = $board ?? $post->board;
$allReplies = $this->loadAllDescendantReplies($post->id, $board, $hasDeletePermission);
$post->setRelation('replies', $allReplies);
}
@@ -406,51 +395,6 @@ class PostRepository implements PostRepositoryInterface
return $post;
}
/**
* 댓글을 트리 구조로 정렬합니다 (parent-child 그룹화).
*
* CommentRepository의 sortByParentChild 로직과 동일하게 구현합니다.
*
* @param \Illuminate\Support\Collection $comments 댓글 컬렉션
* @return \Illuminate\Support\Collection 트리 구조로 정렬된 댓글
*/
private function buildCommentTree($comments)
{
$result = [];
$grouped = $comments->groupBy('parent_id');
// parent_id가 null인 최상위 댓글들을 먼저 처리
foreach ($grouped->get(null, collect()) as $parent) {
$result[] = $parent;
// 해당 부모의 답글들을 바로 다음에 추가
$this->addRepliesRecursively($result, $grouped, $parent->id);
}
// Eloquent Collection으로 변환하여 모델 속성 유지
return $comments->make($result);
}
/**
* 재귀적으로 답글들을 결과 배열에 추가합니다.
*
* @param array &$result 결과 배열 (참조)
* @param \Illuminate\Support\Collection $grouped parent_id로 그룹화된 댓글 컬렉션
* @param int $parentId 부모 댓글 ID
*/
private function addRepliesRecursively(array &$result, $grouped, int $parentId): void
{
// 해당 parent_id를 가진 답글들 가져오기
$replies = $grouped->get($parentId, collect());
foreach ($replies as $reply) {
$result[] = $reply;
// 답글의 답글도 재귀적으로 추가
$this->addRepliesRecursively($result, $grouped, $reply->id);
}
}
/**
* 특정 게시글의 모든 하위 답글을 재귀적으로 로드합니다.
*
@@ -472,15 +416,7 @@ class PostRepository implements PostRepositoryInterface
$query = Post::query()
->whereIn('parent_id', $parentIds)
->when($board, fn ($q) => $q->where('board_id', $board->id))
->with('user')
->withCount([
'comments' => function ($q) use ($board) {
$q->where('board_id', $board?->id);
},
'attachments' => function ($q) use ($board) {
$q->where('board_id', $board?->id);
},
]);
->with('user');
if ($withTrashed) {
$query->withTrashed();
@@ -555,34 +491,148 @@ class PostRepository implements PostRepositoryInterface
* @param bool $withTrashed 삭제된 게시글 포함 여부 (기본: false)
* @return array{prev: Post|null, next: Post|null} 이전/다음 게시글
*/
public function getAdjacentPosts(string $slug, int $id, array $filters = [], bool $withTrashed = false): array
public function getAdjacentPosts(string $slug, int $id, array $filters = [], bool $withTrashed = false, ?int $boardId = null): array
{
// 목록 정렬 로직을 재사용하여 전체 게시글 리스트 생성
// withTrashed=false이면 블라인드/삭제된 게시글 제외
$allItems = $this->buildSortedPostList(
slug: $slug,
columns: ['id', 'title', 'parent_id', 'is_notice', 'status'],
withTrashed: $withTrashed,
filters: $filters
);
// boardId가 전달되면 Board 모델 재조회 없이 직접 사용
if (! $boardId) {
$board = Board::where('slug', $slug)->first();
if (! $board) {
return ['prev' => null, 'next' => null];
}
$boardId = $board->id;
}
// 현재 게시글의 위치 찾기
$currentIndex = $allItems->search(function ($item) use ($id) {
return $item->id === $id;
});
$category = $filters['category'] ?? null;
$orderBy = $filters['order_by'] ?? 'id';
$orderDirection = $filters['order_direction'] ?? 'desc';
if ($currentIndex === false) {
// Enum 객체를 문자열로 변환 (buildSortedPostList와 동일 패턴)
if ($orderBy instanceof \BackedEnum) {
$orderBy = $orderBy->value;
}
if ($orderDirection instanceof \BackedEnum) {
$orderDirection = $orderDirection->value;
}
// Enum 값 → 실제 DB 컬럼 매핑 (author → author_name)
$columnMapping = [
'author' => 'author_name',
];
if (isset($columnMapping[$orderBy])) {
$orderBy = $columnMapping[$orderBy];
}
// 허용된 정렬 컬럼 화이트리스트 (SQL 인젝션 방지)
$allowedColumns = ['id', 'view_count', 'created_at', 'title', 'author_name'];
if (! in_array($orderBy, $allowedColumns)) {
$orderBy = 'id';
}
$orderDirection = in_array(strtolower($orderDirection), ['asc', 'desc']) ? strtolower($orderDirection) : 'desc';
$currentPost = Post::find($id, [$orderBy, 'id']);
if ($currentPost === null) {
return ['prev' => null, 'next' => null];
}
// 이전/다음 게시글 반환
$prev = $currentIndex > 0 ? $allItems->get($currentIndex - 1) : null;
$next = $currentIndex < $allItems->count() - 1 ? $allItems->get($currentIndex + 1) : null;
$currentValue = $currentPost->{$orderBy};
return [
'prev' => $prev,
'next' => $next,
];
// 기본 조건: 공지 제외, 원글만, 게시 상태
$baseQuery = fn () => Post::query()
->where('board_id', $boardId)
->where('is_notice', false)
->whereNull('parent_id')
->where('status', PostStatus::Published->value)
->when(! $withTrashed, fn ($q) => $q->whereNull('deleted_at'))
->when($category, fn ($q) => $q->where('category', $category))
->select(['id', 'title']);
// 이전/다음 글 조회 (2단계: strict 비교 → tie-breaking)
// OR 조건은 MySQL 옵티마이저가 인덱스를 사용하지 못하므로
// strict 비교(< or >)를 먼저 시도하고, 결과가 없으면 동일 값 tie-breaking 쿼리 실행
$prev = $this->findAdjacentPost(
$baseQuery, $orderBy, $orderDirection, $currentValue, $id, 'prev'
);
$next = $this->findAdjacentPost(
$baseQuery, $orderBy, $orderDirection, $currentValue, $id, 'next'
);
return ['prev' => $prev, 'next' => $next];
}
/**
* 이전 또는 다음 게시글을 조회합니다. (인덱스 최적화)
*
* OR 조건은 MySQL 옵티마이저가 인덱스를 사용하지 못하므로,
* strict 비교를 먼저 시도하고 결과가 없으면 동일 값 tie-breaking 쿼리를 실행합니다.
*
* @param \Closure $baseQuery 기본 쿼리 팩토리
* @param string $orderBy 정렬 컬럼
* @param string $orderDirection 정렬 방향 (asc/desc)
* @param mixed $currentValue 현재 게시글의 정렬 값
* @param int $id 현재 게시글 ID
* @param string $direction 조회 방향 (prev/next)
* @return Post|null 이전/다음 게시글
*/
private function findAdjacentPost(\Closure $baseQuery, string $orderBy, string $orderDirection, mixed $currentValue, int $id, string $direction): ?Post
{
$isPrev = $direction === 'prev';
// prev: 정렬 기준으로 현재 글보다 앞 → desc면 >, asc면 <
// next: 정렬 기준으로 현재 글보다 뒤 → desc면 <, asc면 >
$strictOp = match (true) {
$isPrev && $orderDirection === 'desc' => '>',
$isPrev && $orderDirection === 'asc' => '<',
! $isPrev && $orderDirection === 'desc' => '<',
default => '>',
};
$sortDir = $isPrev
? ($orderDirection === 'desc' ? 'asc' : 'desc')
: $orderDirection;
// DESC 정렬: 목록은 ORDER BY col DESC, id DESC
// prev(위쪽) = 같은 값 내에서 id > current → idOp='>', idSort='asc'(가장 가까운 것)
// next(아래쪽) = 같은 값 내에서 id < current → idOp='<', idSort='desc'(가장 가까운 것)
// ASC 정렬: 목록은 ORDER BY col ASC, id ASC
// prev(위쪽) = 같은 값 내에서 id < current → idOp='<', idSort='desc'
// next(아래쪽) = 같은 값 내에서 id > current → idOp='>', idSort='asc'
$idOp = ($isPrev xor $orderDirection === 'asc') ? '>' : '<';
$idSort = $idOp === '>' ? 'asc' : 'desc';
// 1단계: 동일 정렬 값 내 tie-breaking (id 비교)
// 동일 값 내의 글이 정렬상 더 가까우므로 먼저 확인
$tieQuery = $baseQuery()
->where($orderBy, $currentValue)
->where('id', $idOp, $id)
->orderBy('id', $idSort);
$result = $tieQuery->first();
if ($result) {
return $result;
}
// 2단계: 동일 값 내에 없으면 다른 정렬 값으로 이동
if ($orderBy === 'created_at') {
// created_at: 서브쿼리 MAX/MIN으로 정확한 값을 먼저 찾고 등호 조회
// → 콜드 스타트(버퍼 풀 미적재)에서도 ~2ms (range scan 대비 100배 이상 빠름)
$aggregateFunc = $strictOp === '<' ? 'MAX' : 'MIN';
$subQuery = $baseQuery()
->select(DB::raw("{$aggregateFunc}(`{$orderBy}`)"))
->where($orderBy, $strictOp, $currentValue);
return $baseQuery()
->where($orderBy, DB::raw("({$subQuery->toSql()})"))
->mergeBindings($subQuery->getQuery())
->orderBy('id', $idSort)
->first();
}
// 그 외 컬럼: strict 비교 (인덱스 range scan)
return $baseQuery()
->where($orderBy, $strictOp, $currentValue)
->orderBy($orderBy, $sortDir)
->orderBy('id', $idSort)
->first();
}
/**
@@ -597,7 +647,7 @@ class PostRepository implements PostRepositoryInterface
* @param array $filters 필터 조건 (검색, 상태, 분류 등)
* @param int|null $perPage 페이지당 원글 수 (null이면 전체 조회)
* @param int $currentPage 현재 페이지 번호
* @return \Illuminate\Support\Collection|\Illuminate\Pagination\LengthAwarePaginator 정렬된 게시글 컬렉션 또는 페이지네이터
* @return Collection|LengthAwarePaginator 정렬된 게시글 컬렉션 또는 페이지네이터
*/
private function buildSortedPostList(
string $slug,
@@ -607,35 +657,19 @@ class PostRepository implements PostRepositoryInterface
array $withCount = [],
array $filters = [],
?int $perPage = null,
int $currentPage = 1
int $currentPage = 1,
?Board $board = null
) {
$board = Board::where('slug', $slug)->first();
// board가 전달되지 않은 경우에만 DB 조회 (하위 호환 유지)
if (! $board) {
$board = Board::where('slug', $slug)->first();
}
$boardId = $board?->id;
// Eager loading(with)의 관계에 board_id 조건을 명시적으로 바인딩
// (모델 관계 정의에서 $this->board_id를 사용하면 Eager loading 시 null이 되는 문제 해결)
$relations = $this->bindBoardIdToRelations($relations, $boardId);
// withCount의 comments/replies에도 board_id 조건을 명시적으로 바인딩
if (in_array('comments', $withCount)) {
unset($withCount[array_search('comments', $withCount)]);
$withCount['comments'] = function ($query) use ($boardId) {
$query->where('board_id', $boardId);
};
}
if (in_array('replies', $withCount)) {
unset($withCount[array_search('replies', $withCount)]);
$withCount['replies'] = function ($query) use ($boardId) {
$query->where('board_id', $boardId);
};
}
if (in_array('attachments', $withCount)) {
unset($withCount[array_search('attachments', $withCount)]);
$withCount['attachments'] = function ($query) use ($boardId) {
$query->where('board_id', $boardId);
};
}
// 권한 스코프 필터링용 permission identifier (Service에서 컨텍스트 기반으로 전달)
$postPermission = $filters['scope_permission'] ?? "sirsoft-board.{$slug}.admin.posts.read";
unset($filters['scope_permission']);
@@ -662,9 +696,6 @@ class PostRepository implements PostRepositoryInterface
if (! empty($relations)) {
$noticeQuery->with($relations);
}
if (! empty($withCount)) {
$noticeQuery->withCount($withCount);
}
$notices = $noticeQuery->get($columns);
}
@@ -721,20 +752,19 @@ class PostRepository implements PostRepositoryInterface
$orderDirection = 'desc'; // 기본값으로 폴백
}
// 정렬 적용
$parentQuery->orderBy($orderBy, $orderDirection);
// 정렬 적용 (id를 2차 정렬로 추가 — 동일 값 내 순서를 결정론적으로 보장)
// created_at은 초 단위라 실질적 중복이 드물지만, view_count/title/author_name은 중복이 많음
$parentQuery->orderBy($orderBy, $orderDirection)->orderBy('id', $orderDirection);
if (! empty($relations)) {
$parentQuery->with($relations);
}
if (! empty($withCount)) {
$parentQuery->withCount($withCount);
}
// 페이지네이션 여부에 따라 분기
if ($perPage !== null) {
// 페이지네이션 사용
$paginator = $parentQuery->paginate($perPage, $columns, 'page', $currentPage);
// simplePaginate 사용 — COUNT(*) 쿼리 제거로 대량 데이터 성능 개선
// total은 Service 캐시 카운트로 별도 제공
$paginator = $parentQuery->simplePaginate($perPage, $columns, 'page', $currentPage);
$parents = $paginator->getCollection();
} else {
// 전체 조회
@@ -764,9 +794,6 @@ class PostRepository implements PostRepositoryInterface
if (! empty($relations)) {
$levelQuery->with($relations);
}
if (! empty($withCount)) {
$levelQuery->withCount($withCount);
}
$levelReplies = $levelQuery->get($columns);
@@ -821,27 +848,31 @@ class PostRepository implements PostRepositoryInterface
*/
public function getUserActivityStats(int $userId): array
{
// 단일 테이블 단일 쿼리
$totalPosts = Post::where('user_id', $userId)->count();
// 비활성 게시판 제외
$inactiveBoardIds = $this->getInactiveBoardIds();
// 삭제된 게시글·비활성 게시판의 댓글 제외 (목록 API와 동일 기준)
$totalComments = (int) Comment::where('board_comments.user_id', $userId)
->join('board_posts', function ($join) {
$join->on('board_posts.id', '=', 'board_comments.post_id')
->whereNull('board_posts.deleted_at');
})
->join('boards', function ($join) {
$join->on('boards.id', '=', 'board_comments.board_id')
->where('boards.is_active', true);
})
->count();
// 쿼리 1: COUNT — idx_board_posts_user_activity 커버링 (Using index)
$postsQuery = Post::where('user_id', $userId);
if (! empty($inactiveBoardIds)) {
$postsQuery->whereNotIn('board_id', $inactiveBoardIds);
}
$totalPosts = $postsQuery->count();
$totalViews = (int) Post::where('user_id', $userId)->sum('view_count');
// 쿼리 2: SUM(comments_count) + SUM(view_count) — idx_board_posts_user_board_stats 커버링
// withTrashed: deleted_at 조건 제거로 커버링 인덱스(Using index) 활용 → 테이블 접근 없음
// comments_count는 PostCountSyncListener가 정확히 동기화하므로 SUM으로 대체 (JOIN 제거)
// 삭제 게시글 포함해도 실질적 차이 미미 (33건/5,632건)
$statsQuery = Post::withTrashed()->where('user_id', $userId);
if (! empty($inactiveBoardIds)) {
$statsQuery->whereNotIn('board_id', $inactiveBoardIds);
}
$sums = $statsQuery->selectRaw('COALESCE(SUM(comments_count), 0) as total_comments, COALESCE(SUM(view_count), 0) as total_views')
->first();
return [
'total_posts' => $totalPosts,
'total_comments' => $totalComments,
'total_views' => $totalViews,
'total_comments' => (int) $sums->total_comments,
'total_views' => (int) $sums->total_views,
];
}
@@ -911,12 +942,14 @@ class PostRepository implements PostRepositoryInterface
};
$orderDirection = $sort === 'oldest' ? 'asc' : 'desc';
$cachedTotal = $filters['cached_total'] ?? null;
if ($activityType === 'commented' && ! $isPublic) {
return $this->getUserCommentedActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $orderColumn, $orderDirection, $perPage);
return $this->getUserCommentedActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $orderColumn, $orderDirection, $perPage, $cachedTotal);
}
// authored (기본값, 공개 프로필 포함)
return $this->getUserAuthoredActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $isPublic, $orderColumn, $orderDirection, $perPage);
return $this->getUserAuthoredActivities($userId, $boardIdFilter, $excludeBoardIds, $search, $isPublic, $orderColumn, $orderDirection, $perPage, $cachedTotal);
}
/**
@@ -929,7 +962,6 @@ class PostRepository implements PostRepositoryInterface
* @param string $orderColumn 정렬 컬럼
* @param string $orderDirection 정렬 방향
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator
*/
private function getUserAuthoredActivities(
int $userId,
@@ -939,24 +971,24 @@ class PostRepository implements PostRepositoryInterface
bool $isPublic,
string $orderColumn,
string $orderDirection,
int $perPage
int $perPage,
?int $cachedTotal = null
): LengthAwarePaginator {
// JOIN 대신 whereNotIn으로 비활성 게시판 제외 — idx_board_posts_user_created 인덱스 활용
$inactiveBoardIds = $this->getInactiveBoardIds();
$allExcludeIds = array_unique(array_merge($excludeBoardIds, $inactiveBoardIds));
$query = Post::query()
->join('boards', function ($join) {
$join->on('boards.id', '=', 'board_posts.board_id')
->where('boards.is_active', true);
})
->where('board_posts.user_id', $userId)
->with('board')
->withCount('comments')
->orderBy($orderColumn, $orderDirection);
if ($boardIdFilter) {
$query->where('board_posts.board_id', $boardIdFilter);
}
if (! empty($excludeBoardIds)) {
$query->whereNotIn('board_posts.board_id', $excludeBoardIds);
if (! empty($allExcludeIds)) {
$query->whereNotIn('board_posts.board_id', $allExcludeIds);
}
if ($isPublic) {
@@ -972,24 +1004,24 @@ class PostRepository implements PostRepositoryInterface
});
}
$paginator = $query->paginate($perPage);
$paginator = $query->paginate($perPage, ['*'], 'page', null, $cachedTotal);
// paginate 후 10건에만 PHP 가공 적용 (N+1 아님)
$paginator->through(function ($post) {
return [
'id' => $post->id,
'board_slug' => $post->board?->slug,
'board_name' => $post->board?->getLocalizedName() ?? '',
'activity_type' => 'authored',
'activity_count' => 0,
'title' => $post->title,
'is_secret' => (bool) $post->is_secret,
'status' => $post->status?->value,
'view_count' => $post->view_count,
'comments_count' => (int) ($post->comments_count ?? 0),
'created_at' => $this->formatCreatedAt($post->created_at),
'id' => $post->id,
'board_slug' => $post->board?->slug,
'board_name' => $post->board?->getLocalizedName() ?? '',
'activity_type' => 'authored',
'activity_count' => 0,
'title' => $post->title,
'is_secret' => (bool) $post->is_secret,
'status' => $post->status?->value,
'view_count' => $post->view_count,
'comments_count' => (int) ($post->comments_count ?? 0),
'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')),
'content_plain' => ($post->content_mode ?? 'text') === 'html'
'content_plain' => ($post->content_mode ?? 'text') === 'html'
? $this->stripHtmlToPlainText($post->content ?? '')
: ($post->content ?? ''),
];
@@ -1008,7 +1040,6 @@ class PostRepository implements PostRepositoryInterface
* @param string $orderColumn 정렬 컬럼
* @param string $orderDirection 정렬 방향
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator
*/
private function getUserCommentedActivities(
int $userId,
@@ -1017,16 +1048,18 @@ class PostRepository implements PostRepositoryInterface
?string $search,
string $orderColumn,
string $orderDirection,
int $perPage
int $perPage,
?int $cachedTotal = null
): LengthAwarePaginator {
// DB::raw() / whereRaw() 내부 raw SQL은 prefix 자동 적용이 안 되므로 명시적으로 처리
// DB::raw()를 from()/join()에 사용하면 테이블명 prefix 자동 추가를 우회할 수 있음
// 단, ->where() / ->whereNull() 은 컬럼명 앞 테이블명에도 prefix를 붙이므로
// alias 참조는 반드시 whereRaw()로 처리해야 함
$prefix = DB::getTablePrefix();
$commentsTable = $prefix.'board_comments';
$postsTable = $prefix.'board_posts';
// 비활성 게시판 제외 — JOIN 없이 인덱스 활용
$inactiveBoardIds = $this->getInactiveBoardIds();
$allExcludeIds = array_unique(array_merge($excludeBoardIds, $inactiveBoardIds));
$latestCommentSub = DB::table(DB::raw("{$commentsTable} as bc_outer"))
->selectRaw('bc_outer.post_id, bc_outer.content, bc_outer.created_at')
->whereRaw("bc_outer.id = (
@@ -1048,20 +1081,20 @@ class PostRepository implements PostRepositoryInterface
->select([
'board_posts.*',
DB::raw('COUNT(DISTINCT uc.id) as activity_count'),
DB::raw("(SELECT COUNT(*) FROM {$commentsTable} ac WHERE ac.post_id = {$postsTable}.id AND ac.deleted_at IS NULL) as comments_count"),
'board_posts.comments_count',
'lc.content as comment_content',
'lc.created_at as comment_created_at',
])
->with('board')
->groupBy('board_posts.id', 'board_posts.board_id', 'lc.content', 'lc.created_at')
->groupBy('board_posts.id', 'board_posts.board_id', 'board_posts.comments_count', 'lc.content', 'lc.created_at')
->orderBy($orderColumn, $orderDirection);
if ($boardIdFilter) {
$query->where('board_posts.board_id', $boardIdFilter);
}
if (! empty($excludeBoardIds)) {
$query->whereNotIn('board_posts.board_id', $excludeBoardIds);
if (! empty($allExcludeIds)) {
$query->whereNotIn('board_posts.board_id', $allExcludeIds);
}
if ($search) {
@@ -1069,24 +1102,24 @@ class PostRepository implements PostRepositoryInterface
$query->where('uc.content', 'like', "%{$keyword}%");
}
$paginator = $query->paginate($perPage);
$paginator = $query->paginate($perPage, ['*'], 'page', null, $cachedTotal);
// paginate 후 10건에만 PHP 가공 적용
$paginator->through(function ($post) {
return [
'id' => $post->id,
'board_slug' => $post->board?->slug,
'board_name' => $post->board?->getLocalizedName() ?? '',
'activity_type' => 'commented',
'activity_count' => (int) ($post->activity_count ?? 0),
'title' => $post->title,
'is_secret' => (bool) $post->is_secret,
'status' => $post->status?->value,
'view_count' => $post->view_count,
'comments_count' => (int) ($post->comments_count ?? 0),
'created_at' => $this->formatCreatedAt($post->created_at),
'id' => $post->id,
'board_slug' => $post->board?->slug,
'board_name' => $post->board?->getLocalizedName() ?? '',
'activity_type' => 'commented',
'activity_count' => (int) ($post->activity_count ?? 0),
'title' => $post->title,
'is_secret' => (bool) $post->is_secret,
'status' => $post->status?->value,
'view_count' => $post->view_count,
'comments_count' => (int) ($post->comments_count ?? 0),
'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')),
'content_plain' => ($post->content_mode ?? 'text') === 'html'
'content_plain' => ($post->content_mode ?? 'text') === 'html'
? $this->stripHtmlToPlainText($post->content ?? '')
: ($post->content ?? ''),
];
@@ -1112,13 +1145,7 @@ class PostRepository implements PostRepositoryInterface
$query = $this->buildPublicSearchQuery($slug, $keyword);
$total = $query->count();
$board = Board::where('slug', $slug)->first();
$items = $query->with('user')
->withCount([
'comments' => function ($q) use ($board) {
$q->where('board_id', $board?->id);
},
])
->orderBy($orderBy, $direction)
->limit($limit)
->get();
@@ -1159,7 +1186,6 @@ class PostRepository implements PostRepositoryInterface
$items = (clone $query)
->with('user', 'board')
->withCount('comments')
->orderBy($orderBy, $direction)
->forPage($page, $perPage)
->get();
@@ -1175,7 +1201,6 @@ class PostRepository implements PostRepositoryInterface
*
* @param array $boardIds 검색 대상 게시판 ID 목록
* @param string $keyword 검색 키워드
* @return int
*/
public function countAcrossBoards(array $boardIds, string $keyword): int
{
@@ -1187,21 +1212,20 @@ class PostRepository implements PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param string $keyword 검색 키워드
* @return \Illuminate\Database\Eloquent\Builder
* @return Builder
*/
private function buildPublicSearchQuery(string $slug, string $keyword)
{
$board = Board::where('slug', $slug)->first();
$escapedKeyword = $this->escapeLikeKeyword($keyword);
return Post::query()
$query = Post::query()
->where('board_id', $board?->id)
->where('status', \Modules\Sirsoft\Board\Enums\PostStatus::Published->value)
->where('is_secret', false)
->where(function ($q) use ($escapedKeyword) {
$q->where('title', 'like', "%{$escapedKeyword}%")
->orWhere('content', 'like', "%{$escapedKeyword}%");
});
->where('status', PostStatus::Published->value)
->where('is_secret', false);
$this->applyKeywordSearch($query, $keyword);
return $query;
}
/**
@@ -1209,20 +1233,39 @@ class PostRepository implements PostRepositoryInterface
*
* @param array $boardIds 게시판 ID 목록
* @param string $keyword 검색 키워드
* @return \Illuminate\Database\Eloquent\Builder
* @return Builder
*/
private function buildPublicSearchQueryByIds(array $boardIds, string $keyword)
{
$escapedKeyword = $this->escapeLikeKeyword($keyword);
return Post::query()
$query = Post::query()
->whereIn('board_id', $boardIds)
->where('status', \Modules\Sirsoft\Board\Enums\PostStatus::Published->value)
->where('is_secret', false)
->where(function ($q) use ($escapedKeyword) {
->where('status', PostStatus::Published->value)
->where('is_secret', false);
$this->applyKeywordSearch($query, $keyword);
return $query;
}
/**
* 키워드 검색 조건을 쿼리에 적용합니다.
*
* FULLTEXT 인덱스가 지원되면 MATCH...AGAINST를, 아니면 LIKE fallback을 사용합니다.
*
* @param Builder $query 쿼리 빌더
* @param string $keyword 검색 키워드
*/
private function applyKeywordSearch(Builder $query, string $keyword): void
{
if (DatabaseFulltextEngine::supportsFulltext()) {
$query->whereRaw('MATCH(`title`, `content`) AGAINST(? IN BOOLEAN MODE)', [$keyword]);
} else {
$escapedKeyword = $this->escapeLikeKeyword($keyword);
$query->where(function ($q) use ($escapedKeyword) {
$q->where('title', 'like', "%{$escapedKeyword}%")
->orWhere('content', 'like', "%{$escapedKeyword}%");
});
}
}
/**
@@ -1369,4 +1412,17 @@ class PostRepository implements PostRepositoryInterface
->oldest()
->first();
}
/**
* 비활성 게시판 ID 목록을 조회합니다.
*
* boards 테이블은 소규모(~수십 건)이므로 단순 쿼리로 충분합니다.
* JOIN 대신 whereNotIn 패턴에 사용하여 board_posts 인덱스 활용을 유도합니다.
*
* @return array<int> 비활성 게시판 ID 배열
*/
private function getInactiveBoardIds(): array
{
return Board::where('is_active', false)->pluck('id')->all();
}
}