2023-02-06 17:47:54 +01:00

136 lines
3.4 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
{
public const DEFAULT_CURRENT_PAGE_KEY = 'page';
public const DEFAULT_ITEM_PER_NUMBER_KEY = 'item_per_page';
public const DEFAULT_PAGE_NUMBER = 1;
/**
* the default item per page. This may be overriden by
* the request or inside the paginator.
*
* @var int
*/
private $itemPerPage;
/**
* the request stack.
*
* @var RequestStack
*/
private $requestStack;
/**
* the router and generator for url.
*
* @var RouterInterface
*/
private $router;
public function __construct(
RequestStack $requestStack,
RouterInterface $router,
$itemPerPage = 20
) {
$this->itemPerPage = $itemPerPage;
$this->requestStack = $requestStack;
$this->router = $router;
}
/**
* 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,
$route = null,
?array $routeParameters = null
) {
return new Paginator(
$totalItems,
$this->getCurrentItemsPerPage(),
$this->getCurrentPageNumber(),
null === $route ? $this->getCurrentRoute() : $route,
null === $routeParameters ? $this->getCurrentRouteParameters() :
$routeParameters,
$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()
);
}
}