Files
Gnuboard7/app/Helpers/ResponseHelper.php
T
HeuJung b10e89bef0 fix(core,board,ecommerce,page,gdpr,ckeditor5,kginicis,admin_basic,basic): 목록 조회·검증 계층 정비 및 감사 지적 전건 처리
목록 조회 성능 축(깊은 OFFSET·정렬·색인)과 그 검증 계층에서 계획서 전수검수와 3회에 걸친
감사가 지적한 항목을 처리했다. 세부 경위는 의 각 회차 문서에 있다.

검증 계층 — 컨트롤러가 base Request 를 직접 주입받던 확장 13곳을 전용 FormRequest 로 옮겼다.
옮기면서 기존 동작 계약은 그대로 두었다: 상한 초과 limit 을 거부하지 않고 상한까지 반환하던
공개 API, per_page 를 범위로 조정하던 관리자 목록, 미지원 period 를 year 로 해석하던 인기글
목록 모두 종전과 같은 응답을 낸다. 상한/폴백을 rules 로 승격시키면 200 이던 응답이 422 가
되어 기존 링크가 깨지므로, 규칙은 타입만 닫고 클램프·폴백은 접근자가 맡는다. period 는
접근자가 닫힌 집합만 반환해 캐시 키 공간도 함께 닫힌다.

ckeditor5 이미지 업로드만 ResponseHelper 봉투를 쓰지 않는다. 응답을 파싱하는 주체가 CDN 으로
로드되는 상위 CKEditor5 43.3.1 의 SimpleUploadAdapter 라 규약을 바꿀 수 없어, 각 응답 지점에
사유를 명시한 면제를 부착하고 근거를 API 문서에 남겼다.

하네스 — 룰 5개의 대상 경로 패턴이 매처와 맞지 않아 번들 확장 컨트롤러가 검사 대상에서
통째로 빠져 있었다. 패턴을 고치자 확장 위반 17건이 드러나 전건 처리했다. severity 오타가
요약 집계 양쪽에 안 잡혀 "0 error" 로 보고되던 문제도 런너 사전 검증으로 막았다.

정렬 게이트 대조 하네스는 관계 정렬 변형만 쓰는 저장소를 탐지하지 못한 채 통과시키고 있었다.
탐지·제외·인자 파싱을 함께 고치고 단위 테스트를 신설했다.
2026-08-02 15:29:29 +09:00

473 lines
18 KiB
PHP

