1 | <?php |
||
12 | class PaginateElasticaQuerySubscriber implements EventSubscriberInterface |
||
13 | { |
||
14 | /** |
||
15 | * @var Request |
||
16 | */ |
||
17 | private $request; |
||
18 | |||
19 | /** |
||
20 | * @param RequestStack|Request $requestStack |
||
21 | */ |
||
22 | public function setRequest($requestStack) |
||
30 | |||
31 | /** |
||
32 | * @param ItemsEvent $event |
||
33 | */ |
||
34 | public function items(ItemsEvent $event) |
||
35 | { |
||
36 | if ($event->target instanceof PaginatorAdapterInterface) { |
||
37 | // Add sort to query |
||
38 | $this->setSorting($event); |
||
39 | |||
40 | /** @var $results PartialResultsInterface */ |
||
41 | $results = $event->target->getResults($event->getOffset(), $event->getLimit()); |
||
42 | |||
43 | $event->count = $results->getTotalHits(); |
||
44 | $event->items = $results->toArray(); |
||
45 | $aggregations = $results->getAggregations(); |
||
46 | if (null != $aggregations) { |
||
47 | $event->setCustomPaginationParameter('aggregations', $aggregations); |
||
48 | } |
||
49 | |||
50 | $event->stopPropagation(); |
||
51 | } |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * Adds knp paging sort to query. |
||
56 | * |
||
57 | * @param ItemsEvent $event |
||
58 | */ |
||
59 | protected function setSorting(ItemsEvent $event) |
||
60 | { |
||
61 | $options = $event->options; |
||
62 | $sortField = $this->request->get($options['sortFieldParameterName']); |
||
63 | |||
64 | if (!$sortField && isset($options['defaultSortFieldName'])) { |
||
65 | $sortField = $options['defaultSortFieldName']; |
||
66 | } |
||
67 | |||
68 | if (!empty($sortField)) { |
||
69 | // determine sort direction |
||
70 | $dir = 'asc'; |
||
71 | $sortDirection = $this->request->get($options['sortDirectionParameterName']); |
||
72 | |||
73 | if (!$sortDirection && isset($options['defaultSortDirection'])) { |
||
74 | $sortDirection = $options['defaultSortDirection']; |
||
75 | } |
||
76 | |||
77 | if ('desc' === strtolower($sortDirection)) { |
||
78 | $dir = 'desc'; |
||
79 | } |
||
80 | |||
81 | // check if the requested sort field is in the sort whitelist |
||
82 | if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'])) { |
||
83 | throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField)); |
||
84 | } |
||
85 | |||
86 | // set sort on active query |
||
87 | $event->target->getQuery()->setSort(array( |
||
88 | $sortField => array('order' => $dir, 'ignore_unmapped' => true), |
||
89 | )); |
||
90 | } |
||
91 | } |
||
92 | |||
93 | /** |
||
94 | * @return array |
||
95 | */ |
||
96 | public static function getSubscribedEvents() |
||
102 | } |
||
103 |