store-manage/app/Http/Resources/WorkflowCheckResource.php

46 lines
1.3 KiB
PHP

<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Database\Eloquent\Relations\Relation;
use RuntimeException;
class WorkflowCheckResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$resource = $this->mapResource($this->subject_type);
return [
'check_status' => $this->check_status,
'check_status_text' => $this->check_status?->text(),
'checked_at' => $this->checked_at?->getTimestamp(),
'check_remarks' => (string) $this->check_remarks,
'logs' => WorkflowLogResource::collection($this->whenLoaded('logs')),
'subject_id' => $this->subject_id,
'subject_type' => $this->subject_type,
'subject' => $resource::make($this->whenLoaded('subject')),
];
}
protected function mapResource(string $type)
{
$model = Relation::getMorphedModel($type);
$class = match ($model) {
default => 'App\\Http\\Resources\\'.class_basename($model).'Resource',
};
if (! class_exists($class)) {
throw new RuntimeException('未知的 subject_type');
}
return $class;
}
}