Completed
Push — master ( 77aa02...26f422 )
by Karel
19:59 queued 08:48
created

PaginateElasticaQuerySubscriber::setSorting()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 15
ccs 12
cts 12
cp 1
rs 9.2
c 2
b 0
f 0
cc 4
eloc 8
nc 4
nop 1
crap 4
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 9
    public function setRequest($requestStack)
23
    {
24 9
        if ($requestStack instanceof Request) {
25 9
            $this->request = $requestStack;
26 9
        } elseif ($requestStack instanceof RequestStack) {
27
            $this->request = $requestStack->getMasterRequest();
28
        }
29 9
    }
30
31
    /**
32
     * @param ItemsEvent $event
33
     */
34 9
    public function items(ItemsEvent $event)
35
    {
36 9
        if ($event->target instanceof PaginatorAdapterInterface) {
37
            // Add sort to query
38 9
            $this->setSorting($event);
39
40
            /** @var $results PartialResultsInterface */
41 8
            $results = $event->target->getResults($event->getOffset(), $event->getLimit());
42
43 8
            $event->count = $results->getTotalHits();
44 8
            $event->items = $results->toArray();
45 8
            $aggregations = $results->getAggregations();
46 8
            if (null != $aggregations) {
47
                $event->setCustomPaginationParameter('aggregations', $aggregations);
48
            }
49
50 8
            $event->stopPropagation();
51 8
        }
52 8
    }
53
54
    /**
55
     * Adds knp paging sort to query.
56
     *
57
     * @param ItemsEvent $event
58
     */
59 9
    protected function setSorting(ItemsEvent $event)
60
    {
61 9
        $options = $event->options;
62 9
        $sortField = $this->request->get($options['sortFieldParameterName']);
63
64 9
        if (!$sortField && isset($options['defaultSortFieldName'])) {
65 1
            $sortField = $options['defaultSortFieldName'];
66 1
        }
67
68 9
        if (!empty($sortField)) {
69 8
            $event->target->getQuery()->setSort(array(
70 8
                $sortField => $this->getSort($sortField, $options),
71 7
            ));
72 7
        }
73 8
    }
74
75 8
    protected function getSort($sortField, array $options = [])
76
    {
77
        $sort = [
78 8
            'order' => $this->getSortDirection($sortField, $options),
79 7
        ];
80
81 7 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...
82 4
            $path = is_callable($options['sortNestedPath']) ?
83 4
                $options['sortNestedPath']($sortField) : $options['sortNestedPath'];
84
85 4
            if (!empty($path)) {
86 4
                $sort['nested_path'] = $path;
87 4
            }
88 4
        }
89
90 7 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...
91 2
            $filter = is_callable($options['sortNestedFilter']) ?
92 2
                $options['sortNestedFilter']($sortField) : $options['sortNestedFilter'];
93
94 2
            if (!empty($filter)) {
95 2
                $sort['nested_filter'] = $filter;
96 2
            }
97 2
        }
98
99 7
        return $sort;
100
    }
101
102 8
    protected function getSortDirection($sortField, array $options = [])
103
    {
104 8
        $dir = 'asc';
105 8
        $sortDirection = $this->request->get($options['sortDirectionParameterName']);
106
107 8
        if (empty($sortDirection) && isset($options['defaultSortDirection'])) {
108
            $sortDirection = $options['defaultSortDirection'];
109
        }
110
111 8
        if ('desc' === strtolower($sortDirection)) {
112 1
            $dir = 'desc';
113 1
        }
114
115
        // check if the requested sort field is in the sort whitelist
116 8
        if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'])) {
117 1
            throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField));
118
        }
119
120 7
        return $dir;
121
    }
122
123
    /**
124
     * @return array
125
     */
126 4
    public static function getSubscribedEvents()
127
    {
128
        return array(
129 4
            'knp_pager.items' => array('items', 1),
130 4
        );
131
    }
132
}
133