12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <?php
- namespace App\Http\Resources\API;
- use App\Models\Enums\ApprovalObjectType;
- use Illuminate\Http\Request;
- use Illuminate\Http\Resources\Json\ResourceCollection;
- class ApprovalCollection extends ResourceCollection
- {
- public function __construct($resource)
- {
- parent::__construct($resource);
- }
- /**
- * Transform the resource collection into an array.
- *
- * @return array<int|string, mixed>
- */
- public function toArray(Request $request): array
- {
- $groupObjects = $this->getGroupObjects();
- $items = [];
- foreach ($this->resource as $approval) {
- $items[] = [
- 'id' => $approval->id,
- 'status' => $approval->status,
- 'object_type' => $approval->object_type,
- 'object_id' => $approval->object_id,
- 'node_level' => $approval->node_level,
- 'created_by' => new UserProfileResource($approval->createdBy),
- 'object' => [
- 'id' => $approval->object_id,
- 'name' => data_get($groupObjects, sprintf("%s.%s", $approval->object_type, $approval->object_id)),
- ]
- ];
- }
- return $items;
- }
- protected function getGroupObjects(): array
- {
- $groupObjects = [];
- foreach(collect($this->resource->items())->groupBy("object_type") as $objectType => $items) {
- $approvalObjectType = ApprovalObjectType::from($objectType);
- $groupObjects[$objectType] = $approvalObjectType
- ->modelBuilder()
- ->whereIn("id", array_column($items->toArray(), "object_id"))
- ->pluck($approvalObjectType->nameField(), "id");
- };
- return $groupObjects;
- }
- }
|