ApprovalCollection.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. 'object' => [
  30. 'id' => $approval->object_id,
  31. 'name' => data_get($groupObjects, sprintf("%s.%s", $approval->object_type, $approval->object_id)),
  32. ]
  33. ];
  34. }
  35. return $items;
  36. }
  37. protected function getGroupObjects(): array
  38. {
  39. $groupObjects = [];
  40. foreach(collect($this->resource->items())->groupBy("object_type") as $objectType => $items) {
  41. $approvalObjectType = ApprovalObjectType::from($objectType);
  42. $groupObjects[$objectType] = $approvalObjectType
  43. ->modelBuilder()
  44. ->whereIn("id", array_column($items->toArray(), "object_id"))
  45. ->pluck($approvalObjectType->nameField(), "id");
  46. };
  47. return $groupObjects;
  48. }
  49. }