ApprovalCollection.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Http\Resources\API;
  3. use App\Models\Enums\ApprovalObjectType;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Http\Resources\Json\ResourceCollection;
  6. class ApprovalCollection extends ResourceCollection
  7. {
  8. public function __construct($resource)
  9. {
  10. parent::__construct($resource);
  11. }
  12. /**
  13. * Transform the resource collection into an array.
  14. *
  15. * @return array<int|string, mixed>
  16. */
  17. public function toArray(Request $request): array
  18. {
  19. $groupObjects = $this->getGroupObjects();
  20. $items = [];
  21. foreach ($this->resource as $approval) {
  22. $items[] = [
  23. 'id' => $approval->id,
  24. 'status' => $approval->status,
  25. 'object_type' => $approval->object_type,
  26. 'object_id' => $approval->object_id,
  27. 'node_level' => $approval->node_level,
  28. 'created_by' => new UserProfileResource($approval->createdBy),
  29. 'display_id' => $approval->display_id,
  30. 'object' => [
  31. 'id' => $approval->object_id,
  32. 'name' => data_get($groupObjects, sprintf("%s.%s", $approval->object_type, $approval->object_id)),
  33. ]
  34. ];
  35. }
  36. return $items;
  37. }
  38. protected function getGroupObjects(): array
  39. {
  40. $groupObjects = [];
  41. foreach(collect($this->resource->items())->groupBy("object_type") as $objectType => $items) {
  42. $approvalObjectType = ApprovalObjectType::from($objectType);
  43. $groupObjects[$objectType] = $approvalObjectType
  44. ->modelBuilder()
  45. ->whereIn("id", array_column($items->toArray(), "object_id"))
  46. ->pluck($approvalObjectType->nameField(), "id");
  47. };
  48. return $groupObjects;
  49. }
  50. }