generated from liutk/owl-admin-base
50 lines
1.5 KiB
PHP
50 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Resources;
|
|
|
|
use App\Exceptions\RuntimeException;
|
|
use Illuminate\Database\Eloquent\Relations\Relation;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Resources\Json\JsonResource;
|
|
|
|
class TaskResource extends JsonResource
|
|
{
|
|
/**
|
|
* Transform the resource into an array.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toArray(Request $request): array
|
|
{
|
|
$resource = $this->mapResource($this->taskable_type);
|
|
|
|
return [
|
|
'id' => $this->id,
|
|
'name' => $this->name,
|
|
'taskable_type' => $this->taskable_type,
|
|
'taskable_id' => $this->taskable_id,
|
|
'taskable' => $resource::make($this->whenLoaded('taskable')),
|
|
'start_at' => (int) $this->start_at?->timestamp,
|
|
'start_format' => $this->start_at?->format('Y年m月d日'),
|
|
'end_at' => (int) $this->end_at?->timestamp,
|
|
'end_format' => $this->end_at?->format('Y年m月d日'),
|
|
'created_at' => $this->created_at->timestamp,
|
|
'created_format' => $this->created_at->format('Y-m-d'),
|
|
];
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|