Completed
Push — master ( f7313f...f3d09b )
by Karel
03:49
created

PaginateElasticaQuerySubscriber   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 121
Duplicated Lines 13.22 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 92.16%

Importance

Changes 0
Metric Value
wmc 24
c 0
b 0
f 0
lcom 1
cbo 5
dl 16
loc 121
ccs 47
cts 51
cp 0.9216
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setRequest() 0 8 3
A items() 0 19 3
A getSubscribedEvents() 0 6 1
C getSort() 16 26 7
B getSortDirection() 0 20 6
A setSorting() 0 15 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
        } 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
        }
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
        }
67
68 9
        if (!empty($sortField)) {
69 8
            $event->target->getQuery()->setSort(array(
70 8
                $sortField => $this->getSort($sortField, $options),
71
            ));
72
        }
73 8
    }
74
75 8
    protected function getSort($sortField, array $options = [])
76
    {
77
        $sort = [
78 8
            'order' => $this->getSortDirection($sortField, $options),
79
        ];
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
            }
88
        }
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
            }
97
        }
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
        }
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
        );
131
    }
132
}
133