NotificationCollection.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Http\Resources\API;
  3. use App\Models\Action;
  4. use App\Models\Enums\ApprovalObjectType;
  5. use App\Models\Enums\NotificationObjectType;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Http\Resources\Json\ResourceCollection;
  8. class NotificationCollection extends ResourceCollection
  9. {
  10. /**
  11. * Transform the resource collection into an array.
  12. *
  13. * @return array<int|string, mixed>
  14. */
  15. public function toArray(Request $request): array
  16. {
  17. list ($actions, $actionGroupObjects) = $this->widthActionObjects();
  18. $items = [];
  19. foreach ($this->resource->items() as $item) {
  20. $object = null;
  21. if ($item->object_type == NotificationObjectType::ACTION->value) {
  22. $action = $actions[$item->object_id];
  23. $objectAction = $item->extra_fields['action'] ?? $action->action;
  24. $object = [
  25. 'id' => $action->id,
  26. 'action' => $objectAction,
  27. 'action_label' => __(sprintf("action-labels.label.%s", $objectAction)),
  28. 'created_by' => new UserProfileResource($action->createdBy),
  29. 'comment' => $action->commtent,
  30. 'object_type' => $action->object_type,
  31. 'object' => [
  32. 'id' => $action->object_id,
  33. 'name' => data_get($actionGroupObjects, sprintf("%s.%s", $action->object_type, $action->object_id)),
  34. ]
  35. ];
  36. }
  37. $row = [
  38. 'id' => $item->id,
  39. 'object_type' => $item->object_type,
  40. 'created_at'=>(string)$item->created_at,
  41. 'content' => $item->content,
  42. 'read_at' => (string)$item->read_at,
  43. 'read_status' => (bool)$item->read_at,
  44. 'display_id'=>$item->display_id,
  45. 'object' => $object,
  46. ];
  47. $items[] = $row;
  48. }
  49. return $items;
  50. }
  51. protected function widthActionObjects(): array
  52. {
  53. $actionIDS = collect($this->resource->items())->where("object_type", NotificationObjectType::ACTION->value)->pluck("object_id");
  54. $actions = Action::with(['createdBy'])->whereIn("id", $actionIDS->toArray())->get();
  55. $actionGroupObjects = [];
  56. foreach($actions->groupBy("object_type") as $objectType => $items) {
  57. $approvalObjectType = ApprovalObjectType::from($objectType);
  58. $actionGroupObjects[$objectType] = $approvalObjectType
  59. ->modelBuilder()
  60. ->whereIn("id", array_column($items->toArray(), "object_id"))
  61. ->pluck($approvalObjectType->nameField(), "id");
  62. };
  63. return [$actions->keyBy("id"), $actionGroupObjects];
  64. }
  65. }