123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace App\Http\Resources\API;
- use App\Models\Action;
- use App\Models\Enums\ApprovalObjectType;
- use App\Models\Enums\NotificationObjectType;
- use Illuminate\Http\Request;
- use Illuminate\Http\Resources\Json\ResourceCollection;
- class NotificationCollection extends ResourceCollection
- {
- /**
- * Transform the resource collection into an array.
- *
- * @return array<int|string, mixed>
- */
- public function toArray(Request $request): array
- {
- list ($actions, $actionGroupObjects) = $this->widthActionObjects();
- $items = [];
- foreach ($this->resource->items() as $item) {
- $object = null;
- if ($item->object_type == NotificationObjectType::ACTION->value) {
- $action = $actions[$item->object_id];
- $objectAction = $item->extra_fields['action'] ?? $action->action;
- $object = [
- 'id' => $action->id,
- 'action' => $objectAction,
- 'action_label' => __(sprintf("action-labels.label.%s", $objectAction)),
- 'created_by' => new UserProfileResource($action->createdBy),
- 'comment' => $action->commtent,
- 'object_type' => $action->object_type,
- 'object' => [
- 'id' => $action->object_id,
- 'name' => data_get($actionGroupObjects, sprintf("%s.%s", $action->object_type, $action->object_id)),
- ]
- ];
- }
- $row = [
- 'id' => $item->id,
- 'object_type' => $item->object_type,
- 'content' => $item->content,
- 'read_at' => (string)$item->read_at,
- 'read_status' => (bool)$item->read_at,
- 'object' => $object,
- ];
- $items[] = $row;
- }
- return $items;
- }
- protected function widthActionObjects(): array
- {
- $actionIDS = collect($this->resource->items())->where("object_type", NotificationObjectType::ACTION->value)->pluck("object_id");
- $actions = Action::with(['createdBy'])->whereIn("id", $actionIDS->toArray())->get();
- $actionGroupObjects = [];
- foreach($actions->groupBy("object_type") as $objectType => $items) {
- $approvalObjectType = ApprovalObjectType::from($objectType);
- $actionGroupObjects[$objectType] = $approvalObjectType
- ->modelBuilder()
- ->whereIn("id", array_column($items->toArray(), "object_id"))
- ->pluck($approvalObjectType->nameField(), "id");
- };
- return [$actions->keyBy("id"), $actionGroupObjects];
- }
- }
|