Files
chill-bundles/src/Bundle/ChillMainBundle/Pagination/PaginatorFactory.php

123 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Pagination;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
/**
* Create paginator instances.
*/
class PaginatorFactory
{
final public const DEFAULT_CURRENT_PAGE_KEY = 'page';
final public const DEFAULT_ITEM_PER_NUMBER_KEY = 'item_per_page';
final public const DEFAULT_PAGE_NUMBER = 1;
/**
* @param int $itemPerPage
*/
public function __construct(
/**
* the request stack.
*/
private readonly RequestStack $requestStack,
/**
* the router and generator for url.
*/
private readonly RouterInterface $router,
/**
* the default item per page. This may be overriden by
* the request or inside the paginator.
*/
private $itemPerPage = 20
) {
}
/**
* create a paginator instance.
*
* The default route and route parameters are the current ones. If set,
* thos route are overriden.
*
* @param int $totalItems
* @param string|null $route the specific route to use in pages
* @param array|null $routeParameters the specific route parameters to use in pages
*
* @return PaginatorInterface
*/
public function create(
$totalItems,
?string $route = null,
?array $routeParameters = null
) {
return new Paginator(
$totalItems,
$this->getCurrentItemsPerPage(),
$this->getCurrentPageNumber(),
$route ?? $this->getCurrentRoute(),
$routeParameters ?? $this->getCurrentRouteParameters(),
$this->router,
self::DEFAULT_CURRENT_PAGE_KEY,
self::DEFAULT_ITEM_PER_NUMBER_KEY
);
}
public function getCurrentItemsPerPage()
{
return $this->requestStack
->getCurrentRequest()
->query
->getInt(self::DEFAULT_ITEM_PER_NUMBER_KEY, $this->itemPerPage);
}
public function getCurrentPageFirstItemNumber()
{
return ($this->getCurrentPageNumber() - 1) *
$this->getCurrentItemsPerPage();
}
/**
* @return int
*/
public function getCurrentPageNumber()
{
return $this->requestStack
->getCurrentRequest()
->query
->getInt(self::DEFAULT_CURRENT_PAGE_KEY, self::DEFAULT_PAGE_NUMBER);
}
protected function getCurrentRoute()
{
$request = $this->requestStack->getCurrentRequest();
return $request->get('_route');
}
protected function getCurrentRouteParameters()
{
return array_merge(
$this->router->getContext()->getParameters(),
// get the route parameters
$this->requestStack
->getCurrentRequest()
->attributes->get('_route_params'),
// get the query parameters
$this->requestStack
->getCurrentRequest()->query->all()
);
}
}