ldc-legaulois/app/Lib/Helpers/CollectionHelper.php

97 lines
2.7 KiB
PHP
Raw Permalink Normal View History

2024-01-10 14:49:46 +01:00
<?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.
2024-01-10 14:49:46 +01:00
*/
2026-09-25 16:25:31 +02:00
public static function paginate(Collection $results, int $pageSize): LengthAwarePaginator
2024-01-10 14:49:46 +01:00
{
$page = Paginator::resolveCurrentPage('page');
return self::paginateManually($results, $pageSize, $page);
}
/**
* Paginate a collection.
2024-01-10 14:49:46 +01:00
*/
public static function paginateManually(
Collection $results,
int $pageSize,
int $page = 1
2026-09-25 16:25:31 +02:00
): LengthAwarePaginator {
2024-01-10 14:49:46 +01:00
$total = $results->count();
return self::paginator($results->forPage($page, $pageSize), $total, $pageSize, $page, [
'path' => Paginator::resolveCurrentPath(),
2024-01-10 14:49:46 +01:00
'pageName' => 'page',
]);
}
/**
* Create a new length-aware paginator instance.
*/
protected static function paginator(
Collection $items,
int $total,
int $perPage,
int $currentPage,
array $options
2026-09-25 16:25:31 +02:00
): LengthAwarePaginator {
2024-01-10 14:49:46 +01:00
return Container::getInstance()->makeWith(LengthAwarePaginator::class, [
'items' => $items,
'total' => $total,
'perPage' => $perPage,
2024-01-10 14:49:46 +01:00
'currentPage' => $currentPage,
2026-09-25 16:25:31 +02:00
'options' => $options,
2024-01-10 14:49:46 +01:00
]);
}
/**
* Get an array of views for each recipe models given.
*/
public static function getViewsFromPaginateModels(
LengthAwarePaginator $models,
string $path,
string $key
): array {
return $models->through(function ($model) use ($path, $key) {
return view($path, [$key => $model])->render();
})->toArray();
}
/**
* Get an array of views for each item in collection given.
*/
public static function getViewsFromCollection(Collection $collection, string $path, string $key): array
{
return $collection->map(function ($item) use ($path, $key) {
return view($path, [$key => $item])->render();
})->toArray();
}
public static function mapSlidesToFields(array $fields): array
{
return collect($fields)
2026-09-25 16:25:31 +02:00
->filter(fn ($field, $key) => str_starts_with($key, 'slider_image_'))
->filter(fn ($field) => ! empty($field['value']))
->sortKeys()
2026-09-25 16:25:31 +02:00
->map(fn ($field) => [
'image' => [
'path' => $field['value'],
'title' => $field['title'] ?? '',
2026-09-25 16:25:31 +02:00
'alt' => $field['alt'] ?? '',
],
])
->values()
->toArray();
2026-05-13 15:02:14 +02:00
}
2024-01-10 14:49:46 +01:00
}