Completed
Pull Request — master (#1019)
by
unknown
06:04
created

PaginateElasticaQuerySubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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