Completed
Push — master ( 357c73...c8ba24 )
by Karel
37:25 queued 27:22
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
    /**
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()
97
    {
98
        return array(
99
            'knp_pager.items' => array('items', 1),
100 4
        );
101
    }
102
}
103