SearchData.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Models\DTO;
  3. use Illuminate\Contracts\Support\Responsable;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Http\JsonResponse;
  6. class SearchData implements Responsable
  7. {
  8. private array $extra = [];
  9. public function __construct(
  10. public int $page = 1,
  11. public int $perPage = DEFAULT_LIST_PER_PAGE,
  12. public int $pageCount = DEFAULT_LIST_PAGE_COUNT,
  13. public int $offset = 0,
  14. public ?int $sort = null,
  15. public ?string $field = null,
  16. public ?string $keyword = null,
  17. public ?string $startDate = null,
  18. public ?string $endDate = null,
  19. array $extra = []
  20. ) {
  21. $this->extra = $extra;
  22. }
  23. public static function fromRequest(Request $request): static
  24. {
  25. $page = max(1, (int)$request->input('page', 1));
  26. $perPage = max(1, (int)$request->input('per_page', $request->input('perPage', DEFAULT_LIST_PER_PAGE)));
  27. $pageCount = max(1, (int)$request->input('page_count', $request->input('pageCount', DEFAULT_LIST_PAGE_COUNT)));
  28. $offset = ($page - 1) * $perPage;
  29. $dto = new self(
  30. page: $page,
  31. perPage: $perPage,
  32. pageCount: $pageCount,
  33. offset: $offset,
  34. sort: (int)$request->input('sort', 1),
  35. field: $request->input('field'),
  36. keyword: $request->input('keyword'),
  37. startDate: $request->input('start_date'),
  38. endDate: $request->input('end_date')
  39. );
  40. $merged = array_merge($request->route()?->parameters() ?? [] , $request->all());
  41. foreach ($merged as $key => $value) {
  42. if (!property_exists($dto, $key)) {
  43. $dto->{$key} = $value;
  44. }
  45. }
  46. return $dto;
  47. }
  48. public function __set(string $name, mixed $value): void
  49. {
  50. // readonly core �ʵ� ���� ����
  51. if (property_exists($this, $name)) {
  52. throw new \LogicException("Cannot set '{$name}' on SearchData (readonly property).");
  53. }
  54. $this->extra[$name] = $value;
  55. }
  56. public function __get(string $name): mixed
  57. {
  58. return $this->extra[$name] ?? null;
  59. }
  60. public function __isset(string $name): bool
  61. {
  62. return isset($this->extra[$name]);
  63. }
  64. public function toResponse($request): JsonResponse
  65. {
  66. return response()->json([
  67. 'page' => $this->page,
  68. 'perPage' => $this->perPage,
  69. 'pageCount' => $this->pageCount,
  70. 'offset' => $this->offset,
  71. 'sort' => $this->sort,
  72. 'field' => $this->field,
  73. 'keyword' => $this->keyword,
  74. 'startDate' => $this->startDate,
  75. 'endDate' => $this->endDate,
  76. ...$this->extra
  77. ]);
  78. }
  79. }