Completed
Pull Request — master (#1162)
by Alessandro
31:42 queued 21:39
created

PaginateElasticaQuerySubscriber::items()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 11
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
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
            $event->target->getQuery()->setSort(array(
70
                $sortField => $this->getSort($sortField, $options),
71
            ));
72
        }
73
    }
74
75
    protected function getSort($sortField, array $options = [])
76
    {
77
        $ignoreUnmapped = isset($options['sortIgnoreUnmapped']) ? $options['sortIgnoreUnmapped'] : true;
78
        $sort = [
79
            'order' => $this->getSortDirection($sortField, $options),
80
            'ignore_unmapped' => $ignoreUnmapped,
81
        ];
82
83 View Code Duplication
        if (isset($options['sortNestedPath'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
            $path = is_callable($options['sortNestedPath']) ?
85
                $options['sortNestedPath']($sortField) : $options['sortNestedPath'];
86
87
            if (!empty($path)) {
88
                $sort['nested_path'] = $path;
89
            }
90
        }
91
92 View Code Duplication
        if (isset($options['sortNestedFilter'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
93
            $filter = is_callable($options['sortNestedFilter']) ?
94
                $options['sortNestedFilter']($sortField) : $options['sortNestedFilter'];
95
96 4
            if (!empty($filter)) {
97
                $sort['nested_filter'] = $filter;
98
            }
99 4
        }
100
101
        return $sort;
102
    }
103
104
    protected function getSortDirection($sortField, array $options = [])
105
    {
106
        $dir = 'asc';
107
        $sortDirection = $this->request->get($options['sortDirectionParameterName']);
108
109
        if (empty($sortDirection) && isset($options['defaultSortDirection'])) {
110
            $sortDirection = $options['defaultSortDirection'];
111
        }
112
113
        if ('desc' === strtolower($sortDirection)) {
114
            $dir = 'desc';
115
        }
116
117
        // check if the requested sort field is in the sort whitelist
118
        if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'])) {
119
            throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField));
120
        }
121
122
        return $dir;
123
    }
124
125
    /**
126
     * @return array
127
     */
128
    public static function getSubscribedEvents()
129
    {
130
        return array(
131
            'knp_pager.items' => array('items', 1),
132
        );
133
    }
134
}
135