issues/27: update crud from admin api
This commit is contained in:
committed by
Valeriy Petrov
parent
839ccdffb5
commit
bc5468e5a0
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Pagination;
|
||||
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
use Pagerfanta\Doctrine\ORM\QueryAdapter;
|
||||
use Pagerfanta\Exception\NotValidCurrentPageException;
|
||||
use Pagerfanta\Pagerfanta;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
/**
|
||||
* Унифицированная обёртка над Pagerfanta + QueryAdapter.
|
||||
*
|
||||
* Соответствует существующему стилю проекта (см. PriceListController/SpecialistController):
|
||||
* читает page/perPage из Request, ограничивает perPage и возвращает массив
|
||||
* ['data' => [...], 'pagination' => [...]] в едином формате для всех контроллеров.
|
||||
*/
|
||||
final class Paginator
|
||||
{
|
||||
public const DEFAULT_PER_PAGE = 50;
|
||||
public const MAX_PER_PAGE = 500;
|
||||
|
||||
/**
|
||||
* @return array{data: list<mixed>, pagination: array<string, int|bool>}
|
||||
*/
|
||||
public function paginate(
|
||||
QueryBuilder $qb,
|
||||
Request $request,
|
||||
int $defaultPerPage = self::DEFAULT_PER_PAGE,
|
||||
int $maxPerPage = self::MAX_PER_PAGE,
|
||||
): array {
|
||||
$page = max(1, $request->query->getInt('page', 1));
|
||||
$perPage = min(
|
||||
max(1, $request->query->getInt('perPage', $defaultPerPage)),
|
||||
$maxPerPage,
|
||||
);
|
||||
|
||||
$pagerfanta = (new Pagerfanta(new QueryAdapter($qb)))
|
||||
->setMaxPerPage($perPage);
|
||||
|
||||
try {
|
||||
$pagerfanta->setCurrentPage($page);
|
||||
} catch (NotValidCurrentPageException) {
|
||||
// выходим за пределы — возвращаем пустую страницу с корректным total
|
||||
$pagerfanta->setCurrentPage(max(1, $pagerfanta->getNbPages()));
|
||||
}
|
||||
|
||||
$data = iterator_to_array($pagerfanta->getCurrentPageResults(), false);
|
||||
|
||||
return [
|
||||
'data' => $data,
|
||||
'pagination' => [
|
||||
'total' => $pagerfanta->getNbResults(),
|
||||
'count' => count($data),
|
||||
'per_page' => $pagerfanta->getMaxPerPage(),
|
||||
'current_page' => $pagerfanta->getCurrentPage(),
|
||||
'total_pages' => $pagerfanta->getNbPages(),
|
||||
'has_previous_page' => $pagerfanta->hasPreviousPage(),
|
||||
'has_next_page' => $pagerfanta->hasNextPage(),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user