NotificationCollection.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. 'content' => $item->content,
  41. 'read_at' => (string)$item->read_at,
  42. 'read_status' => (bool)$item->read_at,
  43. 'object' => $object,
  44. ];
  45. $items[] = $row;
  46. }
  47. return $items;
  48. }
  49. protected function widthActionObjects(): array
  50. {
  51. $actionIDS = collect($this->resource->items())->where("object_type", NotificationObjectType::ACTION->value)->pluck("object_id");
  52. $actions = Action::with(['createdBy'])->whereIn("id", $actionIDS->toArray())->get();
  53. $actionGroupObjects = [];
  54. foreach($actions->groupBy("object_type") as $objectType => $items) {
  55. $approvalObjectType = ApprovalObjectType::from($objectType);
  56. $actionGroupObjects[$objectType] = $approvalObjectType
  57. ->modelBuilder()
  58. ->whereIn("id", array_column($items->toArray(), "object_id"))
  59. ->pluck($approvalObjectType->nameField(), "id");
  60. };
  61. return [$actions->keyBy("id"), $actionGroupObjects];
  62. }
  63. }