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 | public function items(ItemsEvent $event) |
||
54 | |||
55 | /** |
||
56 | * Adds knp paging sort to query. |
||
57 | * |
||
58 | * @param ItemsEvent $event |
||
59 | */ |
||
60 | protected function setSorting(ItemsEvent $event) |
||
61 | { |
||
62 | $options = $event->options; |
||
63 | $sortField = $this->request->get($options['sortFieldParameterName']); |
||
64 | |||
65 | if (!$sortField && isset($options['defaultSortFieldName'])) { |
||
66 | $sortField = $options['defaultSortFieldName']; |
||
67 | } |
||
68 | |||
69 | if (!empty($sortField)) { |
||
70 | // determine sort direction |
||
71 | $dir = 'asc'; |
||
72 | $sortDirection = $this->request->get($options['sortDirectionParameterName']); |
||
73 | |||
74 | if (!$sortDirection && isset($options['defaultSortDirection'])) { |
||
75 | $sortDirection = $options['defaultSortDirection']; |
||
76 | } |
||
77 | |||
78 | if ('desc' === strtolower($sortDirection)) { |
||
79 | $dir = 'desc'; |
||
80 | } |
||
81 | |||
82 | // check if the requested sort field is in the sort whitelist |
||
83 | if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'])) { |
||
84 | throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField)); |
||
85 | 4 | } |
|
86 | |||
87 | // set sort on active query |
||
88 | 4 | $event->target->getQuery()->setSort(array( |
|
89 | $sortField => array('order' => $dir), |
||
90 | )); |
||
91 | } |
||
92 | } |
||
93 | |||
94 | public static function getSubscribedEvents() |
||
100 | } |
||
101 |