87 lines
2.6 KiB
PHP
87 lines
2.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers\Back;
|
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Contracts\Session\Session;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
|
use Illuminate\Foundation\Validation\ValidatesRequests;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Routing\Route;
|
|
use Illuminate\Support\Str;
|
|
use Uwil\LaravelBackend\Controllers\BackendController as UwilBackendController;
|
|
use Uwil\LaravelBackend\Enums\ItemsPerPaginationEnum;
|
|
use Uwil\LaravelCommon\Helpers\ToolboxHelper;
|
|
|
|
class BackendController extends UwilBackendController
|
|
{
|
|
use AuthorizesRequests;
|
|
use ValidatesRequests;
|
|
|
|
public function __construct(
|
|
protected readonly Request $request,
|
|
protected readonly Session $session,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* Customize pagination with cache or config (default).
|
|
*
|
|
* @template T of \Illuminate\Database\Eloquent\Model
|
|
*
|
|
* @param \Illuminate\Database\Eloquent\Builder<T> $query
|
|
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator<array-key,T>
|
|
*/
|
|
protected function paginate(
|
|
Builder $query,
|
|
?ItemsPerPaginationEnum $pagination = null
|
|
): LengthAwarePaginator {
|
|
$route = $this->request->route();
|
|
|
|
throw_if(
|
|
$route === null,
|
|
\UnexpectedValueException::class,
|
|
'Route is required in order to paginate'
|
|
);
|
|
|
|
$cacheKey = $this->getCacheKey($route);
|
|
$perPage = $this->getPerPage($cacheKey);
|
|
|
|
$this->persistPerPage($cacheKey, $perPage);
|
|
|
|
return $query->paginate(perPage: $perPage)->withQueryString();
|
|
}
|
|
|
|
private function persistPerPage(string $cacheKey, int $perPage): void
|
|
{
|
|
if ($this->session->get($cacheKey) !== $perPage) {
|
|
$this->session->put($cacheKey, $perPage);
|
|
}
|
|
}
|
|
|
|
private function getPerPage(string $cacheKey): int
|
|
{
|
|
$perPage = $this->session->get($cacheKey);
|
|
$perPage = $perPage ?? ItemsPerPaginationEnum::twelve->value();
|
|
|
|
if (! is_scalar($perPage)) {
|
|
throw new \UnexpectedValueException('perPage shall be a scalar valuye');
|
|
}
|
|
|
|
return ToolboxHelper::getValidatedEnum(
|
|
intval($perPage),
|
|
'pagination',
|
|
'\Uwil\LaravelBackend\Enums\ItemsPerPaginationEnum',
|
|
);
|
|
}
|
|
|
|
private function getCacheKey(Route $route): string
|
|
{
|
|
$currentRoutePath = Str::slug($route->getName() ?? 'unknown');
|
|
|
|
return "pagination.{$currentRoutePath}";
|
|
}
|
|
}
|