Skip to content

Instantly share code, notes, and snippets.

@kibao
Created October 31, 2013 09:58
Show Gist options
  • Save kibao/7247174 to your computer and use it in GitHub Desktop.
Save kibao/7247174 to your computer and use it in GitHub Desktop.
JsonHandler for KnpPaginatiorBundle
<?php
namespace Serializer\Handler;
use FOS\RestBundle\View\ViewHandler;
use FOS\RestBundle\View\View;
use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
/**
* @author kibao
*/
class JsonHandler
{
protected $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function createResponse(ViewHandler $handler, View $view, Request $request, $format)
{
$data = $view->getData();
if ($data instanceof SlidingPagination) {
$view->setHeader('Link', $this->getPageLinksHeader($data));
$view->setData($data->getItems());
}
return $handler->createResponse($view, $request, $format);
}
protected function getPageLinksHeader(SlidingPagination $pagination)
{
$pages = $this->getPages($pagination);
$page_links = array();
foreach ($pages as $page => $path) {
$page_links[$page] = sprintf('<%s>; rel="%s"', $path, $page);
}
return implode(', ', $page_links);
}
protected function getPages(SlidingPagination $pagination)
{
$current = $pagination->getCurrentPageNumber();
$pagination_data = $pagination->getPaginationData();
$first = isset($pagination_data['first']) ? $pagination_data['first'] : null;
$previous = isset($pagination_data['previous']) ? $pagination_data['previous'] : null;
$next = isset($pagination_data['next']) ? $pagination_data['next'] : null;
$last = isset($pagination_data['last']) && $pagination_data['last'] != 0 ? $pagination_data['last'] : null;
$pages = array();
if (null !== $first && $current != $first) {
$pages["first"] = $this->generatePath($pagination, $first);
}
if (null !== $previous) {
$pages["previous"] = $this->generatePath($pagination, $previous);
}
if (null !== $next) {
$pages["next"] = $this->generatePath($pagination, $next);
}
if (null !== $last && $current != $last) {
$pages["last"] = $this->generatePath($pagination, $last);
}
return $pages;
}
protected function generatePath(SlidingPagination $pagination, $page, $absolute = true)
{
$params = $pagination->getQuery(
array(
$pagination->getPaginatorOption('pageParameterName') => $page
)
);
return $this->router->generate($pagination->getRoute(), $params, $absolute);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment