Completed
Push — master ( 8425d0...d3b4d6 )
by Karel
06:32
created

PaginateElasticaQuerySubscriber::setRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 0
cts 6
cp 0
rs 9.4285
cc 3
eloc 5
nc 3
nop 1
crap 12
1
<?php
2
3
namespace FOS\ElasticaBundle\Subscriber;
4
5
use FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface;
6
use FOS\ElasticaBundle\Paginator\PartialResultsInterface;
7
use Knp\Component\Pager\Event\ItemsEvent;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\RequestStack;
11
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)
23
    {
24
        if ($requestStack instanceof Request) {
25
            $this->request = $requestStack;
26
        } elseif ($requestStack instanceof RequestStack) {
27
            $this->request = $requestStack->getMasterRequest();
28
        }
29
    }
30
31
    public function items(ItemsEvent $event)
32
    {
33
        if ($event->target instanceof PaginatorAdapterInterface) {
34
            // Add sort to query
35
            $this->setSorting($event);
36
37
            /** @var $results PartialResultsInterface */
38
            $results = $event->target->getResults($event->getOffset(), $event->getLimit());
39
40
            $event->count = $results->getTotalHits();
41
            $event->items = $results->toArray();
42
            $facets = $results->getFacets();
43
            if (null != $facets) {
44
                $event->setCustomPaginationParameter('facets', $facets);
45
            }
46
            $aggregations = $results->getAggregations();
47
            if (null != $aggregations) {
48
                $event->setCustomPaginationParameter('aggregations', $aggregations);
49
            }
50
51
            $event->stopPropagation();
52
        }
53
    }
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'], $options['defaultSortFieldName']);
64
65
        if (!empty($sortField)) {
66
            // determine sort direction
67
            $dir = 'asc';
68
            $sortDirection = $this->request->get($options['sortDirectionParameterName'], $options['defaultSortDirection']);
69
            if ('desc' === strtolower($sortDirection)) {
70
                $dir = 'desc';
71
            }
72
73
            // check if the requested sort field is in the sort whitelist
74
            if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'])) {
75
                throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField));
76
            }
77
78
            // set sort on active query
79
            $event->target->getQuery()->setSort(array(
80
                $sortField => array('order' => $dir),
81
            ));
82
        }
83
    }
84
85 4
    public static function getSubscribedEvents()
86
    {
87
        return array(
88 4
            'knp_pager.items' => array('items', 1),
89
        );
90
    }
91
}
92