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,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Http\Resources\Traits\HasRowNumber;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 활동 로그 컬렉션 리소스
|
||||
*
|
||||
* 활동 로그 목록을 페이지네이션과 함께 반환합니다.
|
||||
*/
|
||||
class ActivityLogCollection extends ResourceCollection
|
||||
{
|
||||
use HasRowNumber;
|
||||
|
||||
/**
|
||||
* 활동 로그 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->mapWithRowNumber(function ($activityLog) {
|
||||
return (new ActivityLogResource($activityLog))->toArray(request());
|
||||
}),
|
||||
'pagination' => $this->resource instanceof LengthAwarePaginator ? [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\App;
|
||||
|
||||
/**
|
||||
* 활동 로그 API 리소스
|
||||
*/
|
||||
class ActivityLogResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request 요청 객체
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'log_type' => $this->log_type->value,
|
||||
'log_type_label' => $this->log_type_label,
|
||||
'loggable_type' => $this->loggable_type,
|
||||
'loggable_type_display' => $this->loggable_type_display,
|
||||
'loggable_id' => $this->loggable_id,
|
||||
'action' => $this->action,
|
||||
'action_label' => $this->action_label,
|
||||
'localized_description' => $this->resolveUnreplacedCount(
|
||||
$this->localized_description,
|
||||
$this->changes
|
||||
),
|
||||
'description_key' => $this->description_key,
|
||||
'properties' => $this->properties,
|
||||
...$this->formatChangesOutput($this->changes),
|
||||
'has_changes' => ! empty($this->changes),
|
||||
'actor_name' => $this->actor_name,
|
||||
'user' => $this->user ? [
|
||||
'uuid' => $this->user->uuid,
|
||||
'name' => $this->user->name,
|
||||
'email' => $this->user->email,
|
||||
] : [
|
||||
'name' => __('common.system'),
|
||||
],
|
||||
'ip_address' => $this->ip_address,
|
||||
'created_at' => $this->formatDateTimeStringForUser($this->created_at),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* changes 데이터를 단일/일괄 구분하여 반환합니다.
|
||||
*
|
||||
* 단일 수정: changes = [{field, old, new}, ...]
|
||||
* 일괄 수정: bulk_changes = [{model_id, changes: [{field, old, new}, ...]}, ...]
|
||||
*
|
||||
* @param array|null $changes 원본 changes 데이터
|
||||
* @return array changes + bulk_changes 키를 포함하는 배열
|
||||
*/
|
||||
private function formatChangesOutput(?array $changes): array
|
||||
{
|
||||
if ($changes === null) {
|
||||
return ['changes' => null, 'bulk_changes' => null];
|
||||
}
|
||||
|
||||
// 일괄 수정 여부 감지: 첫 번째 값이 배열의 배열이면 일괄 (key=모델ID)
|
||||
$firstValue = reset($changes);
|
||||
$isBulk = is_array($firstValue) && isset($firstValue[0]) && is_array($firstValue[0]);
|
||||
|
||||
if ($isBulk) {
|
||||
$bulkChanges = [];
|
||||
foreach ($changes as $modelId => $modelChanges) {
|
||||
$bulkChanges[] = [
|
||||
'model_id' => $modelId,
|
||||
'changes' => $this->translateChangeGroup($modelChanges),
|
||||
];
|
||||
}
|
||||
|
||||
return ['changes' => null, 'bulk_changes' => $bulkChanges];
|
||||
}
|
||||
|
||||
return ['changes' => $this->translateChangeGroup($changes), 'bulk_changes' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 changes 그룹의 label_key 및 enum/boolean label을 번역합니다.
|
||||
*
|
||||
* 하위 호환: 기존 DB 레코드에서 type이 'text'로 저장되어 있지만
|
||||
* 모델의 현재 $activityLogFields에서 'enum'으로 정의된 필드는
|
||||
* 동적으로 enum 라벨을 해석합니다.
|
||||
*
|
||||
* @param array $changes 변경 항목 배열
|
||||
* @return array 번역된 변경 항목 배열
|
||||
*/
|
||||
private function translateChangeGroup(array $changes): array
|
||||
{
|
||||
$modelFields = $this->resolveModelActivityLogFields();
|
||||
|
||||
return array_map(function (array $change) use ($modelFields) {
|
||||
$change['label'] = isset($change['label_key']) ? __($change['label_key']) : ($change['field'] ?? '');
|
||||
|
||||
$storedType = $change['type'] ?? 'text';
|
||||
$field = $change['field'] ?? null;
|
||||
|
||||
// 하위 호환: 저장된 type이 'text'지만 모델에서 'enum'으로 정의된 경우 동적 해석
|
||||
if ($storedType === 'text' && $field && isset($modelFields[$field])) {
|
||||
$currentMeta = $modelFields[$field];
|
||||
if (($currentMeta['type'] ?? 'text') === 'enum' && isset($currentMeta['enum'])) {
|
||||
$storedType = 'enum';
|
||||
$change['type'] = 'enum';
|
||||
$enumClass = $currentMeta['enum'];
|
||||
$change['old_label_key'] = isset($change['old']) ? $enumClass::tryFrom($change['old'])?->labelKey() : null;
|
||||
$change['new_label_key'] = isset($change['new']) ? $enumClass::tryFrom($change['new'])?->labelKey() : null;
|
||||
}
|
||||
}
|
||||
|
||||
if ($storedType === 'enum') {
|
||||
$change['old_label'] = isset($change['old_label_key']) ? __($change['old_label_key']) : null;
|
||||
$change['new_label'] = isset($change['new_label_key']) ? __($change['new_label_key']) : null;
|
||||
}
|
||||
|
||||
if ($storedType === 'boolean') {
|
||||
$change['old_label'] = $change['old'] ? __('common.yes') : __('common.no');
|
||||
$change['new_label'] = $change['new'] ? __('common.yes') : __('common.no');
|
||||
}
|
||||
|
||||
if ($storedType === 'json') {
|
||||
$change['old'] = $this->extractLocaleValue($change['old']);
|
||||
$change['new'] = $this->extractLocaleValue($change['new']);
|
||||
}
|
||||
|
||||
return $change;
|
||||
}, $changes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 JSON 값에서 현재 로케일 텍스트를 추출합니다.
|
||||
*
|
||||
* @param mixed $value 원본 값 (배열이면 로케일 추출, 아니면 그대로 반환)
|
||||
* @return mixed 로케일 텍스트 또는 원본 값
|
||||
*/
|
||||
private function extractLocaleValue(mixed $value): mixed
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$locale = App::getLocale();
|
||||
$fallback = config('app.fallback_locale', 'en');
|
||||
|
||||
return $value[$locale] ?? $value[$fallback] ?? reset($value) ?: $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* loggable_type으로부터 모델의 $activityLogFields 메타데이터를 해석합니다.
|
||||
*
|
||||
* 하위 호환을 위해 기존 DB 레코드의 type: 'text' 필드를
|
||||
* 현재 모델 정의와 비교하여 enum 타입을 동적으로 판별합니다.
|
||||
*
|
||||
* @return array<string, array> 필드 메타데이터 (field => meta 매핑)
|
||||
*/
|
||||
private function resolveModelActivityLogFields(): array
|
||||
{
|
||||
$loggableType = $this->loggable_type;
|
||||
if (! $loggableType || ! class_exists($loggableType)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (! property_exists($loggableType, 'activityLogFields')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $loggableType::$activityLogFields;
|
||||
}
|
||||
|
||||
/**
|
||||
* 일괄 변경 로그에서 description_params에 count가 누락된 경우 보정합니다.
|
||||
*
|
||||
* 하위 호환: 기존 DB 레코드에서 count 파라미터가 누락되어
|
||||
* `:count` 플레이스홀더가 미치환되는 문제를 방지합니다.
|
||||
*
|
||||
* @param string $description 번역된 설명 문자열
|
||||
* @param array|null $changes 변경 사항 데이터
|
||||
* @return string 보정된 설명 문자열
|
||||
*/
|
||||
private function resolveUnreplacedCount(string $description, ?array $changes): string
|
||||
{
|
||||
if (! str_contains($description, ':count') || $changes === null) {
|
||||
return $description;
|
||||
}
|
||||
|
||||
// bulk 형식 감지: 첫 번째 값이 배열의 배열이면 일괄 수정
|
||||
$firstValue = reset($changes);
|
||||
$isBulk = is_array($firstValue) && isset($firstValue[0]) && is_array($firstValue[0]);
|
||||
|
||||
if ($isBulk) {
|
||||
$count = count($changes);
|
||||
|
||||
return str_replace(':count', (string) $count, $description);
|
||||
}
|
||||
|
||||
return $description;
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 체크 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_read' => 'core.activities.read',
|
||||
'can_delete' => 'core.activities.delete',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 소유자 필드명을 반환합니다.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'user_id';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 첨부파일 API 리소스
|
||||
*/
|
||||
class AttachmentResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'hash' => $this->getValue('hash'),
|
||||
'original_filename' => $this->getValue('original_filename'),
|
||||
'mime_type' => $this->getValue('mime_type'),
|
||||
'size' => $this->getValue('size'),
|
||||
'size_formatted' => $this->size_formatted,
|
||||
'collection' => $this->getValue('collection'),
|
||||
'order' => $this->getValue('order'),
|
||||
'download_url' => $this->download_url,
|
||||
'is_image' => $this->is_image,
|
||||
'meta' => $this->getValue('meta'),
|
||||
'source_type' => $this->getValue('source_type')?->value,
|
||||
'source_identifier' => $this->getValue('source_identifier'),
|
||||
|
||||
// 업로더 정보 (로드된 경우)
|
||||
'creator' => $this->whenLoaded('creator', function () {
|
||||
return [
|
||||
'uuid' => $this->creator->uuid,
|
||||
'name' => $this->creator->name,
|
||||
];
|
||||
}),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 소유자 필드명을 반환합니다.
|
||||
*
|
||||
* @return string|null 소유자 필드명
|
||||
*/
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'created_by';
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_update' => 'core.attachments.update',
|
||||
'can_delete' => 'core.attachments.delete',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* 주의: 이 메서드는 toArray() 외부에서 수동 호출되므로
|
||||
* $this->when() 대신 삼항 연산자를 사용해야 합니다.
|
||||
* $this->when()은 Laravel이 toArray()를 처리할 때만 MissingValue를 필터링합니다.
|
||||
*
|
||||
* @param Request|null $request HTTP 요청
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toListArray(?Request $request = null): array
|
||||
{
|
||||
$request = $request ?? request();
|
||||
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'hash' => $this->getValue('hash'),
|
||||
'original_filename' => $this->getValue('original_filename'),
|
||||
'mime_type' => $this->getValue('mime_type'),
|
||||
'size_formatted' => $this->size_formatted,
|
||||
'order' => $this->getValue('order'),
|
||||
'download_url' => $this->download_url,
|
||||
'is_image' => $this->is_image,
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Facades\App;
|
||||
|
||||
class BaseApiResource extends JsonResource
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 배열 데이터
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return parent::toArray($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열 데이터를 객체로 변환하여 접근 가능하게 합니다.
|
||||
*
|
||||
* @return object|mixed 객체로 변환된 리소스
|
||||
*/
|
||||
protected function asObject()
|
||||
{
|
||||
if (is_array($this->resource)) {
|
||||
return (object) $this->resource;
|
||||
}
|
||||
|
||||
return $this->resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열이나 객체에서 안전하게 값을 가져옵니다.
|
||||
*
|
||||
* @param string $key 가져올 키
|
||||
* @param mixed $default 기본값 (키가 없을 경우)
|
||||
* @return mixed 값 또는 기본값
|
||||
*/
|
||||
protected function getValue(string $key, $default = null)
|
||||
{
|
||||
if (is_array($this->resource)) {
|
||||
return $this->resource[$key] ?? $default;
|
||||
}
|
||||
|
||||
return $this->resource->{$key} ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스가 배열인지 확인합니다.
|
||||
*
|
||||
* @return bool 배열 여부
|
||||
*/
|
||||
protected function isArray(): bool
|
||||
{
|
||||
return is_array($this->resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 중첩된 배열을 재귀적으로 객체로 변환합니다.
|
||||
*
|
||||
* @param mixed $data 변환할 데이터
|
||||
* @return mixed 객체로 변환된 데이터
|
||||
*/
|
||||
protected function arrayToObjectRecursive($data)
|
||||
{
|
||||
if (is_array($data)) {
|
||||
return (object) array_map([$this, 'arrayToObjectRecursive'], $data);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 매직 메서드 오버라이드: 배열일 때도 객체처럼 접근 가능하게 합니다.
|
||||
*
|
||||
* @param string $key 속성 키
|
||||
* @return mixed 속성 값
|
||||
*/
|
||||
public function __get($key)
|
||||
{
|
||||
if (is_array($this->resource)) {
|
||||
return $this->resource[$key] ?? null;
|
||||
}
|
||||
|
||||
return parent::__get($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 배열/객체 상관없이 isset 체크를 수행합니다.
|
||||
*
|
||||
* @param string $key 확인할 키
|
||||
* @return bool 존재 여부
|
||||
*/
|
||||
public function __isset($key)
|
||||
{
|
||||
if (is_array($this->resource)) {
|
||||
return isset($this->resource[$key]);
|
||||
}
|
||||
|
||||
return parent::__isset($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 공통 타임스탬프 형식을 반환합니다.
|
||||
* 사용자 timezone으로 변환하여 Y-m-d H:i:s 형식으로 반환합니다.
|
||||
*
|
||||
* @return array<string, string|null> 포맷된 타임스탬프 배열
|
||||
*/
|
||||
protected function formatTimestamps(): array
|
||||
{
|
||||
return [
|
||||
'created_at' => $this->when($this->created_at, fn () => $this->formatDateTimeStringForUser($this->created_at)),
|
||||
'updated_at' => $this->when($this->updated_at, fn () => $this->formatDateTimeStringForUser($this->updated_at)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* datetime 값을 사용자 timezone으로 변환하여 ISO8601 문자열로 반환합니다.
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null ISO8601 형식의 datetime 문자열
|
||||
*/
|
||||
protected function formatDateTimeForUser(?Carbon $datetime): ?string
|
||||
{
|
||||
return TimezoneHelper::toUserTimezone($datetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* datetime 값을 사용자 timezone으로 변환하여 날짜만 반환합니다 (Y-m-d 형식).
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d 형식의 날짜 문자열
|
||||
*/
|
||||
protected function formatDateForUser(?Carbon $datetime): ?string
|
||||
{
|
||||
return TimezoneHelper::toUserDateString($datetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* datetime 값을 사용자 timezone으로 변환하여 Y-m-d H:i:s 형식으로 반환합니다.
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d H:i:s 형식의 datetime 문자열
|
||||
*/
|
||||
protected function formatDateTimeStringForUser(?Carbon $datetime): ?string
|
||||
{
|
||||
return TimezoneHelper::toUserDateTimeString($datetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* datetime 값을 사이트 기본 timezone으로 변환하여 Y-m-d 형식으로 반환합니다.
|
||||
*
|
||||
* HTML <input type="date"> 호환용 (datepicker에 바인딩하는 날짜 필드에 사용).
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d 형식의 날짜 문자열
|
||||
*/
|
||||
protected function formatDateStringForSite(?Carbon $datetime): ?string
|
||||
{
|
||||
return TimezoneHelper::toSiteDateString($datetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* datetime 값을 사이트 기본 timezone으로 변환하여 datetime-local 호환 형식으로 반환합니다.
|
||||
*
|
||||
* HTML <input type="datetime-local"> 호환용 (Y-m-d\TH:i 형식).
|
||||
*
|
||||
* @param Carbon|null $datetime 변환할 datetime
|
||||
* @return string|null Y-m-d\TH:i 형식의 datetime 문자열
|
||||
*/
|
||||
protected function formatDateTimeLocalStringForSite(?Carbon $datetime): ?string
|
||||
{
|
||||
return TimezoneHelper::toSiteDateTimeLocalString($datetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 요청의 타임존을 가져옵니다.
|
||||
* SetTimezone 미들웨어에서 설정한 값을 사용하며, 미설정 시 기본값을 반환합니다.
|
||||
*/
|
||||
protected function getUserTimezone(): string
|
||||
{
|
||||
return TimezoneHelper::getUserTimezone();
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 메시지와 함께 응답을 생성합니다.
|
||||
*
|
||||
* @param string $messageKey 메시지 키
|
||||
* @param array $messageParams 메시지 파라미터
|
||||
* @param string $domain 메시지 도메인
|
||||
* @return $this
|
||||
*/
|
||||
public function withMessage(string $messageKey, array $messageParams = [], string $domain = 'core')
|
||||
{
|
||||
return $this->additional([
|
||||
'message_key' => $messageKey,
|
||||
'message_params' => $messageParams,
|
||||
'message_domain' => $domain,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 필드 값을 현재 로케일에 맞게 반환합니다.
|
||||
*
|
||||
* @param string $field 필드명
|
||||
* @return string|array|null 다국어 값
|
||||
*/
|
||||
protected function getLocalizedField(string $field)
|
||||
{
|
||||
$value = $this->getValue($field);
|
||||
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 이미 문자열이면 그대로 반환
|
||||
if (is_string($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// 배열(다국어)이면 현재 로케일에 맞는 값 반환
|
||||
if (is_array($value)) {
|
||||
$locale = App::getLocale();
|
||||
|
||||
return $value[$locale] ?? $value['ko'] ?? $value['en'] ?? reset($value) ?: null;
|
||||
}
|
||||
|
||||
// Model의 getLocalizedName() 등의 메서드가 있으면 사용
|
||||
$methodName = 'getLocalized'.ucfirst($field);
|
||||
if (is_object($this->resource) && method_exists($this->resource, $methodName)) {
|
||||
return $this->resource->{$methodName}();
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 소유자 필드명을 반환합니다.
|
||||
* null 반환 시 is_owner 필드가 응답에서 제외됩니다.
|
||||
* 자식 클래스에서 오버라이드합니다.
|
||||
*
|
||||
* @return string|null 소유자 필드명
|
||||
*/
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 능력(can_*) 매핑을 반환합니다.
|
||||
* 자식 클래스에서 오버라이드합니다.
|
||||
*
|
||||
* @return array<string, string> ['can_update' => 'module.entity.update', ...]
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 소유자 여부를 계산합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return bool|null 소유자 여부 (ownerField 미정의 시 null)
|
||||
*/
|
||||
protected function resolveIsOwner(Request $request): ?bool
|
||||
{
|
||||
$field = $this->ownerField();
|
||||
if ($field === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ownerId = $this->resource->{$field};
|
||||
if ($ownerId === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $request->user()?->id === $ownerId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 능력 맵을 불리언으로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, bool> 능력 불리언 맵
|
||||
*/
|
||||
protected function resolveAbilities(Request $request): array
|
||||
{
|
||||
return $this->resolveAbilitiesFromMap($this->abilityMap(), $request->user());
|
||||
}
|
||||
|
||||
/**
|
||||
* is_owner + abilities 표준 필드를 반환합니다.
|
||||
* 자식 클래스의 toArray()에서 spread 연산자로 합침.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 메타 데이터
|
||||
*/
|
||||
protected function resourceMeta(Request $request): array
|
||||
{
|
||||
$meta = [];
|
||||
|
||||
$isOwner = $this->resolveIsOwner($request);
|
||||
if ($isOwner !== null) {
|
||||
$meta['is_owner'] = $isOwner;
|
||||
}
|
||||
|
||||
$abilities = $this->resolveAbilities($request);
|
||||
if (! empty($abilities)) {
|
||||
$meta['abilities'] = $abilities;
|
||||
}
|
||||
|
||||
return $meta;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class LayoutResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$content = $this->getValue('content', []);
|
||||
$contentJson = is_array($content) ? json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) : '{}';
|
||||
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'template_id' => $this->getValue('template_id'),
|
||||
'name' => $this->getValue('name'),
|
||||
'description' => $content['meta']['description'] ?? $this->getValue('name'),
|
||||
'endpoint' => $content['endpoint'] ?? null,
|
||||
'components' => $content['components'] ?? [],
|
||||
'data_sources' => $content['data_sources'] ?? [],
|
||||
'metadata' => $content['metadata'] ?? [],
|
||||
|
||||
// 레이아웃 편집 페이지용 필드
|
||||
'content' => $contentJson,
|
||||
'size' => strlen($contentJson),
|
||||
'size_formatted' => $this->formatFileSize(strlen($contentJson)),
|
||||
'has_update' => false, // TODO: 템플릿 파일과 DB 버전 비교 로직 추가
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
// created_by, updated_by는 보안상 제외
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_update' => 'core.templates.layouts.edit',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 크기를 사람이 읽기 쉬운 형태로 변환
|
||||
*
|
||||
* @param int $bytes 바이트 크기
|
||||
* @return string 포맷된 크기 (예: "12.5 KB")
|
||||
*/
|
||||
private function formatFileSize(int $bytes): string
|
||||
{
|
||||
if ($bytes < 1024) {
|
||||
return $bytes . ' B';
|
||||
} elseif ($bytes < 1048576) {
|
||||
return round($bytes / 1024, 1) . ' KB';
|
||||
} else {
|
||||
return round($bytes / 1048576, 1) . ' MB';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class LayoutVersionResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$content = $this->getValue('content', []);
|
||||
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'layout_id' => $this->getValue('layout_id'),
|
||||
'version' => $this->getValue('version'),
|
||||
'endpoint' => $content['endpoint'] ?? null,
|
||||
'components' => $content['components'] ?? [],
|
||||
'data_sources' => $content['data_sources'] ?? [],
|
||||
'metadata' => $content['metadata'] ?? [],
|
||||
'changes_summary' => $this->formatChangesSummary($this->getValue('changes_summary', [])),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
// created_by는 보안상 제외
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* changes_summary를 포맷팅하여 count 필드 추가
|
||||
*
|
||||
* @param array $changesSummary 원본 changes_summary
|
||||
* @return array 포맷팅된 changes_summary
|
||||
*/
|
||||
private function formatChangesSummary(array $changesSummary): array
|
||||
{
|
||||
return [
|
||||
'added' => $changesSummary['added'] ?? [],
|
||||
'removed' => $changesSummary['removed'] ?? [],
|
||||
'modified' => $changesSummary['modified'] ?? [],
|
||||
'added_count' => count($changesSummary['added'] ?? []),
|
||||
'removed_count' => count($changesSummary['removed'] ?? []),
|
||||
'modified_count' => count($changesSummary['modified'] ?? []),
|
||||
'char_diff' => $changesSummary['char_diff'] ?? 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Http\Resources\Traits\HasRowNumber;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 메일 발송 이력 컬렉션 리소스
|
||||
*
|
||||
* 발송 이력 목록을 페이지네이션과 함께 반환합니다.
|
||||
*/
|
||||
class MailSendLogCollection extends ResourceCollection
|
||||
{
|
||||
use HasRowNumber;
|
||||
|
||||
/**
|
||||
* 메일 발송 이력 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->mapWithRowNumber(function ($mailSendLog) {
|
||||
return (new MailSendLogResource($mailSendLog))->toArray(request());
|
||||
}),
|
||||
'pagination' => $this->resource instanceof LengthAwarePaginator ? [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 메일 발송 이력 API 리소스
|
||||
*/
|
||||
class MailSendLogResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string> 능력명 => 권한 식별자 매핑
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_delete' => 'core.mail-send-logs.delete',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 배열 데이터
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'sender_email' => $this->sender_email,
|
||||
'sender_name' => $this->sender_name,
|
||||
'recipient_email' => $this->recipient_email,
|
||||
'recipient_name' => $this->recipient_name,
|
||||
'subject' => $this->subject,
|
||||
'body' => $this->body,
|
||||
'template_type' => $this->template_type,
|
||||
'extension_type' => $this->extension_type?->value,
|
||||
'extension_identifier' => $this->extension_identifier,
|
||||
'source' => $this->source,
|
||||
'status' => $this->status,
|
||||
'error_message' => $this->error_message,
|
||||
'sent_at' => $this->formatDateTimeStringForUser($this->sent_at),
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Http\Resources\Traits\HasRowNumber;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* 메일 템플릿 컬렉션 리소스
|
||||
*
|
||||
* 템플릿 목록을 페이지네이션과 함께 반환합니다.
|
||||
*/
|
||||
class MailTemplateCollection extends ResourceCollection
|
||||
{
|
||||
use HasRowNumber;
|
||||
|
||||
/**
|
||||
* 메일 템플릿 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->mapWithRowNumber(function ($mailTemplate) {
|
||||
return (new MailTemplateResource($mailTemplate))->toArray(request());
|
||||
}),
|
||||
'pagination' => $this->resource instanceof LengthAwarePaginator ? [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class MailTemplateResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return array<string, mixed> 리소스 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'type' => $this->getValue('type'),
|
||||
'subject' => $this->getValue('subject'),
|
||||
'body' => $this->getValue('body'),
|
||||
'variables' => $this->getValue('variables'),
|
||||
'is_active' => (bool) $this->getValue('is_active'),
|
||||
'is_default' => (bool) $this->getValue('is_default'),
|
||||
'updated_by' => $this->updater?->uuid,
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class MenuCollection extends ResourceCollection
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
|
||||
/**
|
||||
* 컬렉션 레벨 능력(can_*) 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string> 능력 키 => 권한 식별자 매핑
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'core.menus.create',
|
||||
'can_update' => 'core.menus.update',
|
||||
'can_delete' => 'core.menus.delete',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 메뉴 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 메뉴 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($menu) {
|
||||
return new MenuResource($menu);
|
||||
}),
|
||||
'abilities' => $this->resolveAbilitiesFromMap($this->abilityMap(), $request->user()),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 네비게이션용 계층 구조 메뉴 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 계층 구조 메뉴 배열
|
||||
*/
|
||||
public function toNavigationArray(): array
|
||||
{
|
||||
// 최상위 메뉴만 필터링 (parent_id가 null인 것들)
|
||||
$topLevelMenus = $this->collection->filter(function ($menu) {
|
||||
return is_null($menu->parent_id);
|
||||
});
|
||||
|
||||
return [
|
||||
'data' => $topLevelMenus->map(function ($menu) {
|
||||
return (new MenuResource($menu))->toNavigationArray();
|
||||
})->sortBy('order')->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플랫 구조의 메뉴 목록을 반환합니다 (관리자용).
|
||||
*
|
||||
* @return array<string, mixed> 플랫 구조 메뉴 목록
|
||||
*/
|
||||
public function toFlatArray(): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($menu) {
|
||||
return [
|
||||
'id' => $menu->id,
|
||||
'name' => $menu->name,
|
||||
'slug' => $menu->slug,
|
||||
'url' => $menu->url,
|
||||
'icon' => $menu->icon,
|
||||
'order' => $menu->order,
|
||||
'is_active' => $menu->is_active,
|
||||
'parent_id' => $menu->parent_id,
|
||||
'module_name' => $menu->module?->name,
|
||||
];
|
||||
})->sortBy(['parent_id', 'order'])->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답에 추가 메타데이터를 포함합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 메타데이터 배열
|
||||
*/
|
||||
public function with(Request $request): array
|
||||
{
|
||||
return [
|
||||
'meta' => [
|
||||
'total_menus' => $this->collection->count(),
|
||||
'active_menus' => $this->collection->where('is_active', true)->count(),
|
||||
'top_level_menus' => $this->collection->whereNull('parent_id')->count(),
|
||||
'modules_used' => $this->collection->pluck('module.name')->filter()->unique()->values(),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class MenuResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 메뉴 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 메뉴 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'name' => $this->getValue('name'), // 다국어 객체 그대로 반환 (프론트엔드에서 $localized() 사용)
|
||||
'slug' => $this->getValue('slug'),
|
||||
'url' => $this->getValue('url'),
|
||||
'icon' => $this->getValue('icon'),
|
||||
'order' => $this->getValue('order'),
|
||||
'is_active' => $this->getValue('is_active', true),
|
||||
|
||||
// 관계형 데이터
|
||||
'parent_id' => $this->getValue('parent_id'), // parent_id 추가 (프론트엔드에서 필요)
|
||||
'extension_type' => $this->getValue('extension_type'),
|
||||
'extension_identifier' => $this->getValue('extension_identifier'),
|
||||
'parent' => $this->whenLoaded('parent', function () {
|
||||
return $this->parent ? [
|
||||
'id' => $this->parent->id,
|
||||
'name' => $this->parent->name, // 다국어 객체 그대로 반환
|
||||
'url' => $this->parent->url,
|
||||
'icon' => $this->parent->icon,
|
||||
] : null;
|
||||
}),
|
||||
|
||||
'children' => $this->whenLoaded('children', function () {
|
||||
return $this->children->map(function ($child) {
|
||||
return [
|
||||
'id' => $child->id,
|
||||
'name' => $child->name, // 다국어 객체 그대로 반환
|
||||
'slug' => $child->slug,
|
||||
'url' => $child->url,
|
||||
'icon' => $child->icon,
|
||||
'order' => $child->order,
|
||||
'is_active' => $child->is_active,
|
||||
'parent_id' => $child->parent_id,
|
||||
'extension_type' => $child->extension_type?->value,
|
||||
'extension_identifier' => $child->extension_identifier,
|
||||
'roles' => $child->relationLoaded('roles') ? $child->roles->map(function ($role) {
|
||||
return [
|
||||
'id' => $role->id,
|
||||
'name' => $role->name,
|
||||
'permission_type' => $role->pivot->permission_type ?? null,
|
||||
];
|
||||
}) : [],
|
||||
];
|
||||
})->sortBy('order')->values();
|
||||
}),
|
||||
|
||||
'creator' => $this->whenLoaded('creator', function () {
|
||||
return $this->creator ? [
|
||||
'uuid' => $this->creator->uuid,
|
||||
'name' => $this->creator->name,
|
||||
'email' => $this->creator->email,
|
||||
] : null;
|
||||
}),
|
||||
|
||||
'roles' => $this->whenLoaded('roles', function () {
|
||||
return $this->roles->map(function ($role) {
|
||||
return [
|
||||
'id' => $role->id,
|
||||
'name' => $role->name,
|
||||
'permission_type' => $role->pivot->permission_type ?? null,
|
||||
];
|
||||
});
|
||||
}),
|
||||
|
||||
// 통계 정보
|
||||
'children_count' => $this->when(
|
||||
isset($this->children_count),
|
||||
$this->getValue('children_count')
|
||||
),
|
||||
'depth_level' => $this->when(
|
||||
isset($this->depth_level),
|
||||
$this->getValue('depth_level')
|
||||
),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 소유자 필드명을 반환합니다.
|
||||
*
|
||||
* @return string|null 소유자 필드명
|
||||
*/
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'created_by';
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'core.menus.create',
|
||||
'can_update' => 'core.menus.update',
|
||||
'can_delete' => 'core.menus.delete',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 네비게이션용 단순한 형태의 배열을 반환합니다 (계층 구조 포함).
|
||||
*
|
||||
* @return array<string, mixed> 네비게이션용 메뉴 정보
|
||||
*/
|
||||
public function toNavigationArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name, // 다국어 객체 그대로 반환
|
||||
'slug' => $this->slug,
|
||||
'url' => $this->url,
|
||||
'icon' => $this->icon,
|
||||
'order' => $this->order,
|
||||
'is_active' => $this->is_active,
|
||||
'children' => $this->whenLoaded('activeChildren', function () {
|
||||
return $this->activeChildren
|
||||
->sortBy('order')
|
||||
->map(function ($child) {
|
||||
return [
|
||||
'id' => $child->id,
|
||||
'name' => $child->name, // 다국어 객체 그대로 반환
|
||||
'slug' => $child->slug,
|
||||
'url' => $child->url,
|
||||
'icon' => $child->icon,
|
||||
'order' => $child->order,
|
||||
'is_active' => $child->is_active,
|
||||
'parent_id' => $child->parent_id,
|
||||
'extension_type' => $child->extension_type?->value,
|
||||
'extension_identifier' => $child->extension_identifier,
|
||||
];
|
||||
})->values();
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자용 상세 정보를 포함한 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 관리자용 상세 메뉴 정보
|
||||
*/
|
||||
public function withAdminInfo(): array
|
||||
{
|
||||
return array_merge($this->toArray(request()), [
|
||||
'admin_notes' => $this->admin_notes,
|
||||
'created_by' => $this->creator?->uuid,
|
||||
'last_accessed_at' => $this->when($this->last_accessed_at, fn () => $this->formatDateTimeForUser($this->last_accessed_at)),
|
||||
'access_count' => $this->access_count ?? 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class ModuleCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* 모듈 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 모듈 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($module) {
|
||||
return new ModuleResource($module);
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 마켓플레이스용 모듈 목록 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 마켓플레이스용 모듈 목록 (설치 횟수 순 정렬)
|
||||
*/
|
||||
public function toMarketplaceArray(): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($module) {
|
||||
return (new ModuleResource($module))->toMarketplaceArray();
|
||||
})->sortByDesc('install_count')->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 모듈 목록을 활성/비활성으로 구분하여 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 활성/비활성 모듈 목록
|
||||
*/
|
||||
public function toInstalledArray(): array
|
||||
{
|
||||
$active = $this->collection->where('is_active', true);
|
||||
$inactive = $this->collection->where('is_active', false);
|
||||
|
||||
return [
|
||||
'active' => $active->map(function ($module) {
|
||||
return (new ModuleResource($module))->toDependencyArray();
|
||||
})->sortBy('name')->values(),
|
||||
'inactive' => $inactive->map(function ($module) {
|
||||
return (new ModuleResource($module))->toDependencyArray();
|
||||
})->sortBy('name')->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 의존성 그래프용 데이터 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 노드와 엣지 정보가 포함된 의존성 그래프 데이터
|
||||
*/
|
||||
public function toDependencyGraph(): array
|
||||
{
|
||||
return [
|
||||
'nodes' => $this->collection->map(function ($module) {
|
||||
return [
|
||||
'id' => $module->slug,
|
||||
'name' => $module->name,
|
||||
'version' => $module->version,
|
||||
'is_active' => $module->is_active,
|
||||
'is_system' => $module->is_system,
|
||||
];
|
||||
}),
|
||||
'edges' => $this->collection->flatMap(function ($module) {
|
||||
if (! $module->relationLoaded('dependencies')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $module->dependencies->map(function ($dependency) use ($module) {
|
||||
return [
|
||||
'from' => $module->slug,
|
||||
'to' => $dependency->slug,
|
||||
'required_version' => $dependency->pivot->required_version ?? null,
|
||||
];
|
||||
});
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템/사용자 모듈로 구분하여 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 시스템 모듈과 사용자 모듈 목록
|
||||
*/
|
||||
public function toByCategoryArray(): array
|
||||
{
|
||||
$system = $this->collection->where('is_system', true);
|
||||
$user = $this->collection->where('is_system', false);
|
||||
|
||||
return [
|
||||
'system' => $system->map(function ($module) {
|
||||
return (new ModuleResource($module))->toDependencyArray();
|
||||
})->sortBy('name')->values(),
|
||||
'user' => $user->map(function ($module) {
|
||||
return (new ModuleResource($module))->toMarketplaceArray();
|
||||
})->sortByDesc('install_count')->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답에 추가 메타데이터를 포함합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 메타데이터 배열
|
||||
*/
|
||||
public function with(Request $request): array
|
||||
{
|
||||
return [
|
||||
'meta' => [
|
||||
'total_modules' => $this->collection->count(),
|
||||
'active_modules' => $this->collection->where('is_active', true)->count(),
|
||||
'system_modules' => $this->collection->where('is_system', true)->count(),
|
||||
'user_modules' => $this->collection->where('is_system', false)->count(),
|
||||
'total_installs' => $this->collection->sum('install_count'),
|
||||
'average_rating' => $this->collection->where('rating', '>', 0)->avg('rating'),
|
||||
'latest_version' => $this->collection->max('version'),
|
||||
'categories' => $this->collection->pluck('tags')->flatten()->unique()->values(),
|
||||
'dependency_count' => $this->collection->sum('dependencies_count'),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ModuleResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 모듈 목록용 리소스를 배열로 변환합니다 (간소화된 정보).
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 모듈 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'vendor' => $this->getValue('vendor'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'description' => $this->getLocalizedField('description'),
|
||||
'dependencies' => $this->getValue('dependencies', []),
|
||||
'status' => $this->getValue('status'),
|
||||
'assets' => $this->getValue('assets'),
|
||||
// 업데이트 관련 필드
|
||||
'update_available' => $this->getValue('update_available', false),
|
||||
'update_source' => $this->getValue('update_source'),
|
||||
'latest_version' => $this->getValue('latest_version'),
|
||||
'file_version' => $this->getValue('file_version'),
|
||||
'github_url' => $this->getValue('github_url'),
|
||||
'github_changelog_url' => $this->getValue('github_changelog_url'),
|
||||
// pending/bundled 상태
|
||||
'is_pending' => $this->getValue('is_pending', false),
|
||||
'is_bundled' => $this->getValue('is_bundled', false),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_install' => 'core.modules.install',
|
||||
'can_activate' => 'core.modules.activate',
|
||||
'can_uninstall' => 'core.modules.uninstall',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 상세 정보를 배열로 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 상세 모듈 정보
|
||||
*/
|
||||
public function toDetailArray(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'vendor' => $this->getValue('vendor'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'description' => $this->getLocalizedField('description'),
|
||||
'github_url' => $this->getValue('github_url'),
|
||||
'dependencies' => $this->getValue('dependencies', []),
|
||||
'status' => $this->getValue('status'),
|
||||
'is_installed' => $this->getValue('is_installed', false),
|
||||
// 상세 정보
|
||||
'permissions' => $this->getValue('permissions', []),
|
||||
'roles' => $this->getValue('roles', []),
|
||||
'admin_menus' => $this->getValue('admin_menus', []),
|
||||
'license' => $this->getValue('license'),
|
||||
'layouts_count' => $this->getValue('layouts_count', 0),
|
||||
'config' => $this->getValue('config', []),
|
||||
'metadata' => $this->getValue('metadata', []),
|
||||
// 업데이트 관련 필드
|
||||
'update_available' => $this->getValue('update_available', false),
|
||||
'update_source' => $this->getValue('update_source'),
|
||||
'latest_version' => $this->getValue('latest_version'),
|
||||
'file_version' => $this->getValue('file_version'),
|
||||
'github_changelog_url' => $this->getValue('github_changelog_url'),
|
||||
// pending/bundled 상태
|
||||
'is_pending' => $this->getValue('is_pending', false),
|
||||
'is_bundled' => $this->getValue('is_bundled', false),
|
||||
// 타임스탬프
|
||||
'created_at' => $this->getValue('created_at')
|
||||
? TimezoneHelper::toUserDateTimeString(Carbon::parse($this->getValue('created_at')))
|
||||
: null,
|
||||
'updated_at' => $this->getValue('updated_at')
|
||||
? TimezoneHelper::toUserDateTimeString(Carbon::parse($this->getValue('updated_at')))
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 마켓플레이스용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 마켓플레이스용 모듈 정보
|
||||
*/
|
||||
public function toMarketplaceArray(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'status' => $this->getValue('status'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 의존성 체크용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 의존성 확인용 모듈 정보
|
||||
*/
|
||||
public function toDependencyArray(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'status' => $this->getValue('status'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PermissionResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 권한 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 배열 데이터
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'parent_id' => $this->getValue('parent_id'),
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'name' => $this->getLocalizedName(),
|
||||
'name_raw' => $this->getValue('name'),
|
||||
'description' => $this->getLocalizedDescription(),
|
||||
'description_raw' => $this->getValue('description'),
|
||||
'extension_type' => $this->getValue('extension_type'),
|
||||
'extension_identifier' => $this->getValue('extension_identifier'),
|
||||
'order' => $this->getValue('order', 0),
|
||||
'is_assignable' => $this->when(
|
||||
is_object($this->resource) && method_exists($this->resource, 'isAssignable'),
|
||||
fn () => $this->resource->isAssignable()
|
||||
),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
/**
|
||||
* 플러그인 컬렉션 리소스
|
||||
*
|
||||
* 플러그인 목록을 다양한 형태로 변환하여 반환합니다.
|
||||
*/
|
||||
class PluginCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* 플러그인 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 플러그인 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($plugin) {
|
||||
return new PluginResource($plugin);
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 마켓플레이스용 플러그인 목록 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 마켓플레이스용 플러그인 목록
|
||||
*/
|
||||
public function toMarketplaceArray(): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($plugin) {
|
||||
return (new PluginResource($plugin))->toBasicArray();
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 플러그인 목록을 활성/비활성으로 구분하여 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 활성/비활성 플러그인 목록
|
||||
*/
|
||||
public function toInstalledArray(): array
|
||||
{
|
||||
$active = $this->collection->filter(fn ($p) => ($p['status'] ?? '') === 'active');
|
||||
$inactive = $this->collection->filter(fn ($p) => ($p['status'] ?? '') === 'inactive');
|
||||
|
||||
return [
|
||||
'active' => $active->map(function ($plugin) {
|
||||
return (new PluginResource($plugin))->toBasicArray();
|
||||
})->values(),
|
||||
'inactive' => $inactive->map(function ($plugin) {
|
||||
return (new PluginResource($plugin))->toBasicArray();
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답에 추가 메타데이터를 포함합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 메타데이터 배열
|
||||
*/
|
||||
public function with(Request $request): array
|
||||
{
|
||||
$collection = $this->collection;
|
||||
|
||||
return [
|
||||
'meta' => [
|
||||
'total_plugins' => $collection->count(),
|
||||
'active_plugins' => $collection->filter(fn ($p) => ($p['status'] ?? '') === 'active')->count(),
|
||||
'inactive_plugins' => $collection->filter(fn ($p) => ($p['status'] ?? '') === 'inactive')->count(),
|
||||
'installed_plugins' => $collection->filter(fn ($p) => ($p['status'] ?? '') !== 'uninstalled')->count(),
|
||||
'uninstalled_plugins' => $collection->filter(fn ($p) => ($p['status'] ?? '') === 'uninstalled')->count(),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PluginResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 플러그인 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 플러그인 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'vendor' => $this->getValue('vendor'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version', '1.0.0'),
|
||||
'description' => $this->getLocalizedField('description'),
|
||||
'dependencies' => $this->getValue('dependencies', []),
|
||||
'permissions' => $this->getValue('permissions', []),
|
||||
'roles' => $this->getValue('roles', []),
|
||||
'config' => $this->getValue('config', []),
|
||||
'hooks' => $this->getValue('hooks', []),
|
||||
'status' => $this->getValue('status', 'uninstalled'),
|
||||
'is_installed' => $this->getValue('is_installed', false),
|
||||
'has_settings' => $this->getValue('has_settings', false),
|
||||
'settings_route' => $this->getValue('settings_route'),
|
||||
'assets' => $this->getValue('assets'),
|
||||
// 업데이트 관련 필드
|
||||
'update_available' => $this->getValue('update_available', false),
|
||||
'update_source' => $this->getValue('update_source'),
|
||||
'latest_version' => $this->getValue('latest_version'),
|
||||
'file_version' => $this->getValue('file_version'),
|
||||
'github_url' => $this->getValue('github_url'),
|
||||
'github_changelog_url' => $this->getValue('github_changelog_url'),
|
||||
// pending/bundled 상태
|
||||
'is_pending' => $this->getValue('is_pending', false),
|
||||
'is_bundled' => $this->getValue('is_bundled', false),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_install' => 'core.plugins.install',
|
||||
'can_activate' => 'core.plugins.activate',
|
||||
'can_uninstall' => 'core.plugins.uninstall',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 상태를 텍스트로 반환합니다.
|
||||
*
|
||||
* @return string 플러그인 상태 (not_installed, active, inactive)
|
||||
*/
|
||||
protected function getStatusText(): string
|
||||
{
|
||||
if (! $this->getValue('is_installed', false)) {
|
||||
return 'not_installed';
|
||||
}
|
||||
|
||||
if ($this->getValue('is_active', false)) {
|
||||
return 'active';
|
||||
}
|
||||
|
||||
return 'inactive';
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 상세 정보를 배열로 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 상세 플러그인 정보
|
||||
*/
|
||||
public function toDetailArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'vendor' => $this->getValue('vendor'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version', '1.0.0'),
|
||||
'description' => $this->getLocalizedField('description'),
|
||||
'github_url' => $this->getValue('github_url'),
|
||||
'dependencies' => $this->getValue('dependencies', []),
|
||||
'status' => $this->getValue('status', 'uninstalled'),
|
||||
'is_installed' => $this->getValue('is_installed', false),
|
||||
'has_settings' => $this->getValue('has_settings', false),
|
||||
'settings_route' => $this->getValue('settings_route'),
|
||||
// 상세 정보
|
||||
'permissions' => $this->getValue('permissions', []),
|
||||
'roles' => $this->getValue('roles', []),
|
||||
'hooks' => $this->getValue('hooks', []),
|
||||
'config' => $this->getValue('config', []),
|
||||
'license' => $this->getValue('license'),
|
||||
'metadata' => $this->getValue('metadata', []),
|
||||
// 업데이트 관련 필드
|
||||
'update_available' => $this->getValue('update_available', false),
|
||||
'update_source' => $this->getValue('update_source'),
|
||||
'latest_version' => $this->getValue('latest_version'),
|
||||
'file_version' => $this->getValue('file_version'),
|
||||
'github_changelog_url' => $this->getValue('github_changelog_url'),
|
||||
// pending/bundled 상태
|
||||
'is_pending' => $this->getValue('is_pending', false),
|
||||
'is_bundled' => $this->getValue('is_bundled', false),
|
||||
// 타임스탬프
|
||||
'created_at' => $this->getValue('created_at'),
|
||||
'updated_at' => $this->getValue('updated_at'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 기본 정보만 반환합니다 (목록용).
|
||||
*
|
||||
* @return array<string, mixed> 기본 플러그인 정보
|
||||
*/
|
||||
public function toBasicArray(): array
|
||||
{
|
||||
return [
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version', '1.0.0'),
|
||||
'is_installed' => $this->getValue('is_installed', false),
|
||||
'is_active' => $this->getValue('is_active', false),
|
||||
'status' => $this->getStatusText(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치/제거 작업 시 의존성 정보를 포함합니다.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function withDependencies(): self
|
||||
{
|
||||
return $this->additional([
|
||||
'dependency_check' => $this->getDependencyStatus(),
|
||||
'required_by' => $this->getValue('required_by', []),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 의존성 상태를 확인하여 반환합니다.
|
||||
*
|
||||
* @return array<int, array<string, mixed>> 의존성 상태 배열
|
||||
*/
|
||||
protected function getDependencyStatus(): array
|
||||
{
|
||||
$dependencies = $this->getValue('dependencies', []);
|
||||
$status = [];
|
||||
|
||||
foreach ($dependencies as $dependency) {
|
||||
$status[] = [
|
||||
'name' => $dependency['name'] ?? $dependency,
|
||||
'version' => $dependency['version'] ?? '*',
|
||||
'satisfied' => $dependency['satisfied'] ?? false,
|
||||
];
|
||||
}
|
||||
|
||||
return $status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class RoleCollection extends ResourceCollection
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
|
||||
/**
|
||||
* 컬렉션 레벨 능력(can_*) 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string> 능력 키 => 권한 식별자 매핑
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'core.permissions.create',
|
||||
'can_update' => 'core.permissions.update',
|
||||
'can_delete' => 'core.permissions.delete',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 역할 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 역할 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => RoleResource::collection($this->collection),
|
||||
'abilities' => $this->resolveAbilitiesFromMap($this->abilityMap(), $request->user()),
|
||||
'pagination' => $this->resource instanceof \Illuminate\Pagination\LengthAwarePaginator ? [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Enums\ExtensionOwnerType;
|
||||
use App\Extension\ModuleManager;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class RoleResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 역할 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 배열 데이터
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'name' => $this->getLocalizedName(),
|
||||
'name_raw' => $this->getValue('name'),
|
||||
'description' => $this->getLocalizedDescription(),
|
||||
'description_raw' => $this->getValue('description'),
|
||||
'extension_type' => $this->getValue('extension_type'),
|
||||
'extension_identifier' => $this->getValue('extension_identifier'),
|
||||
'extension_name' => $this->getExtensionName(),
|
||||
'is_deletable' => is_object($this->resource) && method_exists($this->resource, 'isDeletable')
|
||||
? $this->resource->isDeletable()
|
||||
: true,
|
||||
'is_active' => $this->getValue('is_active', true),
|
||||
'users_count' => $this->when(
|
||||
$this->resource->users_count !== null,
|
||||
fn () => $this->resource->users_count
|
||||
),
|
||||
'permission_ids' => $this->when(
|
||||
$this->resource->relationLoaded('permissions'),
|
||||
fn () => $this->resource->permissions->pluck('id')->toArray()
|
||||
),
|
||||
'permission_values' => $this->when(
|
||||
$this->resource->relationLoaded('permissions'),
|
||||
fn () => $this->resource->permissions->map(fn ($p) => [
|
||||
'id' => $p->id,
|
||||
'scope_type' => $p->pivot->scope_type?->value ?? $p->pivot->scope_type,
|
||||
])->toArray()
|
||||
),
|
||||
'permissions' => $this->when(
|
||||
$this->resource->relationLoaded('permissions'),
|
||||
fn () => $this->buildHierarchicalPermissions($this->resource->permissions)
|
||||
),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 로케일별 이름을 반환합니다.
|
||||
*
|
||||
* @return string|null 확장 이름 또는 null
|
||||
*/
|
||||
protected function getExtensionName(): ?string
|
||||
{
|
||||
$extensionType = $this->resource->extension_type ?? null;
|
||||
$extensionIdentifier = $this->resource->extension_identifier ?? null;
|
||||
|
||||
if ($extensionType === null || $extensionIdentifier === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Enum 값 비교 (ExtensionOwnerType은 string-backed enum)
|
||||
$typeValue = $extensionType instanceof ExtensionOwnerType
|
||||
? $extensionType
|
||||
: ExtensionOwnerType::tryFrom($extensionType);
|
||||
|
||||
if ($typeValue === ExtensionOwnerType::Module) {
|
||||
$info = app(ModuleManager::class)->getModuleInfo($extensionIdentifier);
|
||||
|
||||
return $info['name'] ?? null;
|
||||
}
|
||||
|
||||
if ($typeValue === ExtensionOwnerType::Plugin) {
|
||||
$info = app(PluginManager::class)->getPluginInfo($extensionIdentifier);
|
||||
|
||||
return $info['name'] ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'core.permissions.create',
|
||||
'can_update' => 'core.permissions.update',
|
||||
'can_delete' => 'core.permissions.delete',
|
||||
'can_toggle_status' => 'core.permissions.update',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한을 계층형 구조로 변환합니다.
|
||||
*
|
||||
* @param Collection $permissions 역할에 할당된 권한 컬렉션
|
||||
* @return array 계층형 권한 구조
|
||||
*/
|
||||
protected function buildHierarchicalPermissions(Collection $permissions): array
|
||||
{
|
||||
if ($permissions->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 할당된 권한들의 ID 목록
|
||||
$assignedPermissionIds = $permissions->pluck('id')->toArray();
|
||||
|
||||
// 모든 관련 부모 권한 ID 수집 (category level)
|
||||
$parentIds = $permissions->pluck('parent_id')->filter()->unique()->toArray();
|
||||
|
||||
if (empty($parentIds)) {
|
||||
// 부모가 없으면 flat 구조 그대로 반환
|
||||
return PermissionResource::collection($permissions)->resolve();
|
||||
}
|
||||
|
||||
// 부모 권한들 조회 (category level)
|
||||
$categoryPermissions = Permission::whereIn('id', $parentIds)->get();
|
||||
|
||||
// 그 위의 부모 권한 ID 수집 (module level)
|
||||
$moduleParentIds = $categoryPermissions->pluck('parent_id')->filter()->unique()->toArray();
|
||||
|
||||
// module level 권한들 조회
|
||||
$modulePermissions = ! empty($moduleParentIds)
|
||||
? Permission::whereIn('id', $moduleParentIds)->get()
|
||||
: collect();
|
||||
|
||||
// 계층형 구조 생성
|
||||
$hierarchy = [];
|
||||
|
||||
foreach ($modulePermissions as $modulePermission) {
|
||||
$moduleData = $this->formatPermissionNode($modulePermission, $assignedPermissionIds);
|
||||
$moduleData['children'] = [];
|
||||
|
||||
// 이 모듈에 속한 카테고리들
|
||||
$moduleCategories = $categoryPermissions->where('parent_id', $modulePermission->id);
|
||||
|
||||
foreach ($moduleCategories as $categoryPermission) {
|
||||
$categoryData = $this->formatPermissionNode($categoryPermission, $assignedPermissionIds);
|
||||
$categoryData['children'] = [];
|
||||
|
||||
// 이 카테고리에 속한 권한들 (역할에 할당된 것만)
|
||||
$categoryChildPermissions = $permissions->where('parent_id', $categoryPermission->id);
|
||||
|
||||
foreach ($categoryChildPermissions as $childPermission) {
|
||||
$categoryData['children'][] = $this->formatPermissionNode($childPermission, $assignedPermissionIds);
|
||||
}
|
||||
|
||||
if (! empty($categoryData['children'])) {
|
||||
$moduleData['children'][] = $categoryData;
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($moduleData['children'])) {
|
||||
$hierarchy[] = $moduleData;
|
||||
}
|
||||
}
|
||||
|
||||
// module level 부모가 없는 category들 처리 (2단계 구조인 경우)
|
||||
$orphanCategories = $categoryPermissions->whereNull('parent_id');
|
||||
foreach ($orphanCategories as $categoryPermission) {
|
||||
$categoryData = $this->formatPermissionNode($categoryPermission, $assignedPermissionIds);
|
||||
$categoryData['children'] = [];
|
||||
|
||||
$categoryChildPermissions = $permissions->where('parent_id', $categoryPermission->id);
|
||||
foreach ($categoryChildPermissions as $childPermission) {
|
||||
$categoryData['children'][] = $this->formatPermissionNode($childPermission, $assignedPermissionIds);
|
||||
}
|
||||
|
||||
if (! empty($categoryData['children'])) {
|
||||
$hierarchy[] = $categoryData;
|
||||
}
|
||||
}
|
||||
|
||||
return $hierarchy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 노드를 포맷합니다.
|
||||
*
|
||||
* @param Permission $permission 권한 모델
|
||||
* @param array $assignedPermissionIds 할당된 권한 ID 목록
|
||||
* @return array 포맷된 권한 데이터
|
||||
*/
|
||||
protected function formatPermissionNode(Permission $permission, array $assignedPermissionIds): array
|
||||
{
|
||||
$node = [
|
||||
'id' => $permission->id,
|
||||
'parent_id' => $permission->parent_id,
|
||||
'identifier' => $permission->identifier,
|
||||
'name' => $permission->getLocalizedName(),
|
||||
'name_raw' => $permission->name,
|
||||
'description' => $permission->getLocalizedDescription(),
|
||||
'description_raw' => $permission->description,
|
||||
'extension_type' => $permission->extension_type?->value,
|
||||
'extension_identifier' => $permission->extension_identifier,
|
||||
'resource_route_key' => $permission->resource_route_key,
|
||||
'owner_key' => $permission->owner_key,
|
||||
'order' => $permission->order,
|
||||
'is_assigned' => in_array($permission->id, $assignedPermissionIds),
|
||||
'is_assignable' => $permission->isAssignable(),
|
||||
];
|
||||
|
||||
// 피벗 scope_type 포함 (할당된 권한만)
|
||||
if ($node['is_assigned'] && $permission->pivot) {
|
||||
$node['scope_type'] = $permission->pivot->scope_type?->value ?? $permission->pivot->scope_type;
|
||||
}
|
||||
|
||||
return $node;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class ScheduleCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* 스케줄 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 스케줄 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($schedule) {
|
||||
return (new ScheduleResource($schedule))->toListArray(request());
|
||||
}),
|
||||
'pagination' => $this->when($this->resource instanceof LengthAwarePaginator, [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 통계가 포함된 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @param array $statistics 통계 데이터 배열
|
||||
* @return array<string, mixed> 통계 정보가 포함된 스케줄 컬렉션
|
||||
*/
|
||||
public function withStatistics(array $statistics = []): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($schedule) {
|
||||
return (new ScheduleResource($schedule))->toListArray(request());
|
||||
}),
|
||||
'statistics' => $statistics,
|
||||
'pagination' => $this->when($this->resource instanceof LengthAwarePaginator, [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class ScheduleHistoryCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* 스케줄 실행 이력 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 이력 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($history) {
|
||||
return (new ScheduleHistoryResource($history))->toListArray();
|
||||
}),
|
||||
'pagination' => $this->when($this->resource instanceof LengthAwarePaginator, [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ScheduleHistoryResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 스케줄 실행 이력 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 이력 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'schedule_id' => $this->getValue('schedule_id'),
|
||||
'started_at' => $this->when(
|
||||
$this->getValue('started_at'),
|
||||
fn () => $this->formatDateTimeForUser($this->getValue('started_at'))
|
||||
),
|
||||
'ended_at' => $this->when(
|
||||
$this->getValue('ended_at'),
|
||||
fn () => $this->formatDateTimeForUser($this->getValue('ended_at'))
|
||||
),
|
||||
'duration' => $this->getValue('duration'),
|
||||
'duration_formatted' => $this->resource->duration_formatted ?? null,
|
||||
'status' => $this->getValue('status')?->value ?? $this->getValue('status'),
|
||||
'status_label' => $this->getStatusLabel(),
|
||||
'exit_code' => $this->getValue('exit_code'),
|
||||
'memory_usage' => $this->getValue('memory_usage'),
|
||||
'memory_usage_formatted' => $this->resource->memory_usage_formatted ?? null,
|
||||
'output' => $this->getValue('output'),
|
||||
'error_output' => $this->getValue('error_output'),
|
||||
'trigger_type' => $this->getValue('trigger_type')?->value ?? $this->getValue('trigger_type'),
|
||||
'trigger_type_label' => $this->getTriggerTypeLabel(),
|
||||
|
||||
// 관계형 데이터
|
||||
'triggered_by' => $this->whenLoaded('triggeredBy', function () {
|
||||
$user = $this->getValue('triggeredBy');
|
||||
return $user ? [
|
||||
'uuid' => $user->uuid,
|
||||
'name' => $user->name,
|
||||
] : null;
|
||||
}),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 간략한 이력 정보
|
||||
*/
|
||||
public function toListArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'schedule_id' => $this->getValue('schedule_id'),
|
||||
'started_at' => $this->getValue('started_at')
|
||||
? $this->formatDateTimeForUser($this->getValue('started_at'))
|
||||
: null,
|
||||
'ended_at' => $this->getValue('ended_at')
|
||||
? $this->formatDateTimeForUser($this->getValue('ended_at'))
|
||||
: null,
|
||||
'duration' => $this->getValue('duration'),
|
||||
'duration_formatted' => $this->resource->duration_formatted ?? null,
|
||||
'status' => $this->getValue('status')?->value ?? $this->getValue('status'),
|
||||
'status_label' => $this->getStatusLabel(),
|
||||
'exit_code' => $this->getValue('exit_code'),
|
||||
'memory_usage_formatted' => $this->resource->memory_usage_formatted ?? null,
|
||||
'trigger_type' => $this->getValue('trigger_type')?->value ?? $this->getValue('trigger_type'),
|
||||
'trigger_type_label' => $this->getTriggerTypeLabel(),
|
||||
'triggered_by' => $this->resource->relationLoaded('triggeredBy') && $this->resource->triggeredBy
|
||||
? [
|
||||
'uuid' => $this->resource->triggeredBy->uuid,
|
||||
'name' => $this->resource->triggeredBy->name,
|
||||
]
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 상태 라벨을 반환합니다.
|
||||
*
|
||||
* @return string|null 상태 라벨
|
||||
*/
|
||||
protected function getStatusLabel(): ?string
|
||||
{
|
||||
$status = $this->getValue('status');
|
||||
|
||||
if (!$status) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_object($status) && method_exists($status, 'label')) {
|
||||
return $status->label();
|
||||
}
|
||||
|
||||
return __('schedule.result.' . $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 트리거 유형 라벨을 반환합니다.
|
||||
*
|
||||
* @return string|null 유형 라벨
|
||||
*/
|
||||
protected function getTriggerTypeLabel(): ?string
|
||||
{
|
||||
$type = $this->getValue('trigger_type');
|
||||
|
||||
if (!$type) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_object($type) && method_exists($type, 'label')) {
|
||||
return $type->label();
|
||||
}
|
||||
|
||||
return __('schedule.trigger_type.' . $type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ScheduleResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 스케줄 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 스케줄 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'name' => $this->getValue('name'),
|
||||
'description' => $this->getValue('description'),
|
||||
'type' => $this->getValue('type')?->value ?? $this->getValue('type'),
|
||||
'type_label' => $this->getTypeLabel(),
|
||||
'command' => $this->getValue('command'),
|
||||
'expression' => $this->getValue('expression'),
|
||||
'frequency' => $this->getValue('frequency')?->value ?? $this->getValue('frequency'),
|
||||
'frequency_label' => $this->getFrequencyLabel(),
|
||||
'without_overlapping' => (bool) $this->getValue('without_overlapping'),
|
||||
'run_in_maintenance' => (bool) $this->getValue('run_in_maintenance'),
|
||||
'timeout' => $this->getValue('timeout'),
|
||||
'is_active' => (bool) $this->getValue('is_active'),
|
||||
'last_result' => $this->getValue('last_result')?->value ?? $this->getValue('last_result'),
|
||||
'last_result_label' => $this->getLastResultLabel(),
|
||||
'last_run_at' => $this->when(
|
||||
$this->getValue('last_run_at'),
|
||||
fn () => $this->formatDateTimeForUser($this->getValue('last_run_at'))
|
||||
),
|
||||
'last_duration' => $this->resource->last_duration ?? null,
|
||||
'next_run_at' => $this->when(
|
||||
$this->getValue('next_run_at'),
|
||||
fn () => $this->formatDateTimeForUser($this->getValue('next_run_at'))
|
||||
),
|
||||
'extension_type' => $this->getValue('extension_type')?->value ?? $this->getValue('extension_type'),
|
||||
'extension_identifier' => $this->getValue('extension_identifier'),
|
||||
|
||||
// 관계형 데이터
|
||||
'creator' => $this->whenLoaded('creator', function () {
|
||||
$creator = $this->getValue('creator');
|
||||
|
||||
return $creator ? [
|
||||
'uuid' => $creator->uuid,
|
||||
'name' => $creator->name,
|
||||
] : null;
|
||||
}),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'core.schedules.create',
|
||||
'can_update' => 'core.schedules.update',
|
||||
'can_delete' => 'core.schedules.delete',
|
||||
'can_run' => 'core.schedules.run',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @param Request|null $request HTTP 요청
|
||||
* @return array<string, mixed> 간략한 스케줄 정보
|
||||
*/
|
||||
public function toListArray(?Request $request = null): array
|
||||
{
|
||||
$request = $request ?? request();
|
||||
|
||||
return [
|
||||
'id' => $this->getValue('id'),
|
||||
'name' => $this->getValue('name'),
|
||||
'type' => $this->getValue('type')?->value ?? $this->getValue('type'),
|
||||
'type_label' => $this->getTypeLabel(),
|
||||
'command' => $this->getValue('command'),
|
||||
'expression' => $this->getValue('expression'),
|
||||
'frequency' => $this->getValue('frequency')?->value ?? $this->getValue('frequency'),
|
||||
'frequency_label' => $this->getFrequencyLabel(),
|
||||
'without_overlapping' => (bool) $this->getValue('without_overlapping'),
|
||||
'run_in_maintenance' => (bool) $this->getValue('run_in_maintenance'),
|
||||
'is_active' => (bool) $this->getValue('is_active'),
|
||||
'last_result' => $this->getValue('last_result')?->value ?? $this->getValue('last_result'),
|
||||
'last_result_label' => $this->getLastResultLabel(),
|
||||
'last_run_at' => $this->getValue('last_run_at')
|
||||
? $this->formatDateTimeForUser($this->getValue('last_run_at'))
|
||||
: null,
|
||||
'last_duration' => $this->resource->last_duration ?? null,
|
||||
'next_run_at' => $this->getValue('next_run_at')
|
||||
? $this->formatDateTimeForUser($this->getValue('next_run_at'))
|
||||
: null,
|
||||
'creator' => $this->resource->relationLoaded('creator') && $this->resource->creator
|
||||
? [
|
||||
'uuid' => $this->resource->creator->uuid,
|
||||
'name' => $this->resource->creator->name,
|
||||
]
|
||||
: null,
|
||||
'created_at' => $this->getValue('created_at')
|
||||
? $this->formatDateForUser($this->getValue('created_at'))
|
||||
: null,
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 작업 유형 라벨을 반환합니다.
|
||||
*
|
||||
* @return string|null 유형 라벨
|
||||
*/
|
||||
protected function getTypeLabel(): ?string
|
||||
{
|
||||
$type = $this->getValue('type');
|
||||
|
||||
if (! $type) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_object($type) && method_exists($type, 'label')) {
|
||||
return $type->label();
|
||||
}
|
||||
|
||||
return __('schedule.type.'.$type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 실행 주기 라벨을 반환합니다.
|
||||
*
|
||||
* @return string|null 주기 라벨
|
||||
*/
|
||||
protected function getFrequencyLabel(): ?string
|
||||
{
|
||||
$frequency = $this->getValue('frequency');
|
||||
|
||||
if (! $frequency) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_object($frequency) && method_exists($frequency, 'label')) {
|
||||
return $frequency->label();
|
||||
}
|
||||
|
||||
return __('schedule.frequency.'.$frequency);
|
||||
}
|
||||
|
||||
/**
|
||||
* 마지막 실행 결과 라벨을 반환합니다.
|
||||
*
|
||||
* @return string|null 결과 라벨
|
||||
*/
|
||||
protected function getLastResultLabel(): ?string
|
||||
{
|
||||
$result = $this->getValue('last_result');
|
||||
|
||||
if (! $result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_object($result) && method_exists($result, 'label')) {
|
||||
return $result->label();
|
||||
}
|
||||
|
||||
return __('schedule.result.'.$result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class SettingResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 설정 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 설정 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'key' => $this->getValue('key'),
|
||||
'value' => $this->getValue('value'),
|
||||
'type' => $this->getValue('type', 'string'),
|
||||
'description' => $this->getValue('description'),
|
||||
'group' => $this->getValue('group', 'general'),
|
||||
'is_public' => $this->getValue('is_public', false),
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_update' => 'core.settings.update',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 키-값 쌍만 반환하는 단순한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 키-값 쌍 배열
|
||||
*/
|
||||
public function toSimpleArray(): array
|
||||
{
|
||||
return [
|
||||
$this->getValue('key') => $this->getValue('value'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 시스템 설정 리소스
|
||||
*
|
||||
* 배열 기반 설정 데이터에 abilities 메타를 추가합니다.
|
||||
*/
|
||||
class SettingsResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* Settings는 Eloquent 모델이 아닌 배열이므로
|
||||
* 원본 배열에 abilities 메타를 병합합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 설정 데이터 + abilities
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$data = is_array($this->resource) ? $this->resource : parent::toArray($request);
|
||||
|
||||
return array_merge($data, $this->resourceMeta($request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_update' => 'core.settings.update',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
/**
|
||||
* 템플릿 컬렉션 리소스
|
||||
*
|
||||
* 템플릿 목록을 다양한 형태로 변환하여 반환합니다.
|
||||
*/
|
||||
class TemplateCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* 템플릿 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 템플릿 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($template) {
|
||||
return new TemplateResource($template);
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 마켓플레이스용 템플릿 목록 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 마켓플레이스용 템플릿 목록
|
||||
*/
|
||||
public function toMarketplaceArray(): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->collection->map(function ($template) {
|
||||
return (new TemplateResource($template))->toMarketplaceArray();
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 템플릿 목록을 활성/비활성으로 구분하여 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 활성/비활성 템플릿 목록
|
||||
*/
|
||||
public function toInstalledArray(): array
|
||||
{
|
||||
$active = $this->collection->filter(fn ($t) => ($t['status'] ?? '') === 'active');
|
||||
$inactive = $this->collection->filter(fn ($t) => ($t['status'] ?? '') === 'inactive');
|
||||
|
||||
return [
|
||||
'active' => $active->map(function ($template) {
|
||||
return (new TemplateResource($template))->toDependencyArray();
|
||||
})->values(),
|
||||
'inactive' => $inactive->map(function ($template) {
|
||||
return (new TemplateResource($template))->toDependencyArray();
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* admin/user 템플릿으로 구분하여 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> admin 템플릿과 user 템플릿 목록
|
||||
*/
|
||||
public function toByTypeArray(): array
|
||||
{
|
||||
$admin = $this->collection->filter(fn ($t) => ($t['type'] ?? '') === 'admin');
|
||||
$user = $this->collection->filter(fn ($t) => ($t['type'] ?? '') === 'user');
|
||||
|
||||
return [
|
||||
'admin' => $admin->map(function ($template) {
|
||||
return (new TemplateResource($template))->toDependencyArray();
|
||||
})->values(),
|
||||
'user' => $user->map(function ($template) {
|
||||
return (new TemplateResource($template))->toMarketplaceArray();
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 응답에 추가 메타데이터를 포함합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 메타데이터 배열
|
||||
*/
|
||||
public function with(Request $request): array
|
||||
{
|
||||
$collection = $this->collection;
|
||||
|
||||
return [
|
||||
'meta' => [
|
||||
'total_templates' => $collection->count(),
|
||||
'active_templates' => $collection->filter(fn ($t) => ($t['status'] ?? '') === 'active')->count(),
|
||||
'admin_templates' => $collection->filter(fn ($t) => ($t['type'] ?? '') === 'admin')->count(),
|
||||
'user_templates' => $collection->filter(fn ($t) => ($t['type'] ?? '') === 'user')->count(),
|
||||
'installed_templates' => $collection->filter(fn ($t) => ($t['status'] ?? '') !== 'not_installed')->count(),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use Composer\Semver\Semver;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\App;
|
||||
|
||||
/**
|
||||
* 템플릿 API 리소스
|
||||
*
|
||||
* name, description 필드는 현재 로케일에 맞는 값을 반환합니다.
|
||||
*/
|
||||
class TemplateResource extends BaseApiResource
|
||||
{
|
||||
/**
|
||||
* 템플릿 목록용 리소스를 배열로 변환합니다 (간소화된 정보).
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 템플릿 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'vendor' => $this->getValue('vendor'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'type' => $this->getValue('type'),
|
||||
'status' => $this->getValue('status'),
|
||||
'description' => $this->getLocalizedField('description'),
|
||||
'dependencies' => $this->getDependenciesSummary(),
|
||||
'dependencies_met' => $this->areDependenciesMet(),
|
||||
// 업데이트 관련 필드
|
||||
'update_available' => $this->getValue('update_available', false),
|
||||
'update_source' => $this->getValue('update_source'),
|
||||
'latest_version' => $this->getValue('latest_version'),
|
||||
'file_version' => $this->getValue('file_version'),
|
||||
'github_url' => $this->getValue('github_url'),
|
||||
'github_changelog_url' => $this->getValue('github_changelog_url'),
|
||||
// pending/bundled 상태
|
||||
'is_pending' => $this->getValue('is_pending', false),
|
||||
'is_bundled' => $this->getValue('is_bundled', false),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_install' => 'core.templates.install',
|
||||
'can_activate' => 'core.templates.activate',
|
||||
'can_uninstall' => 'core.templates.uninstall',
|
||||
'can_edit_layouts' => 'core.templates.layouts.edit',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 템플릿 상세 정보를 배열로 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 상세 템플릿 정보
|
||||
*/
|
||||
public function toDetailArray(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'vendor' => $this->getValue('vendor'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'latest_version' => $this->getValue('latest_version'),
|
||||
'update_available' => $this->getValue('update_available', false),
|
||||
'update_source' => $this->getValue('update_source'),
|
||||
'file_version' => $this->getValue('file_version'),
|
||||
'type' => $this->getValue('type'),
|
||||
'status' => $this->getValue('status'),
|
||||
'description' => $this->getLocalizedField('description'),
|
||||
'github_url' => $this->getValue('github_url'),
|
||||
'github_changelog_url' => $this->getValue('github_changelog_url'),
|
||||
// pending/bundled 상태
|
||||
'is_pending' => $this->getValue('is_pending', false),
|
||||
'is_bundled' => $this->getValue('is_bundled', false),
|
||||
// 상세 정보
|
||||
'locales' => $this->getValue('locales', []),
|
||||
'layouts_count' => $this->getValue('layouts_count', 0),
|
||||
'components' => $this->getValue('components', ['basic' => [], 'composite' => []]),
|
||||
'license' => $this->getValue('license'),
|
||||
'metadata' => $this->getValue('metadata', []),
|
||||
// 의존성 상세 정보
|
||||
'dependencies' => $this->getDetailedDependencies(),
|
||||
// 타임스탬프
|
||||
'created_at' => $this->getValue('created_at'),
|
||||
'updated_at' => $this->getValue('updated_at'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 마켓플레이스용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 마켓플레이스용 템플릿 정보
|
||||
*/
|
||||
public function toMarketplaceArray(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'type' => $this->getValue('type'),
|
||||
'status' => $this->getValue('status'),
|
||||
'description' => $this->getLocalizedField('description'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 의존성 체크용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 의존성 확인용 템플릿 정보
|
||||
*/
|
||||
public function toDependencyArray(): array
|
||||
{
|
||||
return [
|
||||
'identifier' => $this->getValue('identifier'),
|
||||
'name' => $this->getLocalizedField('name'),
|
||||
'version' => $this->getValue('version'),
|
||||
'type' => $this->getValue('type'),
|
||||
'status' => $this->getValue('status'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 필드 값을 현재 로케일에 맞게 반환합니다.
|
||||
*
|
||||
* @param string $field 필드명
|
||||
* @return string|array|null 다국어 값
|
||||
*/
|
||||
protected function getLocalizedField(string $field)
|
||||
{
|
||||
$value = $this->getValue($field);
|
||||
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 이미 문자열이면 그대로 반환
|
||||
if (is_string($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// 배열(다국어)이면 현재 로케일에 맞는 값 반환
|
||||
if (is_array($value)) {
|
||||
$locale = App::getLocale();
|
||||
$fallbackLocale = config('app.fallback_locale', 'ko');
|
||||
|
||||
return $value[$locale] ?? $value[$fallbackLocale] ?? reset($value) ?: null;
|
||||
}
|
||||
|
||||
// Model의 getLocalizedName() 등의 메서드가 있으면 사용
|
||||
$methodName = 'getLocalized'.ucfirst($field);
|
||||
if (is_object($this->resource) && method_exists($this->resource, $methodName)) {
|
||||
return $this->resource->{$methodName}();
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 의존성 요약 정보를 반환합니다 (목록용).
|
||||
*
|
||||
* @return array 의존성 목록 ['modules' => [...], 'plugins' => [...]]
|
||||
*/
|
||||
protected function getDependenciesSummary(): array
|
||||
{
|
||||
$dependencies = $this->getValue('dependencies', []);
|
||||
|
||||
$moduleRepository = app(ModuleRepositoryInterface::class);
|
||||
$pluginRepository = app(PluginRepositoryInterface::class);
|
||||
|
||||
$modules = [];
|
||||
$plugins = [];
|
||||
|
||||
// 모듈 의존성 정보 추출 (identifier + name + type)
|
||||
if (isset($dependencies['modules']) && is_array($dependencies['modules'])) {
|
||||
foreach ($dependencies['modules'] as $moduleIdentifier => $versionConstraint) {
|
||||
$module = $moduleRepository->findByIdentifier($moduleIdentifier);
|
||||
$modules[] = [
|
||||
'identifier' => $moduleIdentifier,
|
||||
'name' => $module ? $this->getExtensionName($module) : $moduleIdentifier,
|
||||
'type' => 'module',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 플러그인 의존성 정보 추출 (identifier + name + type)
|
||||
if (isset($dependencies['plugins']) && is_array($dependencies['plugins'])) {
|
||||
foreach ($dependencies['plugins'] as $pluginIdentifier => $versionConstraint) {
|
||||
$plugin = $pluginRepository->findByIdentifier($pluginIdentifier);
|
||||
$plugins[] = [
|
||||
'identifier' => $pluginIdentifier,
|
||||
'name' => $plugin ? $this->getExtensionName($plugin) : $pluginIdentifier,
|
||||
'type' => 'plugin',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'modules' => $modules,
|
||||
'plugins' => $plugins,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 의존성이 충족되었는지 확인합니다.
|
||||
*
|
||||
* @return bool 모든 의존성 충족 여부
|
||||
*/
|
||||
protected function areDependenciesMet(): bool
|
||||
{
|
||||
$dependencies = $this->getValue('dependencies', []);
|
||||
|
||||
// 의존성이 없으면 충족으로 간주
|
||||
if (empty($dependencies)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$moduleRepository = app(ModuleRepositoryInterface::class);
|
||||
$pluginRepository = app(PluginRepositoryInterface::class);
|
||||
|
||||
// 모듈 의존성 확인
|
||||
if (isset($dependencies['modules']) && is_array($dependencies['modules'])) {
|
||||
foreach ($dependencies['modules'] as $moduleIdentifier => $versionConstraint) {
|
||||
$module = $moduleRepository->findActiveByIdentifier($moduleIdentifier);
|
||||
if (! $module) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 버전 체크
|
||||
if (! $this->checkVersionConstraint($module->version, $versionConstraint)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 플러그인 의존성 확인
|
||||
if (isset($dependencies['plugins']) && is_array($dependencies['plugins'])) {
|
||||
foreach ($dependencies['plugins'] as $pluginIdentifier => $versionConstraint) {
|
||||
$plugin = $pluginRepository->findActiveByIdentifier($pluginIdentifier);
|
||||
if (! $plugin) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 버전 체크
|
||||
if (! $this->checkVersionConstraint($plugin->version, $versionConstraint)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 상세 의존성 정보를 반환합니다 (상세 모달용).
|
||||
*
|
||||
* @return array{modules: array, plugins: array} 상세 의존성 정보
|
||||
*/
|
||||
protected function getDetailedDependencies(): array
|
||||
{
|
||||
$dependencies = $this->getValue('dependencies', []);
|
||||
|
||||
$moduleRepository = app(ModuleRepositoryInterface::class);
|
||||
$pluginRepository = app(PluginRepositoryInterface::class);
|
||||
|
||||
$moduleDeps = [];
|
||||
$pluginDeps = [];
|
||||
|
||||
// 모듈 의존성 상세 정보
|
||||
if (isset($dependencies['modules']) && is_array($dependencies['modules'])) {
|
||||
foreach ($dependencies['modules'] as $moduleIdentifier => $versionConstraint) {
|
||||
$module = $moduleRepository->findByIdentifier($moduleIdentifier);
|
||||
$activeModule = $moduleRepository->findActiveByIdentifier($moduleIdentifier);
|
||||
|
||||
$installedVersion = $module?->version;
|
||||
$isActive = (bool) $activeModule;
|
||||
$isMet = $isActive && $installedVersion && $this->checkVersionConstraint($installedVersion, $versionConstraint);
|
||||
|
||||
$moduleDeps[] = [
|
||||
'identifier' => $moduleIdentifier,
|
||||
'name' => $this->getExtensionName($module),
|
||||
'required_version' => $versionConstraint,
|
||||
'installed_version' => $installedVersion,
|
||||
'is_active' => $isActive,
|
||||
'is_met' => $isMet,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 플러그인 의존성 상세 정보
|
||||
if (isset($dependencies['plugins']) && is_array($dependencies['plugins'])) {
|
||||
foreach ($dependencies['plugins'] as $pluginIdentifier => $versionConstraint) {
|
||||
$plugin = $pluginRepository->findByIdentifier($pluginIdentifier);
|
||||
$activePlugin = $pluginRepository->findActiveByIdentifier($pluginIdentifier);
|
||||
|
||||
$installedVersion = $plugin?->version;
|
||||
$isActive = (bool) $activePlugin;
|
||||
$isMet = $isActive && $installedVersion && $this->checkVersionConstraint($installedVersion, $versionConstraint);
|
||||
|
||||
$pluginDeps[] = [
|
||||
'identifier' => $pluginIdentifier,
|
||||
'name' => $this->getExtensionName($plugin),
|
||||
'required_version' => $versionConstraint,
|
||||
'installed_version' => $installedVersion,
|
||||
'is_active' => $isActive,
|
||||
'is_met' => $isMet,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'modules' => $moduleDeps,
|
||||
'plugins' => $pluginDeps,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 버전 제약조건을 검증합니다.
|
||||
*
|
||||
* @param string $installedVersion 설치된 버전
|
||||
* @param string $versionConstraint 요구 버전 제약조건 (예: '>=1.0.0', '^2.0', '~1.2.3')
|
||||
* @return bool 제약조건 충족 여부
|
||||
*/
|
||||
protected function checkVersionConstraint(string $installedVersion, string $versionConstraint): bool
|
||||
{
|
||||
try {
|
||||
return Semver::satisfies($installedVersion, $versionConstraint);
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장(모듈/플러그인)의 다국어 이름을 반환합니다.
|
||||
*
|
||||
* @param object|null $extension 확장 모델
|
||||
* @return string|null 다국어 이름
|
||||
*/
|
||||
protected function getExtensionName(?object $extension): ?string
|
||||
{
|
||||
if (! $extension) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$name = $extension->name;
|
||||
|
||||
// 다국어 배열인 경우
|
||||
if (is_array($name)) {
|
||||
$locale = App::getLocale();
|
||||
$fallbackLocale = config('app.fallback_locale', 'ko');
|
||||
|
||||
return $name[$locale] ?? $name[$fallbackLocale] ?? reset($name) ?: null;
|
||||
}
|
||||
|
||||
// JSON 문자열인 경우
|
||||
if (is_string($name) && str_starts_with($name, '{')) {
|
||||
$decoded = json_decode($name, true);
|
||||
if (is_array($decoded)) {
|
||||
$locale = App::getLocale();
|
||||
$fallbackLocale = config('app.fallback_locale', 'ko');
|
||||
|
||||
return $decoded[$locale] ?? $decoded[$fallbackLocale] ?? reset($decoded) ?: null;
|
||||
}
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Traits;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* 권한(ability) 체크 공통 로직을 제공합니다.
|
||||
*
|
||||
* BaseApiResource와 ResourceCollection 양쪽에서 사용하여
|
||||
* checkAbility() 로직 중복을 방지합니다.
|
||||
*/
|
||||
trait HasAbilityCheck
|
||||
{
|
||||
/**
|
||||
* 단일 permission identifier를 체크합니다.
|
||||
* Gate/Policy 미사용 — User 모델 직접 호출.
|
||||
*
|
||||
* @param string $ability Permission identifier
|
||||
* @param User|null $user 현재 사용자 (null = Guest)
|
||||
* @return bool 권한 보유 여부
|
||||
*/
|
||||
protected function checkAbility(string $ability, ?User $user): bool
|
||||
{
|
||||
return PermissionHelper::check($ability, $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 능력 맵을 불리언으로 변환합니다.
|
||||
*
|
||||
* 권한 체크 후 scope_type 기반 스코프 접근 체크를 수행합니다.
|
||||
*
|
||||
* @param array<string, string> $map ['can_update' => 'module.entity.update', ...]
|
||||
* @param User|null $user 현재 사용자
|
||||
* @return array<string, bool> 능력 불리언 맵
|
||||
*/
|
||||
protected function resolveAbilitiesFromMap(array $map, ?User $user): array
|
||||
{
|
||||
if (empty($map)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect($map)
|
||||
->mapWithKeys(function (string $identifier, string $key) use ($user) {
|
||||
$hasPermission = PermissionHelper::check($identifier, $user);
|
||||
|
||||
// 권한이 없으면 스코프 체크 불필요
|
||||
if (! $hasPermission) {
|
||||
return [$key => false];
|
||||
}
|
||||
|
||||
// 리소스 모델이 있으면 스코프 접근 체크
|
||||
// JsonResource 이중 래핑 시 내부 모델까지 추출
|
||||
$resource = $this->resource;
|
||||
while ($resource instanceof \Illuminate\Http\Resources\Json\JsonResource) {
|
||||
$resource = $resource->resource;
|
||||
}
|
||||
if ($resource instanceof \Illuminate\Database\Eloquent\Model) {
|
||||
return [$key => PermissionHelper::checkScopeAccess($resource, $identifier, $user)];
|
||||
}
|
||||
|
||||
return [$key => true];
|
||||
})
|
||||
->toArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Traits;
|
||||
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* 컬렉션 항목에 순번(number)을 부여하는 Trait
|
||||
*
|
||||
* 페이지네이션 정보와 정렬 방향을 기반으로 각 항목에 순번을 계산합니다.
|
||||
* - 내림차순(desc): 역순 (total, total-1, ...)
|
||||
* - 오름차순(asc): 기본순 (1, 2, 3, ...)
|
||||
*/
|
||||
trait HasRowNumber
|
||||
{
|
||||
/**
|
||||
* 순번이 포함된 데이터 매핑을 수행합니다.
|
||||
*
|
||||
* @param callable $callback 각 항목을 변환하는 콜백 함수
|
||||
* @param string|null $sortOrder 정렬 방향 (asc|desc), null인 경우 request에서 추출
|
||||
* @return Collection 순번이 포함된 변환된 컬렉션
|
||||
*/
|
||||
protected function mapWithRowNumber(callable $callback, ?string $sortOrder = null): Collection
|
||||
{
|
||||
$sortOrder = $sortOrder ?? request()->input('sort_order', 'desc');
|
||||
|
||||
// 페이지네이션이 아닌 경우 단순 인덱스 기반 순번 부여
|
||||
if (! $this->resource instanceof LengthAwarePaginator) {
|
||||
return $this->collection->map(function ($item, $index) use ($callback, $sortOrder) {
|
||||
$total = $this->collection->count();
|
||||
$number = $sortOrder === 'asc' ? $index + 1 : $total - $index;
|
||||
$data = $callback($item);
|
||||
|
||||
return array_merge(['number' => $number], $data);
|
||||
});
|
||||
}
|
||||
|
||||
// 페이지네이션 정보 추출
|
||||
$total = $this->resource->total();
|
||||
$perPage = $this->resource->perPage();
|
||||
$currentPage = $this->resource->currentPage();
|
||||
|
||||
return $this->collection->map(function ($item, $index) use ($callback, $sortOrder, $total, $perPage, $currentPage) {
|
||||
$number = $this->calculateRowNumber($index, $sortOrder, $total, $perPage, $currentPage);
|
||||
$data = $callback($item);
|
||||
|
||||
return array_merge(['number' => $number], $data);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 순번을 계산합니다.
|
||||
*
|
||||
* @param int $index 현재 항목의 인덱스 (0부터 시작)
|
||||
* @param string $sortOrder 정렬 방향 (asc|desc)
|
||||
* @param int $total 전체 항목 수
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @param int $currentPage 현재 페이지 번호
|
||||
* @return int 계산된 순번
|
||||
*/
|
||||
protected function calculateRowNumber(
|
||||
int $index,
|
||||
string $sortOrder,
|
||||
int $total,
|
||||
int $perPage,
|
||||
int $currentPage
|
||||
): int {
|
||||
if ($sortOrder === 'asc') {
|
||||
// 오름차순: 1, 2, 3, ... (페이지별 연속)
|
||||
// 예: 2페이지 → ((2-1) * 10) + 0 + 1 = 11, 12, 13, ...
|
||||
return (($currentPage - 1) * $perPage) + $index + 1;
|
||||
}
|
||||
|
||||
// 내림차순: total, total-1, ... (역순)
|
||||
// 예: 총 30개, 2페이지 → 30 - ((2-1) * 10) - 0 = 20, 19, 18, ...
|
||||
return $total - (($currentPage - 1) * $perPage) - $index;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Http\Resources\Traits\HasAbilityCheck;
|
||||
use App\Http\Resources\Traits\HasRowNumber;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class UserCollection extends ResourceCollection
|
||||
{
|
||||
use HasAbilityCheck;
|
||||
use HasRowNumber;
|
||||
|
||||
/**
|
||||
* 컬렉션 레벨 능력(can_*) 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string> 능력 키 => 권한 식별자 매핑
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_create' => 'core.users.create',
|
||||
'can_update' => 'core.users.update',
|
||||
'can_delete' => 'core.users.delete',
|
||||
'can_assign_roles' => 'core.permissions.update',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 컬렉션을 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<int|string, mixed> 변환된 사용자 컬렉션 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->mapWithRowNumber(function ($user) {
|
||||
return (new UserResource($user))->toListArray(request());
|
||||
}),
|
||||
'pagination' => $this->when($this->resource instanceof \Illuminate\Pagination\LengthAwarePaginator, [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 통계가 포함된 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @param array $statistics 통계 데이터 배열
|
||||
* @return array<string, mixed> 통계 정보가 포함된 사용자 컬렉션
|
||||
*/
|
||||
public function withStatistics(array $statistics = []): array
|
||||
{
|
||||
$isPaginator = $this->resource instanceof \Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
return [
|
||||
'data' => $this->mapWithRowNumber(function ($user) {
|
||||
return (new UserResource($user))->toListArray(request());
|
||||
}),
|
||||
'statistics' => $statistics,
|
||||
'abilities' => $this->resolveAbilitiesFromMap($this->abilityMap(), request()->user()),
|
||||
'pagination' => $isPaginator ? [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자용 상세 정보가 포함된 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 관리자 정보가 포함된 사용자 컬렉션
|
||||
*/
|
||||
public function withAdminInfo(): array
|
||||
{
|
||||
return [
|
||||
'data' => $this->mapWithRowNumber(function ($user) {
|
||||
return (new UserResource($user))->withAdminInfo();
|
||||
}),
|
||||
'pagination' => $this->when($this->resource instanceof \Illuminate\Pagination\LengthAwarePaginator, [
|
||||
'current_page' => $this->resource->currentPage(),
|
||||
'last_page' => $this->resource->lastPage(),
|
||||
'per_page' => $this->resource->perPage(),
|
||||
'total' => $this->resource->total(),
|
||||
'from' => $this->resource->firstItem(),
|
||||
'to' => $this->resource->lastItem(),
|
||||
'has_more_pages' => $this->resource->hasMorePages(),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 간단한 목록 형태의 배열을 반환합니다.
|
||||
*
|
||||
* @return array<int, array<string, mixed>> 간략한 사용자 정보 배열
|
||||
*/
|
||||
public function toSimpleArray(): array
|
||||
{
|
||||
return $this->collection->map(function ($user) {
|
||||
return [
|
||||
'uuid' => $user->uuid,
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
];
|
||||
})->toArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Enums\ConsentType;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\TimezoneHelper;
|
||||
use App\Traits\HasCountryAttributes;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class UserResource extends BaseApiResource
|
||||
{
|
||||
use HasCountryAttributes;
|
||||
|
||||
/**
|
||||
* 사용자 리소스를 배열로 변환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, mixed> 변환된 사용자 데이터 배열
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->getValue('uuid'),
|
||||
'name' => $this->getValue('name'),
|
||||
'nickname' => $this->getValue('nickname'),
|
||||
'email' => $this->getValue('email'),
|
||||
'avatar' => $this->resource->getAvatarUrl(),
|
||||
'language' => $this->getValue('language'),
|
||||
'language_label' => $this->getValue('language')
|
||||
? __('user.language.'.$this->getValue('language'))
|
||||
: null,
|
||||
'country' => $this->getValue('country'),
|
||||
'status' => $this->getValue('status'),
|
||||
'status_label' => $this->getStatusLabel(),
|
||||
'status_variant' => $this->getStatusVariant(),
|
||||
'is_admin' => $this->resource->isAdmin(),
|
||||
'homepage' => $this->getValue('homepage'),
|
||||
'mobile' => $this->getValue('mobile'),
|
||||
'phone' => $this->getValue('phone'),
|
||||
'zipcode' => $this->getValue('zipcode'),
|
||||
'address' => $this->getValue('address'),
|
||||
'address_detail' => $this->getValue('address_detail'),
|
||||
'signature' => $this->getValue('signature'),
|
||||
'bio' => $this->getValue('bio'),
|
||||
'last_login_at' => $this->getValue('last_login_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('last_login_at'))
|
||||
: null,
|
||||
'email_verified_at' => $this->getValue('email_verified_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('email_verified_at'))
|
||||
: null,
|
||||
'timezone' => $this->getValue('timezone'),
|
||||
|
||||
// 관계형 데이터 (필요시 로드)
|
||||
'modules_count' => $this->when(
|
||||
isset($this->modules_count),
|
||||
$this->getValue('modules_count')
|
||||
),
|
||||
'plugins_count' => $this->when(
|
||||
isset($this->plugins_count),
|
||||
$this->getValue('plugins_count')
|
||||
),
|
||||
'menus_count' => $this->when(
|
||||
isset($this->menus_count),
|
||||
$this->getValue('menus_count')
|
||||
),
|
||||
|
||||
// 관계형 데이터
|
||||
'modules' => $this->whenLoaded('modules', function () {
|
||||
return $this->getValue('modules', collect())->map(function ($module) {
|
||||
$moduleResource = new ModuleResource($module);
|
||||
|
||||
return [
|
||||
'id' => $moduleResource->getValue('id'),
|
||||
'name' => $module->getLocalizedName(),
|
||||
'slug' => $moduleResource->getValue('slug'),
|
||||
'is_active' => $moduleResource->getValue('is_active'),
|
||||
];
|
||||
});
|
||||
}),
|
||||
|
||||
'plugins' => $this->whenLoaded('plugins', function () {
|
||||
return $this->getValue('plugins', collect())->map(function ($plugin) {
|
||||
$pluginResource = new PluginResource($plugin);
|
||||
|
||||
return [
|
||||
'id' => $pluginResource->getValue('id'),
|
||||
'name' => $plugin->getLocalizedName(),
|
||||
'slug' => $pluginResource->getValue('slug'),
|
||||
'is_active' => $pluginResource->getValue('is_active'),
|
||||
];
|
||||
});
|
||||
}),
|
||||
|
||||
'menus' => $this->whenLoaded('menus', function () {
|
||||
return $this->getValue('menus', collect())->map(function ($menu) {
|
||||
$menuResource = new MenuResource($menu);
|
||||
|
||||
return [
|
||||
'id' => $menuResource->getValue('id'),
|
||||
'title' => $menu->getLocalizedName(),
|
||||
'url' => $menuResource->getValue('url'),
|
||||
'is_active' => $menuResource->getValue('is_active'),
|
||||
];
|
||||
});
|
||||
}),
|
||||
|
||||
'roles' => $this->whenLoaded('roles', function () {
|
||||
return $this->getValue('roles', collect())->map(function ($role) {
|
||||
return [
|
||||
'id' => $role->id,
|
||||
'identifier' => $role->identifier,
|
||||
'name' => $role->getLocalizedName(),
|
||||
];
|
||||
});
|
||||
}),
|
||||
|
||||
// 권한은 역할을 통해 간접 로드됨 (roles.permissions)
|
||||
'permissions' => $this->whenLoaded('roles', function () {
|
||||
$allPermissions = collect();
|
||||
foreach ($this->resource->roles as $role) {
|
||||
if ($role->relationLoaded('permissions')) {
|
||||
$allPermissions = $allPermissions->merge($role->permissions);
|
||||
}
|
||||
}
|
||||
|
||||
return $allPermissions->unique('id')->map(function ($permission) {
|
||||
return [
|
||||
'id' => $permission->id,
|
||||
'identifier' => $permission->identifier,
|
||||
'name' => $permission->getLocalizedName(),
|
||||
];
|
||||
})->values();
|
||||
}),
|
||||
|
||||
// 약관 동의 이력 (전체 배열 - 플러그인 참조용)
|
||||
'consents' => $this->whenLoaded('consents', function () {
|
||||
return $this->resource->consents->map(fn ($c) => [
|
||||
'consent_type' => $c->consent_type->value,
|
||||
'agreed_at' => $this->formatDateTimeStringForUser($c->agreed_at),
|
||||
'revoked_at' => $this->formatDateTimeStringForUser($c->revoked_at),
|
||||
]);
|
||||
}),
|
||||
|
||||
// 코어 UI용 개별 동의 키 (관리자 화면 직접 바인딩용)
|
||||
'terms_consent' => $this->whenLoaded('consents', function () {
|
||||
$consent = $this->resource->consents
|
||||
->first(fn ($c) => $c->consent_type === ConsentType::Terms);
|
||||
|
||||
return $consent ? [
|
||||
'agreed_at' => $this->formatDateTimeStringForUser($consent->agreed_at),
|
||||
] : null;
|
||||
}),
|
||||
|
||||
'privacy_consent' => $this->whenLoaded('consents', function () {
|
||||
$consent = $this->resource->consents
|
||||
->first(fn ($c) => $c->consent_type === ConsentType::Privacy);
|
||||
|
||||
return $consent ? [
|
||||
'agreed_at' => $this->formatDateTimeStringForUser($consent->agreed_at),
|
||||
] : null;
|
||||
}),
|
||||
|
||||
...$this->formatTimestamps(),
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한 매핑을 반환합니다.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function abilityMap(): array
|
||||
{
|
||||
return [
|
||||
'can_read' => 'core.users.read',
|
||||
'can_create' => 'core.users.create',
|
||||
'can_update' => 'core.users.update',
|
||||
'can_delete' => 'core.users.delete',
|
||||
'can_assign_roles' => 'core.permissions.update',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리소스별 권한을 해석합니다.
|
||||
*
|
||||
* 슈퍼관리자 및 관리자 계정은 삭제할 수 없으므로 can_delete를 강제 false로 설정합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @return array<string, bool> 권한 배열
|
||||
*/
|
||||
protected function resolveAbilities(Request $request): array
|
||||
{
|
||||
$abilities = parent::resolveAbilities($request);
|
||||
|
||||
if ($this->resource->isSuperAdmin() || $this->resource->isAdmin()) {
|
||||
$abilities['can_delete'] = false;
|
||||
}
|
||||
|
||||
return $abilities;
|
||||
}
|
||||
|
||||
/**
|
||||
* 소유자 필드를 반환합니다.
|
||||
*
|
||||
* User 리소스의 경우 자기 자신이 소유자이므로 id 필드를 사용합니다.
|
||||
*
|
||||
* @return string|null 소유자 필드명
|
||||
*/
|
||||
protected function ownerField(): ?string
|
||||
{
|
||||
return 'id';
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자용 상세 정보를 포함한 배열을 반환합니다.
|
||||
*
|
||||
* 주의: 이 메서드는 toArray() 외부에서 수동 호출되므로
|
||||
* $this->when() 대신 삼항 연산자를 사용해야 합니다.
|
||||
*
|
||||
* @return array<string, mixed> 상세 정보가 포함된 사용자 데이터
|
||||
*/
|
||||
public function withAdminInfo(): array
|
||||
{
|
||||
$data = array_merge($this->toArray(request()), [
|
||||
'admin_memo' => $this->getValue('admin_memo'),
|
||||
'ip_address' => $this->getValue('ip_address'),
|
||||
'withdrawn_at' => $this->getValue('withdrawn_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('withdrawn_at'))
|
||||
: null,
|
||||
'blocked_at' => $this->getValue('blocked_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('blocked_at'))
|
||||
: null,
|
||||
]);
|
||||
|
||||
// Filter 훅: 모듈이 자신의 데이터를 응답에 병합
|
||||
return HookManager::applyFilters('core.user.filter_resource_data', $data, $this->resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록용 간단한 형태의 배열을 반환합니다.
|
||||
*
|
||||
* 주의: 이 메서드는 toArray() 외부에서 수동 호출되므로
|
||||
* $this->when() 대신 삼항 연산자를 사용해야 합니다.
|
||||
* $this->when()은 Laravel이 toArray()를 처리할 때만 MissingValue를 필터링합니다.
|
||||
*
|
||||
* @param Request|null $request HTTP 요청
|
||||
* @return array<string, mixed> 간략한 사용자 정보
|
||||
*/
|
||||
public function toListArray(?Request $request = null): array
|
||||
{
|
||||
$request = $request ?? request();
|
||||
$countryCode = $this->getValue('country');
|
||||
$language = $this->getValue('language');
|
||||
$status = $this->getValue('status');
|
||||
$userStatus = $status ? UserStatus::tryFrom($status) : null;
|
||||
|
||||
return [
|
||||
'uuid' => $this->getValue('uuid'),
|
||||
'name' => $this->getValue('name'),
|
||||
'nickname' => $this->getValue('nickname'),
|
||||
'email' => $this->getValue('email'),
|
||||
'language' => $language,
|
||||
'language_label' => $language ? __('user.language.'.$language) : null,
|
||||
'country' => $countryCode,
|
||||
'country_flag' => $countryCode ? $this->getCountryFlag($countryCode) : null,
|
||||
'country_name' => $countryCode ? $this->getCountryName($countryCode) : null,
|
||||
'status' => $status,
|
||||
'status_label' => $userStatus?->label(),
|
||||
'status_variant' => $userStatus?->variant(),
|
||||
'mobile' => $this->getValue('mobile'),
|
||||
'roles' => $this->resource->relationLoaded('roles')
|
||||
? $this->resource->roles->map(fn ($role) => [
|
||||
'id' => $role->id,
|
||||
'identifier' => $role->identifier,
|
||||
'name' => $role->getLocalizedName(),
|
||||
])->toArray()
|
||||
: [],
|
||||
'email_verified_at' => $this->getValue('email_verified_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('email_verified_at'))
|
||||
: null,
|
||||
'last_login_at' => $this->getValue('last_login_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('last_login_at'))
|
||||
: null,
|
||||
'created_at' => $this->getValue('created_at')
|
||||
? $this->formatDateForUser($this->getValue('created_at'))
|
||||
: null,
|
||||
...$this->resourceMeta($request),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로필용 안전한 형태의 배열을 반환합니다 (민감한 정보 제외).
|
||||
*
|
||||
* 주의: 이 메서드는 toArray() 외부에서 수동 호출되므로
|
||||
* $this->when() 대신 삼항 연산자를 사용해야 합니다.
|
||||
*
|
||||
* @return array<string, mixed> 안전한 프로필 정보
|
||||
*/
|
||||
public function toProfileArray(): array
|
||||
{
|
||||
$status = $this->getValue('status');
|
||||
$userStatus = $status ? UserStatus::tryFrom($status) : null;
|
||||
|
||||
$data = [
|
||||
'uuid' => $this->getValue('uuid'),
|
||||
'name' => $this->getValue('name'),
|
||||
'nickname' => $this->getValue('nickname'),
|
||||
'email' => $this->getValue('email'),
|
||||
'avatar' => $this->resource->getAvatarUrl(),
|
||||
'language' => $this->getValue('language'),
|
||||
'timezone' => $this->getValue('timezone'),
|
||||
'country' => $this->getValue('country'),
|
||||
'status' => $status,
|
||||
'status_label' => $userStatus?->label(),
|
||||
'status_variant' => $userStatus?->variant(),
|
||||
'homepage' => $this->getValue('homepage'),
|
||||
'mobile' => $this->getValue('mobile'),
|
||||
'phone' => $this->getValue('phone'),
|
||||
'zipcode' => $this->getValue('zipcode'),
|
||||
'address' => $this->getValue('address'),
|
||||
'address_detail' => $this->getValue('address_detail'),
|
||||
'signature' => $this->getValue('signature'),
|
||||
'bio' => $this->getValue('bio'),
|
||||
'is_super' => $this->resource->isSuperAdmin(),
|
||||
'is_admin' => $this->resource->isAdmin(),
|
||||
'withdrawn_at' => $this->getValue('withdrawn_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('withdrawn_at'))
|
||||
: null,
|
||||
'last_login_at' => $this->getValue('last_login_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('last_login_at'))
|
||||
: null,
|
||||
'last_login_human' => $this->getValue('last_login_at')
|
||||
? TimezoneHelper::toUserCarbon(Carbon::parse($this->getValue('last_login_at')))?->diffForHumans()
|
||||
: null,
|
||||
'created_at' => $this->getValue('created_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('created_at'))
|
||||
: null,
|
||||
'is_owner' => request()->user()?->uuid === $this->resource->uuid,
|
||||
];
|
||||
|
||||
// Filter 훅: 모듈이 자신의 데이터를 프로필 응답에 병합
|
||||
return HookManager::applyFilters('core.user.filter_resource_data', $data, $this->resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 통계용 데이터 배열을 반환합니다.
|
||||
*
|
||||
* 주의: 이 메서드는 toArray() 외부에서 수동 호출되므로
|
||||
* $this->when() 대신 삼항 연산자를 사용해야 합니다.
|
||||
*
|
||||
* @return array<string, mixed> 통계 정보가 포함된 사용자 데이터
|
||||
*/
|
||||
public function toStatisticsArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->getValue('uuid'),
|
||||
'name' => $this->getValue('name'),
|
||||
'email' => $this->getValue('email'),
|
||||
'modules_count' => $this->getValue('modules_count', 0),
|
||||
'plugins_count' => $this->getValue('plugins_count', 0),
|
||||
'menus_count' => $this->getValue('menus_count', 0),
|
||||
'last_login_at' => $this->getValue('last_login_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('last_login_at'))
|
||||
: null,
|
||||
'created_at' => $this->getValue('created_at')
|
||||
? $this->formatDateTimeStringForUser($this->getValue('created_at'))
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 상태 라벨을 반환합니다.
|
||||
*
|
||||
* @return string|null 상태 라벨
|
||||
*/
|
||||
protected function getStatusLabel(): ?string
|
||||
{
|
||||
$status = $this->getValue('status');
|
||||
$userStatus = $status ? UserStatus::tryFrom($status) : null;
|
||||
|
||||
return $userStatus?->label();
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 상태 variant를 반환합니다.
|
||||
*
|
||||
* @return string|null 상태 variant (success, secondary, danger, warning)
|
||||
*/
|
||||
protected function getStatusVariant(): ?string
|
||||
{
|
||||
$status = $this->getValue('status');
|
||||
$userStatus = $status ? UserStatus::tryFrom($status) : null;
|
||||
|
||||
return $userStatus?->variant();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user