v7.0.0-beta.1 release
This commit is contained in:
commit
6595fd0eb5
3967 files changed
+1875383
No files matched your search
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
class AdminLayoutErrorHandler
|
||||
{
|
||||
/**
|
||||
* Create a new class instance.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use App\Enums\ScopeType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\User;
|
||||
use App\Providers\AuthServiceProvider;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 권한 체크 헬퍼
|
||||
*
|
||||
* AuthServiceProvider의 권한 체크 메서드를 간결하게 호출할 수 있는 API를 제공합니다.
|
||||
* scope_type 기반 스코프 체크 기능을 포함합니다.
|
||||
*/
|
||||
class PermissionHelper
|
||||
{
|
||||
/**
|
||||
* Permission 캐시 (resource_route_key, owner_key)
|
||||
*
|
||||
* @var array<string, array{resource_route_key: string|null, owner_key: string|null}>
|
||||
*/
|
||||
protected static array $permissionCache = [];
|
||||
|
||||
/**
|
||||
* 단일 권한 체크
|
||||
*
|
||||
* @param string $ability 권한 식별자
|
||||
* @param User|null $user 사용자 (null이면 현재 인증 사용자 또는 guest)
|
||||
* @return bool 권한 보유 여부
|
||||
*/
|
||||
public static function check(string $ability, ?User $user = null): bool
|
||||
{
|
||||
$user = $user ?? Auth::user();
|
||||
|
||||
return AuthServiceProvider::checkPermission($ability, $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 구조화 권한 체크 (OR/AND 중첩)
|
||||
*
|
||||
* @param array|object $permissions 권한 구조 (flat array=AND, {"or":[...]}, {"and":[...]})
|
||||
* @param User|null $user 사용자
|
||||
* @return bool 권한 보유 여부
|
||||
*/
|
||||
public static function checkWithLogic(array|object $permissions, ?User $user = null): bool
|
||||
{
|
||||
$user = $user ?? Auth::user();
|
||||
|
||||
return AuthServiceProvider::checkPermissionsWithLogic($permissions, $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 해당 권한의 effective scope를 조회합니다.
|
||||
*
|
||||
* @param string $permission 권한 식별자
|
||||
* @param User|null $user 사용자 (null이면 현재 인증 사용자)
|
||||
* @return string|null null(전체), 'role'(소유역할), 'self'(본인)
|
||||
*/
|
||||
public static function getEffectiveScope(string $permission, ?User $user = null): ?string
|
||||
{
|
||||
$user = $user ?? Auth::user();
|
||||
|
||||
if (! $user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $user->getEffectiveScopeForPermission($permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* 해당 권한의 owner_key를 조회합니다 (static 캐시).
|
||||
*
|
||||
* @param string $permission 권한 식별자
|
||||
* @return string|null 소유자 식별 컬럼명
|
||||
*/
|
||||
public static function getOwnerKey(string $permission): ?string
|
||||
{
|
||||
$cached = self::getPermissionScopeData($permission);
|
||||
|
||||
return $cached['owner_key'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 해당 권한의 resource_route_key를 조회합니다 (static 캐시).
|
||||
*
|
||||
* @param string $permission 권한 식별자
|
||||
* @return string|null 리소스 라우트 파라미터명
|
||||
*/
|
||||
public static function getResourceRouteKey(string $permission): ?string
|
||||
{
|
||||
$cached = self::getPermissionScopeData($permission);
|
||||
|
||||
return $cached['resource_route_key'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 엔드포인트의 쿼리에 권한 스코프 필터를 적용합니다.
|
||||
*
|
||||
* @param Builder $query Eloquent 쿼리 빌더
|
||||
* @param string $permission 권한 식별자
|
||||
* @param User|null $user 사용자 (null이면 현재 인증 사용자)
|
||||
* @return void
|
||||
*/
|
||||
public static function applyPermissionScope(Builder $query, string $permission, ?User $user = null): void
|
||||
{
|
||||
$user = $user ?? Auth::user();
|
||||
|
||||
if (! $user) {
|
||||
return;
|
||||
}
|
||||
|
||||
$effectiveScope = $user->getEffectiveScopeForPermission($permission);
|
||||
|
||||
if ($effectiveScope === null) {
|
||||
return; // 전체 접근
|
||||
}
|
||||
|
||||
$ownerKey = self::getOwnerKey($permission);
|
||||
|
||||
if (! $ownerKey) {
|
||||
return; // owner_key 없음 → 스코프 체크 불필요
|
||||
}
|
||||
|
||||
if ($effectiveScope === 'self') {
|
||||
$query->where($ownerKey, $user->id);
|
||||
} elseif ($effectiveScope === 'role') {
|
||||
$myRoleIds = $user->roles()->pluck('roles.id');
|
||||
$query->whereIn($ownerKey, function ($sub) use ($myRoleIds) {
|
||||
$sub->select('user_id')
|
||||
->from('user_roles')
|
||||
->whereIn('role_id', $myRoleIds);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 상세 엔드포인트의 모델에 대한 스코프 접근 권한을 체크합니다.
|
||||
*
|
||||
* @param Model $model 대상 모델
|
||||
* @param string $permission 권한 식별자
|
||||
* @param User|null $user 사용자 (null이면 현재 인증 사용자)
|
||||
* @return bool 접근 허용 여부
|
||||
*/
|
||||
public static function checkScopeAccess(Model $model, string $permission, ?User $user = null): bool
|
||||
{
|
||||
$user = $user ?? Auth::user();
|
||||
|
||||
if (! $user) {
|
||||
return true; // 비인증 사용자는 스코프 체크 스킵 (권한 체크는 미들웨어)
|
||||
}
|
||||
|
||||
$scopeData = self::getPermissionScopeData($permission);
|
||||
$resourceRouteKey = $scopeData['resource_route_key'];
|
||||
$ownerKey = $scopeData['owner_key'];
|
||||
|
||||
// resource_route_key 또는 owner_key가 없으면 스코프 체크 불필요
|
||||
if (! $resourceRouteKey || ! $ownerKey) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$effectiveScope = $user->getEffectiveScopeForPermission($permission);
|
||||
|
||||
// scope=null → 전체 접근
|
||||
if ($effectiveScope === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$resourceOwnerId = $model->{$ownerKey};
|
||||
|
||||
if ($effectiveScope === 'self') {
|
||||
return $resourceOwnerId !== null && (int) $resourceOwnerId === (int) $user->id;
|
||||
}
|
||||
|
||||
if ($effectiveScope === 'role') {
|
||||
if ($resourceOwnerId === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$myRoleIds = $user->roles()->pluck('roles.id');
|
||||
|
||||
return DB::table('user_roles')
|
||||
->where('user_id', $resourceOwnerId)
|
||||
->whereIn('role_id', $myRoleIds)
|
||||
->exists();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission 스코프 데이터를 static 캐시와 함께 조회합니다.
|
||||
*
|
||||
* @param string $permission 권한 식별자
|
||||
* @return array{resource_route_key: string|null, owner_key: string|null}
|
||||
*/
|
||||
protected static function getPermissionScopeData(string $permission): array
|
||||
{
|
||||
if (! isset(self::$permissionCache[$permission])) {
|
||||
$data = Permission::where('identifier', $permission)
|
||||
->select('resource_route_key', 'owner_key')
|
||||
->first();
|
||||
|
||||
self::$permissionCache[$permission] = [
|
||||
'resource_route_key' => $data?->resource_route_key,
|
||||
'owner_key' => $data?->owner_key,
|
||||
];
|
||||
}
|
||||
|
||||
return self::$permissionCache[$permission];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
<?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;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class ResponseHelper
|
||||
{
|
||||
/**
|
||||
* 성공 응답을 생성합니다.
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 실패 응답을 생성합니다.
|
||||
*
|
||||
* @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 !== null) {
|
||||
$response['errors'] = $errors;
|
||||
}
|
||||
|
||||
return response()->json($response, $statusCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 입력 검증 실패 응답을 생성합니다.
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 실패 응답을 생성합니다.
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 부족 응답을 생성합니다.
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스를 찾을 수 없음 응답을 생성합니다.
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 서버 내부 오류 응답을 생성합니다.
|
||||
*
|
||||
* @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 !== null && config('app.debug')) {
|
||||
$response['error'] = $error;
|
||||
}
|
||||
|
||||
return response()->json($response, 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 메시지를 변환합니다.
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 언어 설정을 가져옵니다.
|
||||
*
|
||||
* @return string 사용자 언어 코드 (ko, en)
|
||||
*/
|
||||
private static function getUserLocale(): string
|
||||
{
|
||||
// 인증된 사용자의 언어 설정 확인
|
||||
if (Auth::check() && Auth::user()->language) {
|
||||
return Auth::user()->language;
|
||||
}
|
||||
|
||||
// 헤더에서 언어 설정 확인
|
||||
$acceptLanguage = request()->header('Accept-Language');
|
||||
if ($acceptLanguage) {
|
||||
$locale = self::parseAcceptLanguage($acceptLanguage);
|
||||
if (in_array($locale, ['ko', 'en'])) {
|
||||
return $locale;
|
||||
}
|
||||
}
|
||||
|
||||
// 기본값 반환
|
||||
return config('app.locale', 'ko');
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept-Language HTTP 헤더를 파싱합니다.
|
||||
*
|
||||
* @param string $acceptLanguage Accept-Language 헤더 값
|
||||
* @return string 파싱된 언어 코드
|
||||
*/
|
||||
private static function parseAcceptLanguage(string $acceptLanguage): string
|
||||
{
|
||||
$languages = explode(',', $acceptLanguage);
|
||||
$firstLanguage = trim($languages[0]);
|
||||
|
||||
// 언어-지역 형태에서 언어만 추출 (예: ko-KR -> ko)
|
||||
if (strpos($firstLanguage, '-') !== false) {
|
||||
return explode('-', $firstLanguage)[0];
|
||||
}
|
||||
|
||||
return $firstLanguage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈별 성공 응답을 생성합니다.
|
||||
*
|
||||
* @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를 사용한 성공 응답을 생성합니다.
|
||||
*
|
||||
* @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;
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => self::trans($messageKey, $messageParams, $domain),
|
||||
'data' => $data
|
||||
], $statusCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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|null $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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\App;
|
||||
|
||||
/**
|
||||
* 타임존 변환 헬퍼
|
||||
*
|
||||
* Service, Listener 등 BaseApiResource 외부에서
|
||||
* 사용자 타임존으로 datetime을 변환할 때 사용합니다.
|
||||
*/
|
||||
class TimezoneHelper
|
||||
{
|
||||
/**
|
||||
* 현재 요청의 사용자 타임존을 반환합니다.
|
||||
*
|
||||
* SetTimezone 미들웨어에서 설정한 값을 사용하며,
|
||||
* 미설정 시 config 기본값을 반환합니다.
|
||||
*
|
||||
* @return string 타임존 (예: 'Asia/Seoul')
|
||||
*/
|
||||
public static function getUserTimezone(): string
|
||||
{
|
||||
if (App::bound('user_timezone')) {
|
||||
return App::make('user_timezone');
|
||||
}
|
||||
|
||||
return config('app.default_user_timezone', 'Asia/Seoul');
|
||||
}
|
||||
|
||||
/**
|
||||
* Carbon datetime을 사용자 타임존 ISO8601 문자열로 변환합니다.
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null ISO8601 문자열
|
||||
*/
|
||||
public static function toUserTimezone(?Carbon $datetime): ?string
|
||||
{
|
||||
if (! $datetime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $datetime->copy()->setTimezone(static::getUserTimezone())->toIso8601String();
|
||||
}
|
||||
|
||||
/**
|
||||
* Carbon datetime을 사용자 타임존 Y-m-d H:i:s 문자열로 변환합니다.
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d H:i:s 형식
|
||||
*/
|
||||
public static function toUserDateTimeString(?Carbon $datetime): ?string
|
||||
{
|
||||
if (! $datetime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $datetime->copy()->setTimezone(static::getUserTimezone())->format('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
/**
|
||||
* Carbon datetime을 사용자 타임존 Y-m-d 문자열로 변환합니다.
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d 형식
|
||||
*/
|
||||
public static function toUserDateString(?Carbon $datetime): ?string
|
||||
{
|
||||
if (! $datetime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $datetime->copy()->setTimezone(static::getUserTimezone())->format('Y-m-d');
|
||||
}
|
||||
|
||||
/**
|
||||
* Carbon datetime을 사용자 타임존의 Carbon 인스턴스로 변환합니다.
|
||||
*
|
||||
* diffForHumans(), isToday() 등 후속 조작이 필요한 경우 사용합니다.
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return Carbon|null 사용자 타임존 Carbon
|
||||
*/
|
||||
public static function toUserCarbon(?Carbon $datetime): ?Carbon
|
||||
{
|
||||
if (! $datetime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $datetime->copy()->setTimezone(static::getUserTimezone());
|
||||
}
|
||||
|
||||
/**
|
||||
* 사이트 기본 타임존을 반환합니다.
|
||||
*
|
||||
* 쿠폰 유효기간 등 사이트 전체에 일관된 기준이 필요한 날짜 변환에 사용합니다.
|
||||
*
|
||||
* @return string 타임존 (예: 'Asia/Seoul')
|
||||
*/
|
||||
public static function getSiteTimezone(): string
|
||||
{
|
||||
return config('app.default_user_timezone');
|
||||
}
|
||||
|
||||
/**
|
||||
* Carbon datetime을 사이트 기본 타임존 Y-m-d 문자열로 변환합니다.
|
||||
*
|
||||
* 사용자 타임존이 아닌 사이트 기준 날짜를 반환합니다.
|
||||
* 쿠폰 유효기간 등 사이트 전체에 일관된 기준이 필요한 경우 사용합니다.
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d 형식
|
||||
*/
|
||||
public static function toSiteDateString(?Carbon $datetime): ?string
|
||||
{
|
||||
if (! $datetime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $datetime->copy()->setTimezone(static::getSiteTimezone())->format('Y-m-d');
|
||||
}
|
||||
|
||||
/**
|
||||
* 날짜 문자열을 사이트 기본 타임존 기준 하루 시작(00:00:00)으로 해석하여 UTC Carbon을 반환합니다.
|
||||
*
|
||||
* 예: '2026-03-15' + Asia/Seoul → 2026-03-15 00:00:00 KST → 2026-03-14 15:00:00 UTC
|
||||
*
|
||||
* @param string|null $dateString Y-m-d 형식 날짜 문자열
|
||||
* @return Carbon|null UTC Carbon 인스턴스
|
||||
*/
|
||||
public static function fromSiteDateStartOfDay(?string $dateString): ?Carbon
|
||||
{
|
||||
if (! $dateString) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Carbon::createFromFormat('Y-m-d', $dateString, static::getSiteTimezone())
|
||||
->startOfDay()
|
||||
->utc();
|
||||
}
|
||||
|
||||
/**
|
||||
* 날짜 문자열을 사이트 기본 타임존 기준 하루 끝(23:59:59)으로 해석하여 UTC Carbon을 반환합니다.
|
||||
*
|
||||
* 예: '2026-03-20' + Asia/Seoul → 2026-03-20 23:59:59 KST → 2026-03-20 14:59:59 UTC
|
||||
*
|
||||
* @param string|null $dateString Y-m-d 형식 날짜 문자열
|
||||
* @return Carbon|null UTC Carbon 인스턴스
|
||||
*/
|
||||
public static function fromSiteDateEndOfDay(?string $dateString): ?Carbon
|
||||
{
|
||||
if (! $dateString) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Carbon::createFromFormat('Y-m-d', $dateString, static::getSiteTimezone())
|
||||
->setTime(23, 59, 59)
|
||||
->utc();
|
||||
}
|
||||
|
||||
/**
|
||||
* Carbon datetime을 사이트 기본 타임존 datetime-local 입력 호환 문자열로 변환합니다.
|
||||
*
|
||||
* HTML <input type="datetime-local">은 'Y-m-d\TH:i' 형식을 요구합니다.
|
||||
*
|
||||
* 예: 2026-03-14 15:00:00 UTC → 2026-03-15T00:00 (Asia/Seoul)
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d\TH:i 형식
|
||||
*/
|
||||
public static function toSiteDateTimeLocalString(?Carbon $datetime): ?string
|
||||
{
|
||||
if (! $datetime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $datetime->copy()->setTimezone(static::getSiteTimezone())->format('Y-m-d\TH:i');
|
||||
}
|
||||
|
||||
/**
|
||||
* datetime-local 입력값을 사이트 기본 타임존 기준으로 해석하여 UTC Carbon을 반환합니다.
|
||||
*
|
||||
* 예: '2026-03-15T09:30' + Asia/Seoul → 2026-03-15 09:30:00 KST → 2026-03-15 00:30:00 UTC
|
||||
*
|
||||
* @param string|null $dateTimeString Y-m-d\TH:i 또는 Y-m-d H:i 형식
|
||||
* @return Carbon|null UTC Carbon 인스턴스
|
||||
*/
|
||||
public static function fromSiteDateTime(?string $dateTimeString): ?Carbon
|
||||
{
|
||||
if (! $dateTimeString) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// datetime-local은 'Y-m-d\TH:i' 형식이지만, 'Y-m-d H:i:s' 등도 허용
|
||||
$normalized = str_replace('T', ' ', $dateTimeString);
|
||||
|
||||
return Carbon::parse($normalized, static::getSiteTimezone())->utc();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
use App\Services\ModuleSettingsService;
|
||||
|
||||
if (! function_exists('module_setting')) {
|
||||
/**
|
||||
* 모듈 설정값 조회 헬퍼 함수
|
||||
*
|
||||
* ModuleSettingsService를 통해 모듈 설정을 조회합니다.
|
||||
* 모듈별 설정 서비스(예: EcommerceSettingsService)가 존재하면 자동으로 위임합니다.
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자 (예: 'sirsoft-ecommerce')
|
||||
* @param string|null $key 설정 키 (null이면 전체 설정, 도트 노테이션 지원)
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값
|
||||
*
|
||||
* @example
|
||||
* // 특정 설정값 조회
|
||||
* $itemsPerPage = module_setting('sirsoft-ecommerce', 'product.items_per_page', 20);
|
||||
*
|
||||
* @example
|
||||
* // 전체 설정 조회
|
||||
* $allSettings = module_setting('sirsoft-ecommerce');
|
||||
*/
|
||||
function module_setting(string $moduleIdentifier, ?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
try {
|
||||
$service = app(ModuleSettingsService::class);
|
||||
|
||||
return $service->get($moduleIdentifier, $key, $default);
|
||||
} catch (Throwable) {
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('module_settings')) {
|
||||
/**
|
||||
* 모듈 전체 설정 조회 헬퍼 함수
|
||||
*
|
||||
* @param string $moduleIdentifier 모듈 식별자 (예: 'sirsoft-ecommerce')
|
||||
* @param string|null $category 카테고리명 (null이면 전체 설정)
|
||||
* @return array 설정값 배열
|
||||
*
|
||||
* @example
|
||||
* // 전체 설정 조회
|
||||
* $allSettings = module_settings('sirsoft-ecommerce');
|
||||
*
|
||||
* @example
|
||||
* // 상품 카테고리 설정만 조회
|
||||
* $productSettings = module_settings('sirsoft-ecommerce', 'product');
|
||||
*/
|
||||
function module_settings(string $moduleIdentifier, ?string $category = null): array
|
||||
{
|
||||
try {
|
||||
$service = app(ModuleSettingsService::class);
|
||||
|
||||
if ($category !== null) {
|
||||
return $service->get($moduleIdentifier, $category, []);
|
||||
}
|
||||
|
||||
return $service->get($moduleIdentifier) ?? [];
|
||||
} catch (Throwable) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
use App\Services\PluginSettingsService;
|
||||
|
||||
if (! function_exists('plugin_setting')) {
|
||||
/**
|
||||
* 플러그인 설정값 조회 헬퍼 함수
|
||||
*
|
||||
* @param string $pluginIdentifier 플러그인 식별자 (예: 'sirsoft-daum_postcode')
|
||||
* @param string|null $key 설정 키 (null이면 전체 설정, 도트 노테이션 지원)
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값
|
||||
*
|
||||
* @example
|
||||
* // 특정 설정값 조회
|
||||
* $displayMode = plugin_setting('sirsoft-daum_postcode', 'display_mode', 'layer');
|
||||
*
|
||||
* @example
|
||||
* // 전체 설정 조회
|
||||
* $allSettings = plugin_setting('sirsoft-daum_postcode');
|
||||
*/
|
||||
function plugin_setting(string $pluginIdentifier, ?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
try {
|
||||
$service = app(PluginSettingsService::class);
|
||||
|
||||
return $service->get($pluginIdentifier, $key, $default);
|
||||
} catch (Throwable) {
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('plugin_settings')) {
|
||||
/**
|
||||
* 플러그인 전체 설정 조회 헬퍼 함수
|
||||
*
|
||||
* @param string $pluginIdentifier 플러그인 식별자 (예: 'sirsoft-daum_postcode')
|
||||
* @return array 설정값 배열
|
||||
*
|
||||
* @example
|
||||
* // 전체 설정 조회
|
||||
* $settings = plugin_settings('sirsoft-daum_postcode');
|
||||
*/
|
||||
function plugin_settings(string $pluginIdentifier): array
|
||||
{
|
||||
try {
|
||||
$service = app(PluginSettingsService::class);
|
||||
|
||||
return $service->get($pluginIdentifier) ?? [];
|
||||
} catch (Throwable) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Config;
|
||||
|
||||
if (! function_exists('g7_settings')) {
|
||||
/**
|
||||
* 그누보드7 통합 환경설정 조회 헬퍼 함수
|
||||
*
|
||||
* 코어, 모듈, 플러그인의 환경설정을 통합하여 조회합니다.
|
||||
* 부트스트랩 시점에 로드된 설정값을 Config에서 읽어옵니다.
|
||||
*
|
||||
* @param string|null $key 설정 키 (dot notation)
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값 또는 전체 설정 배열
|
||||
*
|
||||
* @example
|
||||
* // 코어 메일 설정 조회
|
||||
* $mailHost = g7_settings('core.mail.host');
|
||||
*
|
||||
* @example
|
||||
* // 모듈 설정 조회
|
||||
* $shopName = g7_settings('modules.sirsoft-ecommerce.basic_info.shop_name');
|
||||
*
|
||||
* @example
|
||||
* // 플러그인 설정 조회
|
||||
* $displayMode = g7_settings('plugins.sirsoft-daum_postcode.display_mode');
|
||||
*
|
||||
* @example
|
||||
* // 전체 설정 조회
|
||||
* $allSettings = g7_settings();
|
||||
*/
|
||||
function g7_settings(?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
if ($key === null) {
|
||||
return Config::get('g7_settings', []);
|
||||
}
|
||||
|
||||
return Config::get("g7_settings.{$key}", $default);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('g7_core_settings')) {
|
||||
/**
|
||||
* 그누보드7 코어 환경설정 조회 헬퍼 함수
|
||||
*
|
||||
* @param string|null $key 설정 키 (dot notation)
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값
|
||||
*
|
||||
* @example
|
||||
* // 메일 호스트 조회
|
||||
* $mailHost = g7_core_settings('mail.host');
|
||||
*
|
||||
* @example
|
||||
* // 사이트명 조회
|
||||
* $siteName = g7_core_settings('general.site_name');
|
||||
*/
|
||||
function g7_core_settings(?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
if ($key === null) {
|
||||
return Config::get('g7_settings.core', []);
|
||||
}
|
||||
|
||||
return Config::get("g7_settings.core.{$key}", $default);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('g7_module_settings')) {
|
||||
/**
|
||||
* 그누보드7 모듈 환경설정 조회 헬퍼 함수
|
||||
*
|
||||
* @param string $identifier 모듈 식별자 (예: 'sirsoft-ecommerce')
|
||||
* @param string|null $key 설정 키 (dot notation)
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값
|
||||
*
|
||||
* @example
|
||||
* // 이커머스 모듈의 쇼핑몰명 조회
|
||||
* $shopName = g7_module_settings('sirsoft-ecommerce', 'basic_info.shop_name');
|
||||
*
|
||||
* @example
|
||||
* // 모듈 전체 설정 조회
|
||||
* $allSettings = g7_module_settings('sirsoft-ecommerce');
|
||||
*/
|
||||
function g7_module_settings(string $identifier, ?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
if ($key === null) {
|
||||
return Config::get("g7_settings.modules.{$identifier}", []);
|
||||
}
|
||||
|
||||
return Config::get("g7_settings.modules.{$identifier}.{$key}", $default);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('g7_plugin_settings')) {
|
||||
/**
|
||||
* 그누보드7 플러그인 환경설정 조회 헬퍼 함수
|
||||
*
|
||||
* @param string $identifier 플러그인 식별자 (예: 'sirsoft-daum_postcode')
|
||||
* @param string|null $key 설정 키 (dot notation)
|
||||
* @param mixed $default 기본값
|
||||
* @return mixed 설정값
|
||||
*
|
||||
* @example
|
||||
* // 다음 우편번호 플러그인의 표시 모드 조회
|
||||
* $displayMode = g7_plugin_settings('sirsoft-daum_postcode', 'display_mode');
|
||||
*
|
||||
* @example
|
||||
* // 플러그인 전체 설정 조회
|
||||
* $allSettings = g7_plugin_settings('sirsoft-daum_postcode');
|
||||
*/
|
||||
function g7_plugin_settings(string $identifier, ?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
if ($key === null) {
|
||||
return Config::get("g7_settings.plugins.{$identifier}", []);
|
||||
}
|
||||
|
||||
return Config::get("g7_settings.plugins.{$identifier}.{$key}", $default);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user