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,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Services\LayoutPreviewService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
/**
|
||||
* 공개 레이아웃 미리보기 API 컨트롤러
|
||||
*
|
||||
* 토큰 기반으로 미리보기 레이아웃 JSON을 서빙합니다.
|
||||
* 인증 불필요 (토큰이 보안 메커니즘).
|
||||
*/
|
||||
class LayoutPreviewController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* LayoutPreviewService 주입
|
||||
*
|
||||
* @param LayoutPreviewService $layoutPreviewService 미리보기 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private LayoutPreviewService $layoutPreviewService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 미리보기 레이아웃 JSON 서빙
|
||||
*
|
||||
* 토큰으로 편집 중인 레이아웃을 조회하고, 상속 병합 및 extension 적용 후 반환합니다.
|
||||
*
|
||||
* @param string $token 미리보기 토큰 (UUID)
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function serve(string $token): JsonResponse
|
||||
{
|
||||
$layout = $this->layoutPreviewService->getPreviewLayout($token);
|
||||
|
||||
if (! $layout) {
|
||||
return $this->notFound(__('templates.layout_not_found'));
|
||||
}
|
||||
|
||||
return response()->json($layout);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Services\AttachmentService;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* 첨부파일 다운로드 컨트롤러
|
||||
*
|
||||
* 권한 정책에 따라 로그인/비로그인 사용자 모두 접근 가능합니다.
|
||||
* 권한 체크는 AttachmentService에서 하이브리드 방식으로 처리합니다.
|
||||
*/
|
||||
class PublicAttachmentController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* PublicAttachmentController 생성자
|
||||
*
|
||||
* @param AttachmentService $attachmentService 첨부파일 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private AttachmentService $attachmentService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부파일 다운로드
|
||||
*
|
||||
* 이미지 파일은 캐싱 헤더와 함께 인라인 표시하고,
|
||||
* 그 외 파일은 다운로드 방식으로 제공합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $hash 첨부파일 해시 (12자)
|
||||
* @return BinaryFileResponse|StreamedResponse|Response|JsonResponse 파일 응답 또는 에러 응답
|
||||
*/
|
||||
public function download(Request $request, string $hash): BinaryFileResponse|StreamedResponse|Response|JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
try {
|
||||
// 파일 정보 조회 (권한 체크 포함)
|
||||
$fileInfo = $this->attachmentService->getFileInfo($hash, $user);
|
||||
|
||||
if (!$fileInfo) {
|
||||
$attachment = $this->attachmentService->findByHash($hash);
|
||||
|
||||
if (!$attachment) {
|
||||
return $this->notFound('attachment.not_found');
|
||||
}
|
||||
|
||||
return $this->forbidden('attachment.access_denied');
|
||||
}
|
||||
|
||||
// 이미지 파일은 캐싱 헤더와 함께 응답 (환경설정 레이아웃 캐시 TTL 사용, 기본 24시간)
|
||||
if (str_starts_with($fileInfo['mime_type'], 'image/')) {
|
||||
return $this->fileResponse(
|
||||
$fileInfo['path'],
|
||||
$fileInfo['mime_type'],
|
||||
(int) g7_core_settings('cache.layout_ttl', 86400)
|
||||
);
|
||||
}
|
||||
|
||||
// 이미지가 아닌 파일은 기존 다운로드 방식 유지
|
||||
$response = $this->attachmentService->download($hash, $user);
|
||||
|
||||
if (!$response) {
|
||||
return $this->forbidden('attachment.access_denied');
|
||||
}
|
||||
|
||||
return $response;
|
||||
} catch (AuthorizationException) {
|
||||
return $this->forbidden('attachment.access_denied');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Services\LayoutService;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
/**
|
||||
* 공개 레이아웃 API 컨트롤러
|
||||
*
|
||||
* 템플릿 레이아웃 JSON을 프론트엔드에 제공합니다.
|
||||
*/
|
||||
class PublicLayoutController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* 레이아웃 캐시 TTL (초)
|
||||
*/
|
||||
private const CACHE_TTL = 3600;
|
||||
|
||||
/**
|
||||
* TemplateService 및 LayoutService 주입
|
||||
*/
|
||||
public function __construct(
|
||||
private TemplateService $templateService,
|
||||
private LayoutService $layoutService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 병합된 레이아웃 JSON 서빙
|
||||
*
|
||||
* HTTP 캐시 헤더 및 ETag를 지원하여 전송 효율성을 높입니다.
|
||||
* 사용자 권한에 따라 컴포넌트를 필터링하여 서빙합니다.
|
||||
*
|
||||
* @param string $templateIdentifier 템플릿 식별자
|
||||
* @param string $layoutName 레이아웃 이름
|
||||
* @return JsonResponse|Response JSON 응답 또는 304 Not Modified
|
||||
*/
|
||||
public function serve(string $templateIdentifier, string $layoutName): JsonResponse|Response
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage("layouts/{$templateIdentifier}/{$layoutName}", [
|
||||
'identifier' => $templateIdentifier,
|
||||
'layout_name' => $layoutName,
|
||||
]);
|
||||
|
||||
// 1. 템플릿 조회 (활성화 여부 확인)
|
||||
$template = $this->templateService->findByIdentifier($templateIdentifier);
|
||||
|
||||
// 템플릿이 존재하지 않거나 활성화되지 않은 경우
|
||||
if (! $template || $template->status !== ExtensionStatus::Active->value) {
|
||||
return $this->notFound(__('templates.layout_not_found'));
|
||||
}
|
||||
|
||||
try {
|
||||
// 캐시 버전을 키에 포함하여 모듈/플러그인 변경 시 캐시 무효화
|
||||
$cacheVersion = request()->query('v', 0);
|
||||
|
||||
// 서버 측 캐싱 (1시간 유효)
|
||||
// getLayout()을 사용하여 레이아웃 로드, 병합, 확장 적용을 한 번에 수행
|
||||
$mergedLayout = $this->cached(
|
||||
"layout.{$templateIdentifier}.{$layoutName}.v{$cacheVersion}",
|
||||
fn () => $this->layoutService->getLayout($templateIdentifier, $layoutName),
|
||||
self::CACHE_TTL
|
||||
);
|
||||
|
||||
// 권한 체크 (permissions 필드가 있는 경우)
|
||||
$permissionCheckResult = $this->checkLayoutPermissions($mergedLayout);
|
||||
if ($permissionCheckResult !== null) {
|
||||
return $permissionCheckResult;
|
||||
}
|
||||
|
||||
// 컴포넌트별 권한 필터링 (post-cache, 사용자별 동적 처리)
|
||||
$mergedLayout = $this->layoutService->filterComponentsByPermissions(
|
||||
$mergedLayout,
|
||||
request()->user()
|
||||
);
|
||||
|
||||
// ETag 및 Cache-Control 헤더와 함께 응답 반환
|
||||
return $this->successWithCache(
|
||||
'templates.messages.layout_served',
|
||||
$mergedLayout,
|
||||
self::CACHE_TTL
|
||||
);
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
|
||||
// 레이아웃 또는 부모 레이아웃을 찾을 수 없음 - 예외 메시지 전달
|
||||
return $this->notFound($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 권한 체크
|
||||
*
|
||||
* 레이아웃에 permissions 필드가 있으면 권한을 체크합니다.
|
||||
* flat array(AND), 구조화 객체(OR/AND 중첩) 모두 지원합니다.
|
||||
*
|
||||
* @param array $layout 병합된 레이아웃 데이터
|
||||
* @return JsonResponse|null 권한 없으면 에러 응답, 있으면 null
|
||||
*/
|
||||
private function checkLayoutPermissions(array $layout): ?JsonResponse
|
||||
{
|
||||
$permissions = $layout['permissions'] ?? [];
|
||||
|
||||
// 권한 요구사항 없음 (공개 레이아웃)
|
||||
if (empty($permissions)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 구조화된 권한 로직(OR/AND) 지원
|
||||
if (! PermissionHelper::checkWithLogic($permissions)) {
|
||||
$user = request()->user();
|
||||
$permissionList = $this->flattenPermissionList($permissions);
|
||||
|
||||
// 비회원이면 401, 회원이면 403
|
||||
if ($user === null) {
|
||||
return $this->unauthorized('auth.layout_guest_permission_denied', [
|
||||
'required_permissions' => $permissionList,
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->forbidden('auth.layout_permission_denied', [
|
||||
'required_permissions' => $permissionList,
|
||||
]);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 구조에서 모든 권한 식별자를 평탄화하여 문자열로 반환합니다.
|
||||
*
|
||||
* 에러 메시지에 필요한 권한 목록을 표시하기 위해 사용합니다.
|
||||
*
|
||||
* @param array $permissions 권한 구조 (flat array 또는 구조화 객체)
|
||||
* @return string 쉼표로 구분된 권한 식별자 문자열
|
||||
*/
|
||||
private function flattenPermissionList(array $permissions): string
|
||||
{
|
||||
$flat = [];
|
||||
array_walk_recursive($permissions, function ($value) use (&$flat) {
|
||||
if (is_string($value)) {
|
||||
$flat[] = $value;
|
||||
}
|
||||
});
|
||||
|
||||
return implode(', ', array_unique($flat));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Http\Requests\Public\Module\ServeModuleAssetRequest;
|
||||
use App\Services\ModuleService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
* 공개 모듈 API 컨트롤러
|
||||
*
|
||||
* 모듈 에셋 서빙을 담당합니다.
|
||||
*/
|
||||
class PublicModuleController extends PublicBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ModuleService $moduleService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 에셋 서빙
|
||||
*
|
||||
* @param ServeModuleAssetRequest $request 검증된 요청 (경로, 확장자 검증 완료)
|
||||
* @param string $identifier 모듈 식별자 (vendor-module 형식)
|
||||
* @param string $path 에셋 경로 (dist/js/module.iife.js 등)
|
||||
* @return BinaryFileResponse|JsonResponse|Response
|
||||
*/
|
||||
public function serveAsset(
|
||||
ServeModuleAssetRequest $request,
|
||||
string $identifier,
|
||||
string $path
|
||||
): BinaryFileResponse|JsonResponse|Response {
|
||||
// FormRequest에서 이미 보안 검증 완료
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('modules.assets', ['identifier' => $identifier, 'path' => $path]);
|
||||
|
||||
// Service에서 파일 경로 조회 (검증은 FormRequest에서 완료됨)
|
||||
$result = $this->moduleService->getAssetFilePath($identifier, $path);
|
||||
|
||||
// 에러 처리
|
||||
if (! $result['success']) {
|
||||
return match ($result['error']) {
|
||||
'module_not_found' => $this->notFound(__('modules.errors.not_found', ['module' => $identifier])),
|
||||
'file_not_found' => $this->notFound(__('modules.errors.file_not_found')),
|
||||
'file_type_not_allowed' => $this->forbidden(__('modules.errors.file_type_not_allowed')),
|
||||
default => $this->error(__('modules.errors.unknown_error'), 500),
|
||||
};
|
||||
}
|
||||
|
||||
// 파일 반환 (ETag 및 환경별 캐싱 헤더 포함, 1년 캐시)
|
||||
return $this->fileResponse($result['filePath'], $result['mimeType'], 31536000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Http\Requests\Public\Plugin\ServePluginAssetRequest;
|
||||
use App\Services\PluginService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
* 공개 플러그인 API 컨트롤러
|
||||
*
|
||||
* 플러그인 에셋 서빙을 담당합니다.
|
||||
*/
|
||||
class PublicPluginController extends PublicBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PluginService $pluginService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 에셋 서빙
|
||||
*
|
||||
* @param ServePluginAssetRequest $request 검증된 요청 (경로, 확장자 검증 완료)
|
||||
* @param string $identifier 플러그인 식별자 (vendor-plugin 형식)
|
||||
* @param string $path 에셋 경로 (dist/js/plugin.iife.js 등)
|
||||
* @return BinaryFileResponse|JsonResponse|Response
|
||||
*/
|
||||
public function serveAsset(
|
||||
ServePluginAssetRequest $request,
|
||||
string $identifier,
|
||||
string $path
|
||||
): BinaryFileResponse|JsonResponse|Response {
|
||||
// FormRequest에서 이미 보안 검증 완료
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('plugins.assets', ['identifier' => $identifier, 'path' => $path]);
|
||||
|
||||
// Service에서 파일 경로 조회 (검증은 FormRequest에서 완료됨)
|
||||
$result = $this->pluginService->getAssetFilePath($identifier, $path);
|
||||
|
||||
// 에러 처리
|
||||
if (! $result['success']) {
|
||||
return match ($result['error']) {
|
||||
'plugin_not_found' => $this->notFound(__('plugins.errors.not_found', ['plugin' => $identifier])),
|
||||
'file_not_found' => $this->notFound(__('plugins.errors.file_not_found')),
|
||||
'file_type_not_allowed' => $this->forbidden(__('plugins.errors.file_type_not_allowed')),
|
||||
default => $this->error(__('plugins.errors.unknown_error'), 500),
|
||||
};
|
||||
}
|
||||
|
||||
// 파일 반환 (ETag 및 환경별 캐싱 헤더 포함, 1년 캐시)
|
||||
return $this->fileResponse($result['filePath'], $result['mimeType'], 31536000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Models\User;
|
||||
use App\Services\UserService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
/**
|
||||
* 공개 사용자 프로필 컨트롤러
|
||||
*
|
||||
* 타인의 공개 프로필 정보를 조회하는 API를 제공합니다.
|
||||
* 인증 없이 접근 가능합니다.
|
||||
*
|
||||
* 게시글 관련 API는 게시판 모듈(sirsoft-board)에서 제공합니다:
|
||||
* - 게시글 목록: GET /api/modules/sirsoft-board/users/{userId}/posts
|
||||
* - 게시글 통계: GET /api/modules/sirsoft-board/users/{userId}/posts/stats
|
||||
*/
|
||||
class PublicProfileController extends PublicBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private UserService $userService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 공개 프로필을 조회합니다.
|
||||
*
|
||||
* 사용자 상태에 따라 차등 데이터를 반환합니다:
|
||||
* - active: 전체 정보 (name, avatar, bio, created_at)
|
||||
* - inactive: 기본 정보만 (bio 제외)
|
||||
* - blocked: 최소 정보만 (avatar, bio, created_at 제외)
|
||||
* - withdrawn/미존재: 404 에러
|
||||
*
|
||||
* 게시글 통계(posts_count, comments_count)는 게시판 모듈 API를 통해 별도 조회합니다.
|
||||
*
|
||||
* @param User $user 사용자 모델 (Route Model Binding, uuid 기반)
|
||||
* @return JsonResponse 공개 프로필 정보
|
||||
*/
|
||||
public function show(User $user): JsonResponse
|
||||
{
|
||||
$profileData = $this->userService->getPublicProfile($user->id);
|
||||
|
||||
if ($profileData === null) {
|
||||
return $this->error('user.not_found', 404);
|
||||
}
|
||||
|
||||
return $this->success('user.profile_success', $profileData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Http\Requests\Public\SearchRequest;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
/**
|
||||
* 통합 검색 API 컨트롤러
|
||||
*
|
||||
* 코어에서 검색 기반 구조를 제공하고,
|
||||
* 각 모듈이 Filter Hook을 통해 검색 결과를 추가합니다.
|
||||
*/
|
||||
class PublicSearchController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* 통합 검색 수행
|
||||
*
|
||||
* @param SearchRequest $request HTTP 요청
|
||||
* @return JsonResponse 검색 결과
|
||||
*/
|
||||
public function search(SearchRequest $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
|
||||
$q = trim($validated['q'] ?? '');
|
||||
$type = $validated['type'] ?? 'all';
|
||||
$sort = $validated['sort'] ?? 'relevance';
|
||||
$page = (int) ($validated['page'] ?? 1);
|
||||
$perPage = (int) ($validated['per_page'] ?? 10);
|
||||
|
||||
// 검색어가 비어있으면 빈 결과 반환
|
||||
if (empty($q)) {
|
||||
return $this->success(__('search.empty_keyword'), $this->buildEmptyResponse());
|
||||
}
|
||||
|
||||
// 검색 컨텍스트 구성 (모듈별 파라미터는 request 전체를 전달하여 각 모듈이 직접 처리)
|
||||
$context = [
|
||||
'q' => $q,
|
||||
'type' => $type,
|
||||
'sort' => $sort,
|
||||
'page' => $page,
|
||||
'per_page' => $perPage,
|
||||
'all_tab_limit' => 5,
|
||||
'user' => $request->user(),
|
||||
'request' => $request,
|
||||
];
|
||||
|
||||
// Filter Hook을 통해 각 모듈이 검색 결과 추가
|
||||
// 모듈들은 자신의 카테고리를 ['category' => ['total' => N, 'items' => [...]]] 형식으로 추가
|
||||
// 빈 배열로 시작하여 모듈이 자유롭게 카테고리 추가 가능
|
||||
$results = HookManager::applyFilters('core.search.results', [], $context);
|
||||
|
||||
// 프론트엔드용 응답 구조로 변환 (훅을 통해 모듈이 처리)
|
||||
$response = $this->buildResponse($q, $results, $context);
|
||||
|
||||
return $this->success(
|
||||
__('search.results_found', ['count' => $response['total']]),
|
||||
$response
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 검색 결과 응답 구조 생성
|
||||
*
|
||||
* @return array 빈 결과 응답
|
||||
*/
|
||||
private function buildEmptyResponse(): array
|
||||
{
|
||||
return [
|
||||
'q' => '',
|
||||
'total' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook 결과를 프론트엔드용 응답 구조로 변환
|
||||
*
|
||||
* 코어는 기본 응답 구조만 생성하고,
|
||||
* 각 모듈이 core.search.build_response 훅을 통해 자신의 카테고리 응답을 구성합니다.
|
||||
*
|
||||
* @param string $q 검색어
|
||||
* @param array $results Hook에서 반환된 검색 결과
|
||||
* @param array $context 검색 컨텍스트
|
||||
* @return array 프론트엔드용 응답 구조
|
||||
*/
|
||||
private function buildResponse(string $q, array $results, array $context): array
|
||||
{
|
||||
$response = [
|
||||
'q' => $q,
|
||||
'total' => $this->calculateTotal($results),
|
||||
];
|
||||
|
||||
// 각 모듈이 자신의 카테고리 응답 구조를 추가할 수 있도록 훅 제공
|
||||
// 모듈은 $results에서 자신의 데이터를 가져와 $response에 추가
|
||||
$response = HookManager::applyFilters('core.search.build_response', $response, $results, $context);
|
||||
|
||||
// 전체 합계를 항상 보존 (탭 UI에서 전체 건수 표시용)
|
||||
$response['all_count'] = $response['total'];
|
||||
|
||||
// 특정 탭 조회 시 total을 해당 탭의 count로 설정
|
||||
$type = $context['type'] ?? 'all';
|
||||
if ($type !== 'all') {
|
||||
$countKey = $type.'_count';
|
||||
if (isset($response[$countKey])) {
|
||||
$response['total'] = $response[$countKey];
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 검색 결과 수 계산
|
||||
*
|
||||
* @param array $results Hook에서 반환된 검색 결과
|
||||
* @return int 전체 결과 수
|
||||
*/
|
||||
private function calculateTotal(array $results): int
|
||||
{
|
||||
$total = 0;
|
||||
foreach ($results as $categoryData) {
|
||||
$total += $categoryData['total'] ?? 0;
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Enums\ExtensionStatus;
|
||||
use App\Extension\Traits\ClearsTemplateCaches;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Http\Requests\Public\Template\ServeTemplateAssetRequest;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
* 공개 템플릿 API 컨트롤러
|
||||
*/
|
||||
class PublicTemplateController extends PublicBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private TemplateService $templateService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 라우트 정보 조회 (활성화된 모듈의 routes 포함)
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자 (vendor-name 형식)
|
||||
*/
|
||||
public function getRoutes(string $identifier): JsonResponse
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.routes', ['identifier' => $identifier]);
|
||||
|
||||
// 캐시 버전을 키에 포함하여 모듈/플러그인 변경 시 캐시 무효화
|
||||
$cacheVersion = request()->query('v', 0);
|
||||
|
||||
// 캐싱된 응답 반환 (1시간 유효)
|
||||
$routesData = $this->cached(
|
||||
"template.routes.{$identifier}.v{$cacheVersion}",
|
||||
function () use ($identifier) {
|
||||
// Service에서 템플릿 + 모듈 routes 데이터 병합 조회
|
||||
$result = $this->templateService->getRoutesDataWithModules($identifier);
|
||||
|
||||
// 에러 처리
|
||||
if (! $result['success']) {
|
||||
return ['error' => $result['error']];
|
||||
}
|
||||
|
||||
return ['success' => true, 'data' => $result['data']];
|
||||
},
|
||||
3600
|
||||
);
|
||||
|
||||
// 에러 응답 처리
|
||||
if (isset($routesData['error'])) {
|
||||
return match ($routesData['error']) {
|
||||
'template_not_found' => $this->notFound(
|
||||
__('templates.errors.not_found', ['template' => $identifier])
|
||||
),
|
||||
'routes_not_found' => $this->notFound(
|
||||
__('templates.errors.routes_not_found')
|
||||
),
|
||||
'invalid_json' => $this->error(
|
||||
__('templates.errors.invalid_json'),
|
||||
500
|
||||
),
|
||||
default => $this->error(__('templates.errors.unknown_error'), 500),
|
||||
};
|
||||
}
|
||||
|
||||
// data 키 누락 시 기본 구조 반환 (캐시 오류 방어)
|
||||
if (! isset($routesData['data'])) {
|
||||
return $this->error(__('templates.errors.invalid_cache_data'), 500);
|
||||
}
|
||||
|
||||
return $this->success(
|
||||
__('templates.messages.routes_retrieved'),
|
||||
$routesData['data']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 정적 파일 서빙
|
||||
*/
|
||||
public function serveAsset(ServeTemplateAssetRequest $request, string $identifier, string $path): BinaryFileResponse|JsonResponse|Response
|
||||
{
|
||||
// FormRequest에서 이미 보안 검증 완료
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.assets', ['identifier' => $identifier, 'path' => $path]);
|
||||
|
||||
// Service에서 파일 경로 조회 (검증은 FormRequest에서 완료됨)
|
||||
$result = $this->templateService->getAssetFilePath($identifier, $path);
|
||||
|
||||
// 에러 처리
|
||||
if (! $result['success']) {
|
||||
return match ($result['error']) {
|
||||
'template_not_found' => $this->notFound(__('templates.errors.not_found', ['template' => $identifier])),
|
||||
'file_not_found' => $this->notFound(__('templates.errors.file_not_found')),
|
||||
'file_type_not_allowed' => $this->forbidden(__('templates.errors.file_type_not_allowed')),
|
||||
default => $this->error(__('templates.errors.unknown_error'), 500),
|
||||
};
|
||||
}
|
||||
|
||||
// 파일 반환 (ETag 및 환경별 캐싱 헤더 포함)
|
||||
return $this->fileResponse($result['filePath'], $result['mimeType'], 31536000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 컴포넌트 정의 파일 서빙
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
*/
|
||||
public function serveComponents(string $identifier): JsonResponse
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.components', ['identifier' => $identifier]);
|
||||
|
||||
// Service에서 파일 경로 조회 및 검증
|
||||
$result = $this->templateService->getComponentsFilePath($identifier);
|
||||
|
||||
// 에러 처리
|
||||
if (! $result['success']) {
|
||||
return match ($result['error']) {
|
||||
'template_not_found' => $this->notFound(__('templates.errors.not_found', ['template' => $identifier])),
|
||||
'components_not_found' => $this->notFound(__('templates.errors.components_not_found')),
|
||||
default => $this->error(__('templates.errors.unknown_error'), 500),
|
||||
};
|
||||
}
|
||||
|
||||
// JSON 파싱 및 반환
|
||||
$components = json_decode(file_get_contents($result['componentsPath']), true);
|
||||
|
||||
return $this->cachedJsonResponse($components, 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 설정 파일 서빙 (template.json)
|
||||
*
|
||||
* error_config 등 템플릿 메타데이터를 프론트엔드에 제공합니다.
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
*/
|
||||
public function serveConfig(string $identifier): JsonResponse
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.config', ['identifier' => $identifier]);
|
||||
|
||||
// 캐싱된 응답 반환 (1시간 유효)
|
||||
$configData = $this->cached(
|
||||
"template.config.{$identifier}",
|
||||
function () use ($identifier) {
|
||||
// 템플릿 존재 확인
|
||||
$template = $this->templateService->findByIdentifier($identifier);
|
||||
if (! $template || $template->status !== ExtensionStatus::Active->value) {
|
||||
return ['error' => 'template_not_found'];
|
||||
}
|
||||
|
||||
// template.json 파일 경로
|
||||
$configPath = base_path("templates/{$identifier}/template.json");
|
||||
|
||||
if (! file_exists($configPath)) {
|
||||
return ['error' => 'config_not_found'];
|
||||
}
|
||||
|
||||
$content = file_get_contents($configPath);
|
||||
$data = json_decode($content, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return ['error' => 'invalid_json'];
|
||||
}
|
||||
|
||||
return ['success' => true, 'data' => $data];
|
||||
},
|
||||
3600
|
||||
);
|
||||
|
||||
// 에러 응답 처리
|
||||
if (isset($configData['error'])) {
|
||||
return match ($configData['error']) {
|
||||
'template_not_found' => $this->notFound(
|
||||
__('templates.errors.not_found', ['template' => $identifier])
|
||||
),
|
||||
'config_not_found' => $this->notFound(
|
||||
__('templates.errors.template_json_not_found')
|
||||
),
|
||||
'invalid_json' => $this->error(
|
||||
__('templates.errors.invalid_json'),
|
||||
500
|
||||
),
|
||||
default => $this->error(__('templates.errors.unknown_error'), 500),
|
||||
};
|
||||
}
|
||||
|
||||
// 캐시 버전을 응답에 포함하여 프론트엔드가 API 호출 시 사용하도록 함
|
||||
$responseData = $configData['data'];
|
||||
$responseData['cache_version'] = ClearsTemplateCaches::getExtensionCacheVersion();
|
||||
|
||||
return $this->success(
|
||||
__('templates.messages.config_retrieved'),
|
||||
$responseData
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 다국어 파일 서빙 (활성화된 모듈의 다국어 데이터 포함)
|
||||
*
|
||||
* @param string $identifier 템플릿 식별자
|
||||
* @param string $locale 로케일 (ko, en 등)
|
||||
*/
|
||||
public function serveLanguage(string $identifier, string $locale): JsonResponse
|
||||
{
|
||||
// API 사용량 기록
|
||||
$this->logApiUsage('templates.language', [
|
||||
'identifier' => $identifier,
|
||||
'locale' => $locale,
|
||||
]);
|
||||
|
||||
// 캐시 버전을 키에 포함하여 모듈/플러그인 변경 시 캐시 무효화
|
||||
$cacheVersion = request()->query('v', 0);
|
||||
|
||||
// 캐싱된 응답 반환 (1시간 유효)
|
||||
$languageData = $this->cached(
|
||||
"template.language.{$identifier}.{$locale}.v{$cacheVersion}",
|
||||
function () use ($identifier, $locale) {
|
||||
// Service에서 템플릿 + 모듈 다국어 데이터 병합 조회
|
||||
$result = $this->templateService->getLanguageDataWithModules($identifier, $locale);
|
||||
|
||||
// 에러 처리
|
||||
if (! $result['success']) {
|
||||
return ['error' => $result['error']];
|
||||
}
|
||||
|
||||
return ['success' => true, 'data' => $result['data']];
|
||||
},
|
||||
3600
|
||||
);
|
||||
|
||||
// 에러 응답 처리
|
||||
if (isset($languageData['error'])) {
|
||||
return match ($languageData['error']) {
|
||||
'template_not_found' => $this->notFound(
|
||||
__('templates.errors.not_found', ['template' => $identifier])
|
||||
),
|
||||
'locale_not_supported' => $this->notFound(
|
||||
__('templates.errors.locale_not_supported', [
|
||||
'template' => $identifier,
|
||||
'locale' => $locale,
|
||||
])
|
||||
),
|
||||
'file_not_found' => $this->notFound(
|
||||
__('templates.errors.language_file_not_found', ['locale' => $locale])
|
||||
),
|
||||
'invalid_json' => $this->error(
|
||||
__('templates.errors.invalid_json'),
|
||||
500
|
||||
),
|
||||
default => $this->error(__('templates.errors.unknown_error'), 500),
|
||||
};
|
||||
}
|
||||
|
||||
// 성공 응답 (JSON 데이터 직접 반환, 래핑 없음)
|
||||
return $this->cachedJsonResponse($languageData['data'], 3600);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Public;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Seo\SitemapGenerator;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
/**
|
||||
* Sitemap XML 컨트롤러
|
||||
*
|
||||
* sitemap.xml 요청을 처리하여 캐시된 또는 실시간 생성된
|
||||
* Sitemap XML을 반환합니다.
|
||||
*/
|
||||
class SitemapController extends Controller
|
||||
{
|
||||
/**
|
||||
* sitemap.xml을 반환합니다.
|
||||
*
|
||||
* 캐시가 있으면 캐시된 XML, 없으면 실시간 생성 후 캐시 저장.
|
||||
*
|
||||
* @param SitemapGenerator $generator Sitemap 생성기
|
||||
*/
|
||||
public function index(SitemapGenerator $generator): Response
|
||||
{
|
||||
$enabled = (bool) g7_core_settings('seo.sitemap_enabled', true);
|
||||
if (! $enabled) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$xml = Cache::get('seo:sitemap');
|
||||
|
||||
if (! $xml) {
|
||||
$xml = $generator->generate();
|
||||
$ttl = (int) g7_core_settings('seo.sitemap_cache_ttl', 86400);
|
||||
Cache::put('seo:sitemap', $xml, $ttl);
|
||||
}
|
||||
|
||||
return response($xml, 200, [
|
||||
'Content-Type' => 'application/xml',
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user