Completed
Pull Request — master (#1162)
by Alessandro
33:21 queued 30:53
created

PaginateElasticaQuerySubscriber   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 123
Duplicated Lines 13.01 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 92.45%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 25
c 3
b 0
f 0
lcom 1
cbo 5
dl 16
loc 123
ccs 49
cts 53
cp 0.9245
rs 10

6 Methods

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

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 8
        $ignoreUnmapped = isset($options['sortIgnoreUnmapped']) ? $options['sortIgnoreUnmapped'] : true;
78
        $sort = [
79 8
            'order' => $this->getSortDirection($sortField, $options),
80 7
            'ignore_unmapped' => $ignoreUnmapped,
81
        ];
82
83 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...
84 4
            $path = is_callable($options['sortNestedPath']) ?
85 4
                $options['sortNestedPath']($sortField) : $options['sortNestedPath'];
86
87 4
            if (!empty($path)) {
88 4
                $sort['nested_path'] = $path;
89
            }
90
        }
91
92 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...
93 2
            $filter = is_callable($options['sortNestedFilter']) ?
94 2
                $options['sortNestedFilter']($sortField) : $options['sortNestedFilter'];
95
96 2
            if (!empty($filter)) {
97 2
                $sort['nested_filter'] = $filter;
98
            }
99
        }
100
101 7
        return $sort;
102
    }
103
104 8
    protected function getSortDirection($sortField, array $options = [])
105
    {
106 8
        $dir = 'asc';
107 8
        $sortDirection = $this->request->get($options['sortDirectionParameterName']);
108
109 8
        if (empty($sortDirection) && isset($options['defaultSortDirection'])) {
110
            $sortDirection = $options['defaultSortDirection'];
111
        }
112
113 8
        if ('desc' === strtolower($sortDirection)) {
114 1
            $dir = 'desc';
115
        }
116
117
        // check if the requested sort field is in the sort whitelist
118 8
        if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'])) {
119 1
            throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField));
120
        }
121
122 7
        return $dir;
123
    }
124
125
    /**
126
     * @return array
127
     */
128 4
    public static function getSubscribedEvents()
129
    {
130
        return array(
131 4
            'knp_pager.items' => array('items', 1),
132
        );
133
    }
134
}
135