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

@@ -1,86 +0,0 @@
<?php
namespace Modules\Sirsoft\Board\Repositories;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Modules\Sirsoft\Board\Models\BoardMailTemplate;
use Modules\Sirsoft\Board\Repositories\Contracts\BoardMailTemplateRepositoryInterface;
/**
* 게시판 메일 템플릿 리포지토리 구현체
*/
class BoardMailTemplateRepository implements BoardMailTemplateRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function findById(int $id): ?BoardMailTemplate
{
return BoardMailTemplate::find($id);
}
/**
* {@inheritdoc}
*/
public function findByType(string $type): ?BoardMailTemplate
{
return BoardMailTemplate::where('type', $type)->first();
}
/**
* {@inheritdoc}
*/
public function getActiveByType(string $type): ?BoardMailTemplate
{
return BoardMailTemplate::active()->byType($type)->first();
}
/**
* {@inheritdoc}
*/
public function getAllTemplates(): Collection
{
return BoardMailTemplate::orderBy('id')->get();
}
/**
* {@inheritdoc}
*/
public function update(BoardMailTemplate $template, array $data): bool
{
return $template->update($data);
}
/**
* {@inheritdoc}
*/
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator
{
$sortBy = $filters['sort_by'] ?? 'id';
$sortOrder = $filters['sort_order'] ?? 'asc';
$query = BoardMailTemplate::query()->orderBy($sortBy, $sortOrder);
if (! empty($filters['search'])) {
$search = $filters['search'];
$searchType = $filters['search_type'] ?? 'all';
$query->where(function ($q) use ($search, $searchType) {
$locales = config('app.supported_locales', ['ko', 'en']);
if ($searchType === 'subject' || $searchType === 'all') {
foreach ($locales as $locale) {
$q->orWhere("subject->{$locale}", 'like', "%{$search}%");
}
}
if ($searchType === 'body' || $searchType === 'all') {
foreach ($locales as $locale) {
$q->orWhere("body->{$locale}", 'like', "%{$search}%");
}
}
});
}
return $query->paginate($perPage);
}
}
@@ -202,30 +202,37 @@ class BoardRepository implements BoardRepositoryInterface
return [];
}
// 댓글 수 서브쿼리
$commentCountSubquery = Comment::query()
->selectRaw('COUNT(*)')
->whereColumn('board_comments.post_id', 'board_posts.id')
->whereNull('board_comments.deleted_at');
$columns = ['id', 'board_id', 'title', 'author_name', 'created_at', 'view_count', 'is_secret', 'comments_count'];
// board_id IN (...) + ORDER BY created_at DESC → 풀스캔 방지
// 각 board_id별 개별 쿼리(인덱스 활용) 후 UNION ALL로 합침
$subQueries = $activeBoardIds->map(
fn ($boardId) => Post::query()
->select($columns)
->where('board_id', $boardId)
->whereNull('deleted_at')
->whereNull('parent_id')
->where('status', 'published')
->orderBy('created_at', 'desc')
->limit($limit)
);
$unionQuery = $subQueries->shift();
foreach ($subQueries as $sub) {
$unionQuery = $unionQuery->unionAll($sub);
}
$postIds = DB::query()
->fromSub($unionQuery, 'sub')
->orderBy('created_at', 'desc')
->limit($limit)
->pluck('id');
$posts = Post::query()
->with('board:id,slug,name')
->select([
'id',
'board_id',
'title',
'author_name',
'created_at',
'view_count',
'is_secret',
])
->selectSub($commentCountSubquery, 'comment_count')
->whereIn('board_id', $activeBoardIds)
->whereNull('deleted_at')
->whereNull('parent_id')
->where('status', 'published')
->select($columns)
->whereIn('id', $postIds)
->orderBy('created_at', 'desc')
->limit($limit)
->get();
$newHours = g7_module_settings('sirsoft-board', 'basic_defaults.new_display_hours', 24);
@@ -239,7 +246,7 @@ class BoardRepository implements BoardRepositoryInterface
'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->comment_count ?? 0,
'comment_count' => $post->comments_count ?? 0,
'is_secret' => (bool) $post->is_secret,
'is_new' => $post->created_at && $post->created_at->diffInHours(now()) < $newHours,
])->toArray();
@@ -262,12 +269,6 @@ class BoardRepository implements BoardRepositoryInterface
return [];
}
// 댓글 수 서브쿼리
$commentCountSubquery = Comment::query()
->selectRaw('COUNT(*)')
->whereColumn('board_comments.post_id', 'board_posts.id')
->whereNull('board_comments.deleted_at');
$posts = Post::query()
->select([
'id',
@@ -278,8 +279,8 @@ class BoardRepository implements BoardRepositoryInterface
'category',
'is_notice',
'is_secret',
'comments_count',
])
->selectSub($commentCountSubquery, 'comment_count')
->where('board_id', $board->id)
->whereNull('deleted_at')
->whereNull('parent_id')
@@ -297,7 +298,53 @@ class BoardRepository implements BoardRepositoryInterface
'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->comment_count ?? 0,
'comment_count' => $post->comments_count ?? 0,
'category' => $post->category,
'is_notice' => $post->is_notice,
'is_secret' => (bool) $post->is_secret,
'is_new' => $post->created_at && $post->created_at->diffInHours(now()) < $newHours,
])->toArray();
}
/**
* 게시판 ID로 최근 게시물을 조회합니다 (slug 재조회 없음).
*
* @param int $boardId 게시판 ID
* @param int $limit 조회 개수
* @return array<int, array<string, mixed>>
*/
public function getBoardRecentPostsById(int $boardId, int $limit): array
{
$posts = Post::query()
->select([
'id',
'title',
'author_name',
'created_at',
'view_count',
'category',
'is_notice',
'is_secret',
'comments_count',
])
->where('board_id', $boardId)
->whereNull('deleted_at')
->whereNull('parent_id')
->where('status', 'published')
->orderBy('created_at', 'desc')
->limit($limit)
->get();
$newHours = g7_module_settings('sirsoft-board', 'basic_defaults.new_display_hours', 24);
return $posts->map(fn ($post) => [
'id' => $post->id,
'title' => $post->title,
'author_name' => $post->author_name,
'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,
'category' => $post->category,
'is_notice' => $post->is_notice,
'is_secret' => (bool) $post->is_secret,
@@ -334,12 +381,7 @@ class BoardRepository implements BoardRepositoryInterface
*/
public function getTotalPostsCount(): int
{
$activeBoardIds = Board::where('is_active', true)->pluck('id');
return Post::query()
->whereIn('board_id', $activeBoardIds)
->whereNull('deleted_at')
->count();
return (int) Board::where('is_active', true)->sum('posts_count');
}
/**
@@ -360,15 +402,16 @@ class BoardRepository implements BoardRepositoryInterface
}
/**
* 인기 게시글을 조회합니다. (인기도 점수 기준, 기간별 필터링)
* 인기 게시글을 조회합니다. (조회수 > 댓글 수 기준, 기간별 필터링)
*
* board_posts 단일 테이블에서 활성 게시판의 인기 게시글을 조회합니다.
* - 인기도 점수 = 조회수 + (댓글 수 × 5) 기준 내림차순 정렬
* - 기간별 필터링 (today, week, month, all)
* - author nested 객체 구조
* - comment_count 서브쿼리 집계
* - 정렬: 조회수 내림차순, 동일 조회수 시 댓글 수 내림차순
* - 기간별 필터링 (today, week, month, year)
* - idx_board_posts_board_status_created 인덱스로 기간 범위를 먼저 좁힌 후 filesort
* - today/week: 수천 건 이내로 1회차부터 빠름
* - month/year: 수만 건 이상이나 캐시(getCachedPopularPosts)가 커버
*
* @param string $period 기간 필터 (today, week, month, all)
* @param string $period 기간 필터 (today, week, month, year)
* @param int $limit 조회 개수
* @return array<int, array<string, mixed>>
*/
@@ -385,15 +428,10 @@ class BoardRepository implements BoardRepositoryInterface
'today' => now()->startOfDay(),
'week' => now()->subWeek(),
'month' => now()->subMonth(),
default => null,
'year' => now()->subYear(),
default => now()->subYear(),
};
// 댓글 수 서브쿼리
$commentCountSubquery = Comment::query()
->selectRaw('COUNT(*)')
->whereColumn('board_comments.post_id', 'board_posts.id')
->whereNull('board_comments.deleted_at');
$prefix = DB::getTablePrefix();
$query = Post::query()
@@ -408,7 +446,7 @@ class BoardRepository implements BoardRepositoryInterface
'board_posts.id',
'board_posts.board_id',
'board_posts.title',
DB::raw("LEFT({$prefix}board_posts.content, 300) as content_raw"),
DB::raw("LEFT(`{$prefix}board_posts`.`content`, 300) as content_raw"),
'board_posts.user_id',
'board_posts.author_name as guest_author_name',
'users.name as user_name',
@@ -416,27 +454,25 @@ class BoardRepository implements BoardRepositoryInterface
'users.status as user_status',
'attachments.hash as attachment_hash',
'board_posts.view_count',
'board_posts.comments_count',
'board_posts.created_at',
])
->selectSub($commentCountSubquery, 'comment_count')
->whereIn('board_posts.board_id', $activeBoardIds)
->whereNull('board_posts.deleted_at')
->whereNull('board_posts.parent_id')
->where('board_posts.status', 'published')
->where('board_posts.is_secret', false);
if ($dateFilter) {
$query->where('board_posts.created_at', '>=', $dateFilter);
}
->where('board_posts.is_secret', false)
->where('board_posts.created_at', '>=', $dateFilter);
$posts = $query
->orderByRaw("({$prefix}board_posts.view_count + (comment_count * 5)) DESC")
->orderBy('board_posts.view_count', 'desc')
->orderBy('board_posts.comments_count', 'desc')
->limit($limit)
->get();
return $posts->map(function ($post) {
$viewCount = $post->view_count ?? 0;
$commentCount = $post->comment_count ?? 0;
$commentCount = $post->comments_count ?? 0;
// Avatar URL 결정
$avatarUrl = null;
@@ -563,6 +599,35 @@ class BoardRepository implements BoardRepositoryInterface
->get();
}
/**
* 활성 게시판의 통계를 조회합니다 (게시판 수, 게시글 수, 댓글 수).
*
* boards 테이블의 카운팅 컬럼을 SUM하여 단일 쿼리로 집계합니다.
*
* @return object{boards_count: int, posts_total: int, comments_total: int}
*/
public function getActiveBoardStats(): object
{
return Board::where('is_active', true)
->selectRaw('COUNT(*) as boards_count, COALESCE(SUM(posts_count), 0) as posts_total, COALESCE(SUM(comments_count), 0) as comments_total')
->first();
}
/**
* 메뉴용 경량 게시판 목록을 조회합니다.
*
* id, name, slug 컬럼만 조회하여 메뉴 렌더링에 필요한 최소 데이터만 반환합니다.
*
* @return \Illuminate\Database\Eloquent\Collection 활성 게시판 컬렉션 (id, name, slug만 포함)
*/
public function getActiveBoardsForMenu(): \Illuminate\Database\Eloquent\Collection
{
return Board::where('is_active', true)
->select(['id', 'name', 'slug'])
->orderBy('created_at', 'asc')
->get();
}
/**
* 특정 유형의 게시판 개수를 반환합니다.
*
@@ -3,9 +3,10 @@
namespace Modules\Sirsoft\Board\Repositories;
use App\Helpers\PermissionHelper;
use App\Helpers\TimezoneHelper;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Comment;
use Modules\Sirsoft\Board\Repositories\Contracts\CommentRepositoryInterface;
@@ -29,23 +30,17 @@ class CommentRepository implements CommentRepositoryInterface
* @param string $orderDirection 정렬 방향 (ASC 또는 DESC, 기본값: DESC)
* @return Collection 부모-자식 관계로 정렬된 댓글 컬렉션
*/
public function getByPostId(string $slug, int $postId, bool $withTrashed = false, string $orderDirection = 'DESC', ?string $scopePermission = null): Collection
public function getByPostId(string $slug, int $postId, bool $withTrashed = false, string $orderDirection = 'DESC', ?string $scopePermission = null, ?int $boardId = null): Collection
{
$board = Board::where('slug', $slug)->first();
// boardId가 전달되면 Board 모델 재조회 없이 직접 사용
$resolvedBoardId = $boardId ?? Board::where('slug', $slug)->first()?->id;
// 정렬 방향 정규화 (대소문자 무관하게 처리)
$orderDirection = strtoupper($orderDirection) === 'ASC' ? 'asc' : 'desc';
$query = Comment::query()
->where('board_id', $board?->id)
->with(['user', 'parent'])
->withCount([
'replies' => function ($q) use ($board) {
$q->where('board_id', $board?->id);
// 삭제되지 않은 답글만 카운트
$q->whereNull('deleted_at');
},
])
->where('board_id', $resolvedBoardId)
->with(['user', 'user.avatarAttachment', 'parent'])
->where('post_id', $postId);
// 권한 스코프 필터링 (Service에서 컨텍스트 기반으로 전달)
@@ -123,7 +118,6 @@ class CommentRepository implements CommentRepositoryInterface
* 모든 하위 자손(depth 2+)을 포함한 전체 답글 수로 재계산합니다.
*
* @param Collection $comments 정렬된 댓글 컬렉션
* @return void
*/
private function recalculateDescendantCounts(Collection $comments): void
{
@@ -190,7 +184,7 @@ class CommentRepository implements CommentRepositoryInterface
* @param int $id 댓글 ID
* @return Comment 댓글 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(string $slug, int $id): Comment
{
@@ -211,7 +205,7 @@ class CommentRepository implements CommentRepositoryInterface
* @param array $data 수정할 데이터
* @return Comment 수정된 댓글 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(string $slug, int $id, array $data): Comment
{
@@ -229,7 +223,7 @@ class CommentRepository implements CommentRepositoryInterface
* @param int $id 댓글 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(string $slug, int $id): bool
{
@@ -245,7 +239,7 @@ class CommentRepository implements CommentRepositoryInterface
* @param int $id 댓글 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function forceDelete(string $slug, int $id): bool
{
@@ -263,7 +257,7 @@ class CommentRepository implements CommentRepositoryInterface
* @param array $actionLog 작업 이력 데이터
* @return Comment 수정된 댓글 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function updateStatus(string $slug, int $id, string $status, array $actionLog, ?string $triggerType = null): Comment
{
@@ -303,7 +297,7 @@ class CommentRepository implements CommentRepositoryInterface
* @param array $updates 업데이트할 데이터 (status, trigger_type, deleted_at, action_log)
* @return Comment 수정된 댓글
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function updateStatusBulk(string $slug, int $id, array $updates): Comment
{
@@ -401,25 +395,31 @@ class CommentRepository implements CommentRepositoryInterface
$boardSlugFilter = $filters['board_slug'] ?? null;
$search = $filters['search'] ?? null;
$sort = $filters['sort'] ?? 'latest';
$cachedTotal = $filters['cached_total'] ?? null;
$orderDirection = $sort === 'oldest' ? 'asc' : 'desc';
// 비활성 게시판 제외 — JOIN 대신 whereNotIn으로 인덱스 활용
$inactiveBoardIds = Board::where('is_active', false)->pluck('id')->all();
$query = Comment::query()
->select('board_comments.*')
->where('board_comments.user_id', $userId)
// 삭제된 게시글 제외 (INNER JOIN → deleted_at IS NULL)
->join('board_posts', function ($join) {
$join->on('board_posts.id', '=', 'board_comments.post_id')
// 삭제된 게시글 제외 — whereExists로 JOIN 대체
->whereExists(function ($q) {
$q->select(DB::raw(1))
->from('board_posts')
->whereColumn('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);
})
->with(['post.board'])
->orderBy('board_comments.created_at', $orderDirection);
// 비활성 게시판 제외
if (! empty($inactiveBoardIds)) {
$query->whereNotIn('board_comments.board_id', $inactiveBoardIds);
}
// 게시판 필터: board_slug → board_id 조회
if ($boardSlugFilter) {
$boardId = Board::where('slug', $boardSlugFilter)->value('id');
@@ -434,7 +434,7 @@ class CommentRepository implements CommentRepositoryInterface
$query->where('board_comments.content', 'like', $keyword);
}
$paginator = $query->paginate($perPage);
$paginator = $query->paginate($perPage, ['*'], 'page', null, $cachedTotal);
// paginate 후 현재 페이지 항목에만 PHP 가공 적용
$paginator->through(function (Comment $comment) {
@@ -442,18 +442,17 @@ class CommentRepository implements CommentRepositoryInterface
$board = $post?->board;
return [
'id' => $comment->id,
'board_slug' => $board?->slug ?? '',
'board_name' => $board?->getLocalizedName() ?? '',
'post_title' => $post?->title ?? '',
'post_id_val' => $post?->id,
'content' => $comment->content,
'created_at' => $this->formatCreatedAt($comment->created_at),
'id' => $comment->id,
'board_slug' => $board?->slug ?? '',
'board_name' => $board?->getLocalizedName() ?? '',
'post_title' => $post?->title ?? '',
'post_id_val' => $post?->id,
'content' => $comment->content,
'created_at' => $this->formatCreatedAt($comment->created_at),
'created_at_formatted' => $this->formatCreatedAtFormat($comment->created_at, g7_module_settings('sirsoft-board', 'display.date_display_format', 'standard')),
];
});
return $paginator;
}
}
@@ -1,62 +0,0 @@
<?php
namespace Modules\Sirsoft\Board\Repositories\Contracts;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Modules\Sirsoft\Board\Models\BoardMailTemplate;
/**
* 게시판 메일 템플릿 리포지토리 인터페이스
*/
interface BoardMailTemplateRepositoryInterface
{
/**
* ID로 메일 템플릿을 조회합니다.
*
* @param int $id 템플릿 ID
* @return BoardMailTemplate|null
*/
public function findById(int $id): ?BoardMailTemplate;
/**
* 유형으로 메일 템플릿을 조회합니다.
*
* @param string $type 템플릿 유형
* @return BoardMailTemplate|null
*/
public function findByType(string $type): ?BoardMailTemplate;
/**
* 활성 상태인 특정 유형의 템플릿을 조회합니다.
*
* @param string $type 템플릿 유형
* @return BoardMailTemplate|null
*/
public function getActiveByType(string $type): ?BoardMailTemplate;
/**
* 전체 템플릿 목록을 조회합니다.
*
* @return Collection
*/
public function getAllTemplates(): Collection;
/**
* 메일 템플릿을 수정합니다.
*
* @param BoardMailTemplate $template 수정 대상
* @param array $data 수정 데이터
* @return bool
*/
public function update(BoardMailTemplate $template, array $data): bool;
/**
* 메일 템플릿 목록을 페이지네이션하여 조회합니다.
*
* @param array $filters 필터 조건
* @param int $perPage 페이지 당 항목 수
* @return LengthAwarePaginator
*/
public function getPaginated(array $filters = [], int $perPage = 20): LengthAwarePaginator;
}
@@ -121,6 +121,15 @@ interface BoardRepositoryInterface
*/
public function getBoardRecentPosts(string $slug, int $limit): array;
/**
* 게시판 ID로 최근 게시물을 조회합니다 (slug 재조회 없음).
*
* @param int $boardId 게시판 ID
* @param int $limit 조회 개수
* @return array<int, array<string, mixed>>
*/
public function getBoardRecentPostsById(int $boardId, int $limit): array;
/**
* 게시판의 게시글 개수를 조회합니다.
*
@@ -194,6 +203,22 @@ interface BoardRepositoryInterface
*/
public function getActiveBoardsOrdered(string $orderBy = 'created_at', string $orderDirection = 'desc'): Collection;
/**
* 활성 게시판의 통계를 조회합니다 (게시판 수, 게시글 수, 댓글 수).
*
* @return object{boards_count: int, posts_total: int, comments_total: int}
*/
public function getActiveBoardStats(): object;
/**
* 메뉴용 경량 게시판 목록을 조회합니다.
*
* id, name, slug 컬럼만 조회하여 메뉴 렌더링에 필요한 최소 데이터만 반환합니다.
*
* @return Collection 활성 게시판 컬렉션 (id, name, slug만 포함)
*/
public function getActiveBoardsForMenu(): Collection;
/**
* 특정 유형의 게시판 개수를 반환합니다.
*
@@ -3,6 +3,8 @@
namespace Modules\Sirsoft\Board\Repositories\Contracts;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Sirsoft\Board\Models\Comment;
/**
@@ -19,7 +21,7 @@ interface CommentRepositoryInterface
* @param string $orderDirection 정렬 방향 (ASC 또는 DESC, 기본값: DESC)
* @return Collection 정렬된 댓글 컬렉션
*/
public function getByPostId(string $slug, int $postId, bool $withTrashed = false, string $orderDirection = 'DESC', ?string $scopePermission = null): Collection;
public function getByPostId(string $slug, int $postId, bool $withTrashed = false, string $orderDirection = 'DESC', ?string $scopePermission = null, ?int $boardId = null): Collection;
/**
* 댓글을 생성합니다.
@@ -35,6 +37,7 @@ interface CommentRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 댓글 ID
* @return Comment|null 댓글 모델 또는 null
*/
public function find(string $slug, int $id): ?Comment;
@@ -43,8 +46,9 @@ interface CommentRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 댓글 ID
* @return Comment 댓글 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(string $slug, int $id): Comment;
@@ -54,8 +58,9 @@ interface CommentRepositoryInterface
* @param string $slug 게시판 슬러그
* @param int $id 댓글 ID
* @param array $data 수정할 데이터
* @return Comment 수정된 댓글 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(string $slug, int $id, array $data): Comment;
@@ -64,8 +69,9 @@ interface CommentRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 댓글 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(string $slug, int $id): bool;
@@ -74,8 +80,9 @@ interface CommentRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 댓글 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function forceDelete(string $slug, int $id): bool;
@@ -88,7 +95,7 @@ interface CommentRepositoryInterface
* @param array $actionLog 작업 이력 데이터
* @param string|null $triggerType 트리거 유형 (report, admin, auto_hide 등)
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function updateStatus(string $slug, int $id, string $status, array $actionLog, ?string $triggerType = null): Comment;
@@ -100,7 +107,7 @@ interface CommentRepositoryInterface
* @param array $updates 업데이트할 데이터 (status, trigger_type, deleted_at, action_log)
* @return Comment 수정된 댓글
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function updateStatusBulk(string $slug, int $id, array $updates): Comment;
@@ -136,7 +143,7 @@ interface CommentRepositoryInterface
* @param int $userId 사용자 ID
* @param array $filters 필터 조건 (board_slug, search, sort)
* @param int $perPage 페이지당 항목 수
* @return \Illuminate\Pagination\LengthAwarePaginator 댓글 목록
* @return LengthAwarePaginator 댓글 목록
*/
public function getUserComments(int $userId, array $filters = [], int $perPage = 20): \Illuminate\Pagination\LengthAwarePaginator;
public function getUserComments(int $userId, array $filters = [], int $perPage = 20): LengthAwarePaginator;
}
@@ -2,7 +2,11 @@
namespace Modules\Sirsoft\Board\Repositories\Contracts;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Sirsoft\Board\Models\Board;
use Modules\Sirsoft\Board\Models\Post;
/**
@@ -17,8 +21,9 @@ interface PostRepositoryInterface
* @param array $filters 필터 조건
* @param int $perPage 페이지당 항목 수
* @param bool $withTrashed 삭제된 게시글 포함 여부
* @param Board|null $board 게시판 모델 (이미 조회된 경우 전달하여 중복 쿼리 방지)
*/
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;
/**
* 게시글을 생성합니다.
@@ -34,6 +39,7 @@ interface PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return Post|null 게시글 모델 또는 null
*/
public function find(string $slug, int $id): ?Post;
@@ -42,8 +48,9 @@ interface PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return Post 게시글 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(string $slug, int $id): Post;
@@ -53,8 +60,9 @@ interface PostRepositoryInterface
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @param array $data 수정할 데이터
* @return Post 수정된 게시글 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(string $slug, int $id, array $data): Post;
@@ -63,8 +71,9 @@ interface PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(string $slug, int $id): bool;
@@ -73,8 +82,9 @@ interface PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function forceDelete(string $slug, int $id): bool;
@@ -87,7 +97,7 @@ interface PostRepositoryInterface
* @param array $actionLog 작업 이력 데이터
* @param string|null $triggerType 트리거 유형 (admin, report 등)
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function updateStatus(string $slug, int $id, string $status, array $actionLog, ?string $triggerType = null): Post;
@@ -108,7 +118,7 @@ interface 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;
@@ -117,9 +127,10 @@ interface PostRepositoryInterface
*
* @param string $slug 게시판 슬러그
* @param int $id 게시글 ID
* @param int|null $boardId 게시판 ID (전달 시 Board 재조회 생략)
* @return Post|null 게시글 모델 (카운트 포함)
*/
public function findWithCounts(string $slug, int $id): ?Post;
public function findWithCounts(string $slug, int $id, ?int $boardId = null): ?Post;
/**
* 전체 일반 게시글(원글) 수를 조회합니다.
@@ -139,9 +150,10 @@ interface PostRepositoryInterface
* @param int $id 현재 게시글 ID
* @param array $filters 정렬 파라미터 (order_by, order_direction)
* @param bool $withTrashed 삭제된 게시글 포함 여부
* @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): array;
public function getAdjacentPosts(string $slug, int $id, array $filters = [], bool $withTrashed = false, ?int $boardId = null): array;
/**
* 사용자의 게시글 활동 목록을 조회합니다.
@@ -161,7 +173,7 @@ interface PostRepositoryInterface
* @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 $slug, string $keyword, string $orderBy = 'created_at', string $direction = 'desc', int $limit = 10): array;
@@ -183,7 +195,7 @@ interface PostRepositoryInterface
* @param string $direction 정렬 방향 (asc, desc)
* @param int $perPage 페이지당 항목 수
* @param int $page 페이지 번호
* @return array{total: int, items: \Illuminate\Database\Eloquent\Collection}
* @return array{total: int, items: Collection}
*/
public function searchAcrossBoards(array $boardIds, string $keyword, string $orderBy = 'created_at', string $direction = 'desc', int $perPage = 10, int $page = 1): array;
@@ -192,7 +204,6 @@ interface PostRepositoryInterface
*
* @param array $boardIds 검색 대상 게시판 ID 목록
* @param string $keyword 검색 키워드
* @return int
*/
public function countAcrossBoards(array $boardIds, string $keyword): int;
@@ -252,9 +263,9 @@ interface PostRepositoryInterface
* 이커머스 문의 목록 구성 시 게시글 데이터를 일괄 조회할 때 사용합니다.
*
* @param array<int> $ids 게시글 ID 배열
* @return \Illuminate\Database\Eloquent\Collection<int, Post> 게시글 컬렉션
* @return Collection<int, Post> 게시글 컬렉션
*/
public function findByIdsWithRelations(array $ids): \Illuminate\Database\Eloquent\Collection;
public function findByIdsWithRelations(array $ids): Collection;
/**
* 부모 게시글 ID로 첫 번째 자식(답변) 게시글을 조회합니다 (board 관계 포함).
@@ -2,7 +2,10 @@
namespace Modules\Sirsoft\Board\Repositories\Contracts;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Sirsoft\Board\Exceptions\DuplicateReportException;
use Modules\Sirsoft\Board\Models\Report;
use Modules\Sirsoft\Board\Models\ReportLog;
@@ -31,6 +34,7 @@ interface ReportRepositoryInterface
* ID로 신고를 조회합니다.
*
* @param int $id 신고 ID
* @return Report|null 신고 모델 또는 null
*/
public function find(int $id): ?Report;
@@ -38,8 +42,9 @@ interface ReportRepositoryInterface
* ID로 신고를 조회하며, 없으면 예외를 발생시킵니다.
*
* @param int $id 신고 ID
* @return Report 신고 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(int $id): Report;
@@ -48,8 +53,9 @@ interface ReportRepositoryInterface
*
* @param int $id 신고 ID
* @param array $data 수정할 데이터
* @return Report 수정된 신고 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(int $id, array $data): Report;
@@ -57,8 +63,9 @@ interface ReportRepositoryInterface
* 신고를 삭제합니다 (소프트 삭제).
*
* @param int $id 신고 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(int $id): bool;
@@ -66,8 +73,9 @@ interface ReportRepositoryInterface
* 신고를 영구 삭제합니다.
*
* @param int $id 신고 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function forceDelete(int $id): bool;
@@ -98,15 +106,6 @@ interface ReportRepositoryInterface
*/
public function paginateGrouped(array $filters = [], int $perPage = 15): LengthAwarePaginator;
/**
* 특정 대상(게시글/댓글)에 대한 모든 신고를 조회합니다.
*
* @param int $boardId 게시판 ID
* @param string $targetType 대상 타입 (post/comment)
* @param int $targetId 대상 ID
*/
public function findByTarget(int $boardId, string $targetType, int $targetId): \Illuminate\Database\Eloquent\Collection;
/**
* 특정 대상에 대한 모든 신고의 상태를 일괄 변경합니다.
*
@@ -118,15 +117,6 @@ interface ReportRepositoryInterface
*/
public function bulkUpdateStatusByTarget(int $boardId, string $targetType, int $targetId, array $data): int;
/**
* 취소된 신고를 포함하여 동일 대상의 케이스를 조회합니다.
*
* @param int $boardId 게시판 ID
* @param string $targetType 대상 타입 (post/comment)
* @param int $targetId 대상 ID
*/
public function findByTargetWithTrashed(int $boardId, string $targetType, int $targetId): \Illuminate\Database\Eloquent\Collection;
/**
* 사용자의 오늘(자정 기준) 전체 신고 건수를 boards_report_logs 기준으로 조회합니다.
*
@@ -175,7 +165,7 @@ interface ReportRepositoryInterface
* @param array $data 로그 생성 데이터
* @return ReportLog 생성된 로그 모델
*
* @throws \Modules\Sirsoft\Board\Exceptions\DuplicateReportException
* @throws DuplicateReportException
*/
public function createLog(array $data): ReportLog;
@@ -183,9 +173,8 @@ interface ReportRepositoryInterface
* 신고 케이스의 신고자 로그를 페이지네이션으로 반환합니다.
*
* @param int $reportId 신고 케이스 ID
* @param int $perPage 페이지당 항목 수
* @param int $page 페이지 번호
* @return LengthAwarePaginator
* @param int $perPage 페이지당 항목 수
* @param int $page 페이지 번호
*/
public function paginateLogsByReport(int $reportId, int $perPage = 10, int $page = 1): LengthAwarePaginator;
@@ -199,4 +188,17 @@ interface ReportRepositoryInterface
* @return bool 이미 신고 여부
*/
public function hasUserReported(int $userId, int $boardId, string $targetType, int $targetId): bool;
/**
* 특정 사용자가 여러 대상을 신고했는지 일괄 확인합니다.
*
* N+1 방지를 위해 복수 대상의 신고 여부를 한 번의 쿼리로 조회합니다.
*
* @param int $userId 사용자 ID
* @param int $boardId 게시판 ID
* @param string $targetType 대상 타입 (post/comment)
* @param array<int> $targetIds 대상 ID 목록
* @return array<int> 신고한 대상 ID 목록
*/
public function getReportedTargetIds(int $userId, int $boardId, string $targetType, array $targetIds): array;
}
@@ -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();
}
}
@@ -4,6 +4,9 @@ namespace Modules\Sirsoft\Board\Repositories;
use App\Helpers\PermissionHelper;
use App\Search\Engines\DatabaseFulltextEngine;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
@@ -82,6 +85,7 @@ class ReportRepository implements ReportRepositoryInterface
* ID로 신고를 조회합니다.
*
* @param int $id 신고 ID
* @return Report|null 신고 모델 또는 null
*/
public function find(int $id): ?Report
{
@@ -92,8 +96,9 @@ class ReportRepository implements ReportRepositoryInterface
* ID로 신고를 조회하며, 없으면 예외를 발생시킵니다.
*
* @param int $id 신고 ID
* @return Report 신고 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function findOrFail(int $id): Report
{
@@ -106,8 +111,9 @@ class ReportRepository implements ReportRepositoryInterface
*
* @param int $id 신고 ID
* @param array $data 수정할 데이터
* @return Report 수정된 신고 모델
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function update(int $id, array $data): Report
{
@@ -121,8 +127,9 @@ class ReportRepository implements ReportRepositoryInterface
* 신고를 삭제합니다 (소프트 삭제).
*
* @param int $id 신고 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function delete(int $id): bool
{
@@ -135,8 +142,9 @@ class ReportRepository implements ReportRepositoryInterface
* 신고를 영구 삭제합니다.
*
* @param int $id 신고 ID
* @return bool 삭제 성공 여부
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws ModelNotFoundException
*/
public function forceDelete(int $id): bool
{
@@ -318,7 +326,7 @@ class ReportRepository implements ReportRepositoryInterface
* 공통 검색 필드: board_name, author_name, reporter_name
* 추가 검색 필드: $extraFields로 전달 (예: post_title)
*
* @param \Illuminate\Database\Eloquent\Builder $query 쿼리 빌더
* @param Builder $query 쿼리 빌더
* @param array $filters 필터 조건 (search, search_field 키 사용)
* @param array $extraFields 추가 검색 필드 목록
*/
@@ -332,7 +340,7 @@ class ReportRepository implements ReportRepositoryInterface
$searchField = $filters['search_field'] ?? 'all';
$lowerKeyword = mb_strtolower($keyword);
$query->where(function ($q) use ($keyword, $lowerKeyword, $searchField, $extraFields) {
$query->where(function ($q) use ($keyword, $searchField, $extraFields) {
// 추가 필드: post_title (paginateGrouped 전용 — logs 첫 번째 snapshot 기준)
if (in_array('post_title', $extraFields) && ($searchField === 'all' || $searchField === 'post_title')) {
$q->orWhereHas('logs', function ($lq) use ($keyword) {
@@ -366,21 +374,6 @@ class ReportRepository implements ReportRepositoryInterface
});
}
/**
* 특정 대상(게시글/댓글)에 대한 케이스를 조회합니다.
*
* @param int $boardId 게시판 ID
* @param string $targetType 대상 타입 (post/comment)
* @param int $targetId 대상 ID
*/
public function findByTarget(int $boardId, string $targetType, int $targetId): \Illuminate\Database\Eloquent\Collection
{
return Report::where('board_id', $boardId)
->where('target_type', $targetType)
->where('target_id', $targetId)
->get();
}
/**
* 특정 대상에 대한 신고의 상태를 일괄 변경합니다.
*
@@ -408,22 +401,6 @@ class ReportRepository implements ReportRepositoryInterface
->update($data);
}
/**
* 취소된 신고를 포함하여 동일 대상의 케이스를 조회합니다.
*
* @param int $boardId 게시판 ID
* @param string $targetType 대상 타입 (post/comment)
* @param int $targetId 대상 ID
*/
public function findByTargetWithTrashed(int $boardId, string $targetType, int $targetId): \Illuminate\Database\Eloquent\Collection
{
return Report::withTrashed()
->where('board_id', $boardId)
->where('target_type', $targetType)
->where('target_id', $targetId)
->get();
}
/**
* 사용자의 오늘(자정 기준) 전체 신고 건수를 boards_report_logs 기준으로 조회합니다.
*
@@ -526,7 +503,7 @@ class ReportRepository implements ReportRepositoryInterface
* @param array $data 로그 생성 데이터
* @return ReportLog 생성된 로그 모델
*
* @throws \Modules\Sirsoft\Board\Exceptions\DuplicateReportException
* @throws DuplicateReportException
*/
public function createLog(array $data): ReportLog
{
@@ -546,9 +523,8 @@ class ReportRepository implements ReportRepositoryInterface
* 신고 케이스의 신고자 로그를 페이지네이션으로 반환합니다.
*
* @param int $reportId 신고 케이스 ID
* @param int $perPage 페이지당 항목 수
* @param int $page 페이지 번호
* @return LengthAwarePaginator
* @param int $perPage 페이지당 항목 수
* @param int $page 페이지 번호
*/
public function paginateLogsByReport(int $reportId, int $perPage = 10, int $page = 1): LengthAwarePaginator
{
@@ -577,4 +553,29 @@ class ReportRepository implements ReportRepositoryInterface
->where('reporter_id', $userId)
->exists();
}
/**
* 특정 사용자가 여러 대상을 신고했는지 일괄 확인합니다.
*
* N+1 방지를 위해 복수 대상의 신고 여부를 한 번의 쿼리로 조회합니다.
*
* @param int $userId 사용자 ID
* @param int $boardId 게시판 ID
* @param string $targetType 대상 타입 (post/comment)
* @param array<int> $targetIds 대상 ID 목록
* @return array<int> 신고한 대상 ID 목록
*/
public function getReportedTargetIds(int $userId, int $boardId, string $targetType, array $targetIds): array
{
if (empty($targetIds)) {
return [];
}
return Report::where('board_id', $boardId)
->where('target_type', $targetType)
->whereIn('target_id', $targetIds)
->whereHas('logs', fn ($q) => $q->where('reporter_id', $userId))
->pluck('target_id')
->all();
}
}