Merge pull request #485 from piotrantosik/elastica-knp-paginator-sort

Added knp paginator sort functionality to PaginateElasticaQuerySubscribe
This commit is contained in:
Tim Nagel 2014-04-04 08:46:40 +11:00
commit d67d525b66
3 changed files with 54 additions and 0 deletions

View file

@ -126,4 +126,14 @@ class RawPaginatorAdapter implements PaginatorAdapterInterface
return $this->facets;
}
/**
* Returns the Query
*
* @return Query the search query
*/
public function getQuery()
{
return $this->query;
}
}

View file

@ -85,6 +85,9 @@
</service>
<service id="fos_elastica.paginator.subscriber" class="FOS\ElasticaBundle\Subscriber\PaginateElasticaQuerySubscriber">
<call method="setRequest">
<argument type="service" id="request" on-invalid="null" strict="false" />
</call>
<tag name="knp_paginator.subscriber" />
</service>

View file

@ -2,6 +2,7 @@
namespace FOS\ElasticaBundle\Subscriber;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;
use FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface;
@ -9,9 +10,19 @@ use FOS\ElasticaBundle\Paginator\PartialResultsInterface;
class PaginateElasticaQuerySubscriber implements EventSubscriberInterface
{
private $request;
public function setRequest(Request $request = null)
{
$this->request = $request;
}
public function items(ItemsEvent $event)
{
if ($event->target instanceof PaginatorAdapterInterface) {
// Add sort to query
$this->setSorting($event);
/** @var $results PartialResultsInterface */
$results = $event->target->getResults($event->getOffset(), $event->getLimit());
@ -26,6 +37,36 @@ class PaginateElasticaQuerySubscriber implements EventSubscriberInterface
}
}
/**
* Adds knp paging sort to query
*
* @param ItemsEvent $event
*/
protected function setSorting(ItemsEvent $event)
{
$options = $event->options;
$sortField = $this->request->get($options['sortFieldParameterName']);
if (!empty($sortField)) {
// determine sort direction
$dir = 'asc';
$sortDirection = $this->request->get($options['sortDirectionParameterName']);
if ('desc' === strtolower($sortDirection)) {
$dir = 'desc';
}
// check if the requested sort field is in the sort whitelist
if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'])) {
throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField));
}
// set sort on active query
$event->target->getQuery()->setSort(array(
$sortField => array('order' => $dir),
));
}
}
public static function getSubscribedEvents()
{
return array(