<?php
namespace App\Helpers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Facades\App;
class ResponseHelper
{
/**
* JSON 응답 인코딩 옵션.
*
* JSON_UNESCAPED_UNICODE: 한글 등 멀티바이트 문자를 `\uXXXX` (6바이트) 로
* 이스케이프하지 않고 raw UTF-8 (한글 3바이트) 로 직렬화하여 응답 크기를 줄인다.
* 특히 다국어 팩(lang) 응답에서 전송량 절감 효과가 크다.
*/
public const JSON_ENCODE_OPTIONS = JSON_UNESCAPED_UNICODE;
/**
* 성공 응답을 생성합니다.
*
* @param string $messageKey 메시지 키 (기본값: 'messages.success')
* @param mixed $data 응답 데이터
* @param int $statusCode HTTP 상태 코드 (기본값: 200)
* @param array $messageParams 메시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse JSON 응답
*/
public static function success(
string $messageKey = 'messages.success',
mixed $data = null,
int $statusCode = 200,
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
return response()->json([
'success' => true,
'message' => self::trans($messageKey, $messageParams, $domain),
'data' => $data,
], $statusCode, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 실패 응답을 생성합니다.
*
* @param string $messageKey 메시지 키 (기본값: 'messages.failed')
* @param int $statusCode HTTP 상태 코드 (기본값: 400)
* @param mixed $errors 오류 정보
* @param array $messageParams 메시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse JSON 응답
*/
public static function error(
string $messageKey = 'messages.failed',
int $statusCode = 400,
mixed $errors = null,
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
$response = [
'success' => false,
'message' => self::trans($messageKey, $messageParams, $domain),
];
if ($errors instanceof \Throwable) {
if (config('app.debug')) {
// messageParams에 이미 에러 메시지가 포함된 경우 중복 방지
if (empty($messageParams)) {
$response['message'] .= ': '.$errors->getMessage();
}
$response['debug'] = self::formatException($errors);
}
} elseif ($errors !== null) {
if ($statusCode >= 500 && is_string($errors) && ! config('app.debug')) {
// 프로덕션 500+ 에러의 string errors 차단 (내부 예외 메시지 노출 방지)
} else {
$response['errors'] = $errors;
}
}
return response()->json($response, $statusCode, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 입력 검증 실패 응답을 생성합니다.
*
* @param mixed $errors 검증 오류 정보
* @param string $messageKey 메시지 키 (기본값: 'messages.validation_failed')
* @param array $messageParams 메시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 422 상태 코드를 가진 JSON 응답
*/
public static function validationError(
mixed $errors,
string $messageKey = 'messages.validation_failed',
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
return response()->json([
'success' => false,
'message' => self::trans($messageKey, $messageParams, $domain),
'errors' => $errors,
], 422, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 인증 실패 응답을 생성합니다.
*
* @param string $messageKey 메시지 키 (기본값: 'messages.unauthorized')
* @param array $messageParams 메시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 401 상태 코드를 가진 JSON 응답
*/
public static function unauthorized(
string $messageKey = 'messages.unauthorized',
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
return response()->json([
'success' => false,
'message' => self::trans($messageKey, $messageParams, $domain),
], 401, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 권한 부족 응답을 생성합니다.
*
* @param string $messageKey 멤시지 키 (기본값: 'messages.forbidden')
* @param array $messageParams 멤시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 403 상태 코드를 가진 JSON 응답
*/
public static function forbidden(
string $messageKey = 'messages.forbidden',
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
return response()->json([
'success' => false,
'message' => self::trans($messageKey, $messageParams, $domain),
], 403, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 리소스를 찾을 수 없음 응답을 생성합니다.
*
* @param string $messageKey 멤시지 키 (기본값: 'messages.not_found')
* @param array $messageParams 멤시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 404 상태 코드를 가진 JSON 응답
*/
public static function notFound(
string $messageKey = 'messages.not_found',
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
return response()->json([
'success' => false,
'message' => self::trans($messageKey, $messageParams, $domain),
], 404, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 서버 내부 오류 응답을 생성합니다.
*
* @param string $messageKey 멤시지 키 (기본값: 'messages.error_occurred')
* @param mixed $error 오류 정보 (디버그 모드에서만 표시)
* @param array $messageParams 멤시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 500 상태 코드를 가진 JSON 응답
*/
public static function serverError(
string $messageKey = 'messages.error_occurred',
mixed $error = null,
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
$response = [
'success' => false,
'message' => self::trans($messageKey, $messageParams, $domain),
];
if ($error instanceof \Throwable) {
if (config('app.debug')) {
$response['message'] .= ': '.$error->getMessage();
$response['debug'] = self::formatException($error);
}
} elseif ($error !== null && config('app.debug')) {
$response['error'] = $error;
}
return response()->json($response, 500, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 다국어 메시지를 변환합니다.
*
* @param string $key 번역 키
* @param array $params 번역 매개변수
* @param string $domain 번역 도메인
* @return string 번역된 메시지
*/
private static function trans(
string $key,
array $params = [],
string $domain = 'core'
): string {
$locale = self::getUserLocale();
// 도메인별로 다른 경로에서 번역 파일 로드
$translationKey = $domain === 'core' ? $key : "{$domain}::{$key}";
return __($translationKey, $params, $locale);
}
/**
* 응답에 사용할 언어 코드를 반환합니다.
*
* SetLocale 미들웨어가 이미 사용자 언어 우선순위
* (1) 인증 사용자의 users.language → (2) Accept-Language 헤더(localStorage.g7_locale 포함)
* → (3) config('app.locale') fallback
* 를 적용해 App::setLocale() 한 결과를 신뢰합니다. supported_locales 화이트리스트
* (활성 코어 언어팩 기반) 검증도 SetLocale 에서 처리되므로 본 메서드는 그 결과만 반환합니다.
*
* @return string 현재 요청에 적용된 언어 코드
*/
private static function getUserLocale(): string
{
return App::getLocale();
}
/**
* 예외 정보를 디버그용 배열로 변환합니다.
*
* @param \Throwable $e 예외 인스턴스
* @return array 디버그 정보 배열
*/
private static function formatException(\Throwable $e): array
{
return [
'exception' => get_class($e),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => collect($e->getTrace())->take(10)->map(fn ($frame) => [
'file' => $frame['file'] ?? null,
'line' => $frame['line'] ?? null,
'function' => ($frame['class'] ?? '').($frame['type'] ?? '').($frame['function'] ?? ''),
])->toArray(),
];
}
/**
* 모듈별 성공 응답을 생성합니다.
*
* @param string $module 모듈명
* @param string $messageKey 멤시지 키
* @param mixed $data 응답 데이터
* @param int $statusCode HTTP 상태 코드 (기본값: 200)
* @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function moduleSuccess(
string $module,
string $messageKey,
mixed $data = null,
int $statusCode = 200,
array $messageParams = []
): JsonResponse {
return self::success($messageKey, $data, $statusCode, $messageParams, $module);
}
/**
* 모듈별 실패 응답을 생성합니다.
*
* @param string $module 모듈명
* @param string $messageKey 멤시지 키
* @param int $statusCode HTTP 상태 코드 (기본값: 400)
* @param mixed $errors 오류 정보
* @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function moduleError(
string $module,
string $messageKey,
int $statusCode = 400,
mixed $errors = null,
array $messageParams = []
): JsonResponse {
return self::error($messageKey, $statusCode, $errors, $messageParams, $module);
}
/**
* 플러그인별 성공 응답을 생성합니다.
*
* @param string $plugin 플러그인명
* @param string $messageKey 멤시지 키
* @param mixed $data 응답 데이터
* @param int $statusCode HTTP 상태 코드 (기본값: 200)
* @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function pluginSuccess(
string $plugin,
string $messageKey,
mixed $data = null,
int $statusCode = 200,
array $messageParams = []
): JsonResponse {
return self::success($messageKey, $data, $statusCode, $messageParams, $plugin);
}
/**
* 플러그인별 실패 응답을 생성합니다.
*
* @param string $plugin 플러그인명
* @param string $messageKey 멤시지 키
* @param int $statusCode HTTP 상태 코드 (기본값: 400)
* @param mixed $errors 오류 정보
* @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function pluginError(
string $plugin,
string $messageKey,
int $statusCode = 400,
mixed $errors = null,
array $messageParams = []
): JsonResponse {
return self::error($messageKey, $statusCode, $errors, $messageParams, $plugin);
}
/**
* JSON Resource를 사용한 성공 응답을 생성합니다.
*
* `$resource->additional([...])` 로 실은 부가 데이터는 응답 최상위에 함께 나갑니다.
* `JsonResource::resolve()` 는 리소스 본문만 돌려주므로, 그것만 쓰면 호출자가 실은
* 부가 데이터가 조용히 사라집니다 — 예를 들어 확장 업데이트 응답의 `search_index`
* (색인 누락 안내)가 사라지면 검색이 0건을 돌려주는 사실을 운영자가 알 방법이 없습니다.
* `success`/`message`/`data` 키는 부가 데이터로 덮어쓰지 않습니다.
*
* @param string $messageKey 멤시지 키 (기본값: 'messages.success')
* @param JsonResource|ResourceCollection|null $resource JSON 리소스
* @param int $statusCode HTTP 상태 코드 (기본값: 200)
* @param array $messageParams 멤시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse JSON 응답
*/
public static function successWithResource(
string $messageKey = 'messages.success',
JsonResource|ResourceCollection|null $resource = null,
int $statusCode = 200,
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
$data = $resource ? $resource->resolve() : null;
$payload = [
'success' => true,
'message' => self::trans($messageKey, $messageParams, $domain),
'data' => $data,
];
$additional = $resource instanceof JsonResource ? (array) $resource->additional : [];
if ($additional !== []) {
$payload += array_diff_key($additional, $payload);
}
return response()->json($payload, $statusCode, [], self::JSON_ENCODE_OPTIONS);
}
/**
* JSON Resource를 사용한 모듈 성공 응답을 생성합니다.
*
* @param string $module 모듈명
* @param string $messageKey 멤시지 키
* @param JsonResource|ResourceCollection|null $resource JSON 리소스
* @param int $statusCode HTTP 상태 코드 (기본값: 200)
* @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function moduleSuccessWithResource(
string $module,
string $messageKey,
JsonResource|ResourceCollection|null $resource = null,
int $statusCode = 200,
array $messageParams = []
): JsonResponse {
return self::successWithResource($messageKey, $resource, $statusCode, $messageParams, $module);
}
/**
* JSON Resource를 사용한 플러그인 성공 응답을 생성합니다.
*
* @param string $plugin 플러그인명
* @param string $messageKey 멤시지 키
* @param JsonResource|ResourceCollection|null $resource JSON 리소스
* @param int $statusCode HTTP 상태 코드 (기본값: 200)
* @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function pluginSuccessWithResource(
string $plugin,
string $messageKey,
JsonResource|ResourceCollection|null $resource = null,
int $statusCode = 200,
array $messageParams = []
): JsonResponse {
return self::successWithResource($messageKey, $resource, $statusCode, $messageParams, $plugin);
}
/**
* 페이지네이션된 리소스 응답을 생성합니다.
*
* @param string $messageKey 멤시지 키 (기본값: 'messages.success')
* @param ResourceCollection|null $collection 페이지네이션된 리소스 컬렉션
* @param array $messageParams 멤시지 매개변수
* @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 페이지네이션 메타 데이터를 포함한 JSON 응답
*/
public static function successWithPagination(
string $messageKey = 'messages.success',
?ResourceCollection $collection = null,
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
$response = [
'success' => true,
'message' => self::trans($messageKey, $messageParams, $domain),
];
if ($collection) {
$paginationData = $collection->resolve();
$response['data'] = $paginationData['data'];
$response['meta'] = [
'current_page' => $paginationData['current_page'] ?? null,
'from' => $paginationData['from'] ?? null,
'last_page' => $paginationData['last_page'] ?? null,
'path' => $paginationData['path'] ?? null,
'per_page' => $paginationData['per_page'] ?? null,
'to' => $paginationData['to'] ?? null,
'total' => $paginationData['total'] ?? null,
];
$response['links'] = $paginationData['links'] ?? null;
}
return response()->json($response, 200, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 본인인증 요구 응답을 생성합니다 (HTTP 428 Precondition Required).
*
* IDV 정책 미들웨어/Listener 가 IdentityVerificationRequiredException 을 던지면
* Handler 가 이 메서드로 응답을 만듭니다. 프론트 ErrorHandlingResolver 가 이 payload 로
* Challenge 모달을 자동 오픈하고 verify 성공 시 return_request 를 재실행합니다.
*
* @param array $verification policy_key/purpose/provider_id/render_hint/return_request 등
* @return JsonResponse 428 응답
*/
public static function identityRequired(array $verification): JsonResponse
{
return response()->json([
'success' => false,
'error_code' => 'identity_verification_required',
'message' => self::trans('identity.errors.verification_required', [], 'core'),
'verification' => $verification,
], 428, [], self::JSON_ENCODE_OPTIONS);
}
}