ldc-volena/app/Lib/Helpers/CollectionHelper.php
2026-04-24 15:06:55 +02:00

74 lines
2.6 KiB
PHP

<?php
namespace App\Lib\Helpers;
use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class CollectionHelper
{
/**
* Paginate a collection.
*
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Support\Collection<int, TModel> $results
* @param integer $pageSize
* @return \Illuminate\Pagination\LengthAwarePaginator<TModel>
*/
public static function paginate(Collection $results, int $pageSize): \Illuminate\Pagination\LengthAwarePaginator
{
$page = Paginator::resolveCurrentPage('page');
return self::paginateManually($results, $pageSize, $page);
}
/**
* Paginate a collection.
*
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Support\Collection<int, TModel> $results
* @param integer $pageSize
* @param integer $page
* @return \Illuminate\Pagination\LengthAwarePaginator<TModel>
*/
public static function paginateManually(
Collection $results,
int $pageSize,
int $page = 1
): \Illuminate\Pagination\LengthAwarePaginator {
$total = $results->count();
return self::paginator($results->forPage($page, $pageSize), $total, $pageSize, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
}
/**
* Create a new length-aware paginator instance.
*
* @template TModel of \Illuminate\Database\Eloquent\Model
* @param \Illuminate\Support\Collection<int, TModel> $items
* @param integer $total
* @param integer $perPage
* @param integer $currentPage
* @param array<mixed> $options
* @return \Illuminate\Pagination\LengthAwarePaginator<TModel>
*/
protected static function paginator(
Collection $items,
int $total,
int $perPage,
int $currentPage,
array $options
): \Illuminate\Pagination\LengthAwarePaginator {
return Container::getInstance()->makeWith(LengthAwarePaginator::class, [
'items' => $items,
'total' => $total,
'perPage' => $perPage,
'currentPage' => $currentPage,
'options' => $options
]);
}
}