AttributeCollectionProvider.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Webkul\BagistoApi\State;
  3. use ApiPlatform\Laravel\Eloquent\Paginator;
  4. use ApiPlatform\Metadata\Operation;
  5. use ApiPlatform\State\Pagination\Pagination;
  6. use ApiPlatform\State\ProviderInterface;
  7. use Illuminate\Pagination\LengthAwarePaginator;
  8. use Webkul\BagistoApi\Models\Attribute;
  9. class AttributeCollectionProvider implements ProviderInterface
  10. {
  11. public function __construct(
  12. private readonly Pagination $pagination
  13. ) {}
  14. public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
  15. {
  16. $args = $context['args'] ?? [];
  17. $first = isset($args['first']) ? (int) $args['first'] : null;
  18. $last = isset($args['last']) ? (int) $args['last'] : null;
  19. $after = $args['after'] ?? null;
  20. $before = $args['before'] ?? null;
  21. $defaultPerPage = 30;
  22. // Determine page size
  23. if ($first !== null) {
  24. $perPage = $first;
  25. } elseif ($last !== null) {
  26. $perPage = $last;
  27. } else {
  28. $perPage = $defaultPerPage;
  29. }
  30. $offset = 0;
  31. if ($after) {
  32. $decoded = base64_decode($after, true);
  33. $offset = ctype_digit((string) $decoded) ? ((int) $decoded + 1) : 0;
  34. }
  35. if ($before) {
  36. $decoded = base64_decode($before, true);
  37. $cursor = ctype_digit((string) $decoded) ? (int) $decoded : 0;
  38. $offset = max(0, $cursor - $perPage);
  39. }
  40. $query = Attribute::query()
  41. ->with(['options', 'translations', 'translation', 'options.translations', 'options.translation'])
  42. ->orderBy('id', 'asc');
  43. $total = (clone $query)->count();
  44. if ($offset > $total) {
  45. $offset = max(0, $total - $perPage);
  46. }
  47. $items = $query
  48. ->offset($offset)
  49. ->limit($perPage)
  50. ->get();
  51. $currentPage = $total > 0 ? (int) floor($offset / $perPage) + 1 : 1;
  52. return new Paginator(
  53. new LengthAwarePaginator(
  54. $items,
  55. $total,
  56. $perPage,
  57. $currentPage,
  58. ['path' => request()->url()]
  59. )
  60. );
  61. }
  62. }