NotificationCollection.php 2.7 KB

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