Added knp paginator sort functionality to PaginateElasticaQuerySubscriber
This commit is contained in:
parent
e74acb1e4f
commit
13c2d10e39
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -86,6 +86,9 @@
|
|||
|
||||
<service id="fos_elastica.paginator.subscriber" class="FOS\ElasticaBundle\Subscriber\PaginateElasticaQuerySubscriber">
|
||||
<tag name="knp_paginator.subscriber" />
|
||||
<call method="setContainer">
|
||||
<argument type="service" id="service_container" />
|
||||
</call>
|
||||
</service>
|
||||
|
||||
<service id="fos_elastica.property_accessor" class="%fos_elastica.property_accessor.class%" />
|
||||
|
|
|
@ -9,9 +9,20 @@ use FOS\ElasticaBundle\Paginator\PartialResultsInterface;
|
|||
|
||||
class PaginateElasticaQuerySubscriber implements EventSubscriberInterface
|
||||
{
|
||||
private $container;
|
||||
|
||||
public function setContainer($container)
|
||||
{
|
||||
$this->container = $container;
|
||||
}
|
||||
|
||||
public function items(ItemsEvent $event)
|
||||
{
|
||||
if ($event->target instanceof PaginatorAdapterInterface) {
|
||||
|
||||
// Add sort to query
|
||||
$this->addPagingSort($event);
|
||||
|
||||
/** @var $results PartialResultsInterface */
|
||||
$results = $event->target->getResults($event->getOffset(), $event->getLimit());
|
||||
|
||||
|
@ -26,6 +37,38 @@ class PaginateElasticaQuerySubscriber implements EventSubscriberInterface
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds knp paging sort to query
|
||||
*
|
||||
* @param ItemsEvent $event
|
||||
* @return void
|
||||
*/
|
||||
protected function addPagingSort(ItemsEvent $event)
|
||||
{
|
||||
$request = $this->container->get('request');
|
||||
$options = $event->options;
|
||||
$sortField = $request->get($options['sortFieldParameterName']);
|
||||
|
||||
if (!empty($sortField)) {
|
||||
// determine sort direction
|
||||
$dir = 'asc';
|
||||
$sortDirection = $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(
|
||||
|
|
Loading…
Reference in a new issue