Files
Gnuboard7/app/Repositories/NotificationRepository.php
T
HeuJung be9befe023 fix(core,board,ecommerce,page,gdpr,basic): 깊은 OFFSET 목록 조회 개선 및 raw/테이블명 전수 정리
목록이 뒤쪽 페이지로 갈수록 느려지는 원인은 건너뛰는 행의 넓은 컬럼까지 읽는 것이었다.
지연 조인(inner 는 키 컬럼만, outer 는 이번 페이지 행만 전체 컬럼)과 정렬 컬럼 해석을
코어 공통 트레이트로 두고 코어 8 + 확장 6 저장소에 적용했다.

감사 지적 처리:
- 그룹 쿼리의 총 건수 오산 — count 는 groupBy 를 벗기지 않아 첫 그룹의 행 수를
 총 건수로 돌려준다. getCountForPagination 으로 교정.
- audit 전수 스캔이 버퍼 한계로 한 번도 동작하지 않던 결함과, 확장 경로를 놓치던
 정규식 5건을 함께 고쳤다. 그동안 번들 확장의 위반이 보이지 않았다.

raw 20건을 빌더 표현으로 치환하고 하드코딩 테이블명 16건을 모델 유래로 바꿨다.
이 과정에서 마이페이지 「내가 댓글 단 글」 검색이 조인 별칭 충돌로 SQL 오류를 내던
결함이 해소됐다. 재발 차단용 룰 2종을 신설하고, 컬럼 프루닝 룰을 error 로 승격했다
(전역 위반 0건 — warning 으로 두면 "0 error" 판정을 통과하며 무음으로 재누적된다).

정렬 허용 목록은 FormRequest 게이트를 덮어야 한다. 좁으면 검증을 통과한 정렬이 422 도
로그도 없이 기본값으로 되돌아간다(스케줄 실행 이력의 종료시각·소요시간 정렬이 그랬다).
호출처를 스캔해 매핑 완전성까지 검사하는 계약 테스트로 전수 강제한다.

해외 배송지 결함도 함께 고쳤다 — 조회는 city/state/postal_code 로 내려주고 폼은
intl_* 로 제출하는 비대칭 때문에, 수정 시 입력칸이 비어 보이고 저장하면 기존 값이
유실됐다. 쿠폰 수정의 유효기간 미검증과 1인당 사용 제한 부분 수정 차단도 함께 수정.
2026-08-02 14:36:37 +09:00

155 lines
4.7 KiB
PHP

<?php
namespace App\Repositories;
use App\Contracts\Repositories\NotificationRepositoryInterface;
use App\Models\User;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Pagination\LengthAwarePaginator;
class NotificationRepository implements NotificationRepositoryInterface
{
/**
* 사용자의 알림 목록을 페이지네이션으로 조회합니다.
*
* @param User $user 대상 사용자
* @param array $filters 필터 조건 (read: unread|read)
* @param int $perPage 페이지당 항목 수
* @return LengthAwarePaginator 페이지네이션된 알림 목록
*/
public function getByUser(User $user, array $filters = [], int $perPage = 20): LengthAwarePaginator
{
$query = $user->notifications();
if (isset($filters['read']) && $filters['read'] === 'unread') {
$query->whereNull('read_at');
} elseif (isset($filters['read']) && $filters['read'] === 'read') {
$query->whereNotNull('read_at');
}
// audit:allow repository-paginate-column-pruning reason: 사용자 1명에 종속된 알림함 —
// $user->notifications() 로 이미 좁혀지고, 목록이 표시하는 본문 자체가 data(JSON) 라
// 걷어낼 넓은 컬럼이 없다
return $query->orderBy('created_at', 'desc')->paginate($perPage);
}
/**
* 사용자의 미읽음 알림 수를 반환합니다.
*
* @param User $user 대상 사용자
* @return int 미읽음 알림 수
*/
public function getUnreadCount(User $user): int
{
return $user->unreadNotifications()->count();
}
/**
* 특정 알림을 읽음 처리합니다.
*
* @param User $user 대상 사용자
* @param string $notificationId 알림 ID
* @return DatabaseNotification|null 읽음 처리된 알림 (없으면 null)
*/
public function markAsRead(User $user, string $notificationId): ?DatabaseNotification
{
$notification = $user->notifications()->find($notificationId);
if (! $notification) {
return null;
}
$notification->markAsRead();
return $notification;
}
/**
* 지정된 알림들을 일괄 읽음 처리합니다.
*
* @param User $user 대상 사용자
* @param array $ids 알림 ID 배열
* @return int 읽음 처리된 알림 수
*/
public function markBatchAsRead(User $user, array $ids): int
{
return $user->unreadNotifications()
->whereIn('id', $ids)
->update(['read_at' => now()]);
}
/**
* 사용자의 모든 미읽음 알림을 읽음 처리합니다.
*
* @param User $user 대상 사용자
* @return int 읽음 처리된 알림 수
*/
public function markAllAsRead(User $user): int
{
$count = $user->unreadNotifications()->count();
$user->unreadNotifications->markAsRead();
return $count;
}
/**
* 알림을 삭제합니다.
*
* @param User $user 대상 사용자
* @param string $notificationId 알림 ID
* @return bool 삭제 성공 여부 (알림이 없으면 false)
*/
public function delete(User $user, string $notificationId): bool
{
$notification = $user->notifications()->find($notificationId);
if (! $notification) {
return false;
}
return (bool) $notification->delete();
}
/**
* 사용자의 모든 알림을 삭제합니다.
*
* @param User $user
* @return int 삭제된 알림 수
*/
public function deleteAll(User $user): int
{
return $user->notifications()->delete();
}
/**
* 오래된 알림을 정리합니다.
*
* @param int $readRetentionDays 읽은 알림 보관 일수 (0 이하면 정리하지 않음)
* @param int $unreadRetentionDays 미읽음 알림 보관 일수 (0 이하면 정리하지 않음)
* @return array{deleted_read: int, deleted_unread: int}
*/
public function cleanup(int $readRetentionDays, int $unreadRetentionDays): array
{
$deletedRead = 0;
$deletedUnread = 0;
if ($readRetentionDays > 0) {
$deletedRead = DatabaseNotification::whereNotNull('read_at')
->where('read_at', '<', now()->subDays($readRetentionDays))
->delete();
}
if ($unreadRetentionDays > 0) {
$deletedUnread = DatabaseNotification::whereNull('read_at')
->where('created_at', '<', now()->subDays($unreadRetentionDays))
->delete();
}
return [
'deleted_read' => $deletedRead,
'deleted_unread' => $deletedUnread,
];
}
}