Skip to content

Commit

Permalink
feat: collection macros
Browse files Browse the repository at this point in the history
feat: paginated collection
  • Loading branch information
nikuscs committed Sep 29, 2024
1 parent 4c9a69c commit ca86b05
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/Macros/CollectionMacros.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

namespace Flavorly\LaravelHelpers\Macros;

use Flavorly\LaravelHelpers\Contracts\RegistersMacros;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;

class CollectionMacros implements RegistersMacros
{
public static function register(): void
{
self::paginate();
}

public static function paginate(): void
{
// Response Macros
if (! Collection::hasMacro('paginate')) {
/**
* Paginate the collection.
*
* @param int $perPage
* @param int $page
* @param array $options
* @return LengthAwarePaginator
*/
Collection::macro('paginate', function (
int $perPage = 15,
?int $page = null,
string $pageName = 'page',
array $options = []
): LengthAwarePaginator {
$page = $page ?: (Paginator::resolveCurrentPage($pageName) ?: 1);

/**
* @var Collection<int, mixed> $this
*/
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->toArray(),
$this->count(),
$perPage,
$page,
[
...$options,
'path' => LengthAwarePaginator::resolveCurrentPath(),
'query' => request()->query(),
]
);
});
}
}
}

0 comments on commit ca86b05

Please sign in to comment.