Completed
Pull Request — master (#188)
by
unknown
63:26
created

DynamicAggregateFilter::preProcessSearch()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 57
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 3
Metric Value
c 4
b 1
f 3
dl 0
loc 57
rs 8.7433
cc 6
eloc 37
nc 12
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\FilterManagerBundle\Filter\Widget\Dynamic;
13
14
use ONGR\ElasticsearchBundle\Result\Aggregation\AggregationValue;
15
use ONGR\ElasticsearchDSL\Aggregation\FilterAggregation;
16
use ONGR\ElasticsearchDSL\Aggregation\NestedAggregation;
17
use ONGR\ElasticsearchDSL\Aggregation\TermsAggregation;
18
use ONGR\ElasticsearchDSL\BuilderInterface;
19
use ONGR\ElasticsearchDSL\Query\BoolQuery;
20
use ONGR\ElasticsearchDSL\Query\NestedQuery;
21
use ONGR\ElasticsearchDSL\Query\TermQuery;
22
use ONGR\ElasticsearchDSL\Query\TermsQuery;
23
use ONGR\ElasticsearchDSL\Search;
24
use ONGR\ElasticsearchBundle\Result\DocumentIterator;
25
use ONGR\FilterManagerBundle\Filter\FilterState;
26
use ONGR\FilterManagerBundle\Filter\Helper\SizeAwareTrait;
27
use ONGR\FilterManagerBundle\Filter\Helper\ViewDataFactoryInterface;
28
use ONGR\FilterManagerBundle\Filter\ViewData\AggregateViewData;
29
use ONGR\FilterManagerBundle\Filter\ViewData;
30
use ONGR\FilterManagerBundle\Filter\Widget\AbstractSingleRequestValueFilter;
31
use ONGR\FilterManagerBundle\Filter\Helper\FieldAwareInterface;
32
use ONGR\FilterManagerBundle\Filter\Helper\FieldAwareTrait;
33
use ONGR\FilterManagerBundle\Search\SearchRequest;
34
use Symfony\Component\HttpFoundation\Request;
35
36
/**
37
 * This class provides single terms choice.
38
 */
39
class DynamicAggregateFilter extends AbstractSingleRequestValueFilter implements FieldAwareInterface, ViewDataFactoryInterface
40
{
41
    use FieldAwareTrait, SizeAwareTrait;
42
43
    /**
44
     * @var array
45
     */
46
    private $sortType;
47
48
    /**
49
     * @var string
50
     */
51
    private $nameField;
52
53
    /**
54
     * @var array
55
     */
56
    private $valueArray;
57
58
    /**
59
     * @param array $sortType
60
     */
61
    public function setSortType($sortType)
62
    {
63
        $this->sortType = $sortType;
64
    }
65
66
    /**
67
     * @return array
68
     */
69
    public function getSortType()
70
    {
71
        return $this->sortType;
72
    }
73
74
    /**
75
     * @return string
76
     */
77
    public function getNameField()
78
    {
79
        return $this->nameField;
80
    }
81
82
    /**
83
     * @param string $nameField
84
     */
85
    public function setNameField($nameField)
86
    {
87
        $this->nameField = $nameField;
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function modifySearch(Search $search, FilterState $state = null, SearchRequest $request = null)
94
    {
95
        list($path, $field) = explode('>', $this->getField());
96
97
        if ($state && $state->isActive()) {
98
            $boolQuery = new BoolQuery();
99
            foreach ($state->getValue() as $value) {
100
                $boolQuery->add(
101
                    new NestedQuery(
102
                        $path,
103
                        new TermQuery($field, $value)
104
                    )
105
                );
106
            }
107
            $search->addPostFilter($boolQuery);
108
        }
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function preProcessSearch(Search $search, Search $relatedSearch, FilterState $state = null)
115
    {
116
        list($path, $field) = explode('>', $this->getField());
117
        $name = $state->getName();
0 ignored issues
show
Bug introduced by
It seems like $state is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
118
        $aggregation = new NestedAggregation(
119
            $name,
120
            $path
121
        );
122
        $termsAggregation = new TermsAggregation('query', $field);
123
        $termsAggregation->addParameter('size', 0);
124
125
        if ($this->getSortType()) {
126
            $termsAggregation->addParameter('order', [$this->getSortType()['type'] => $this->getSortType()['order']]);
127
        }
128
129
        if ($this->getSize() > 0) {
130
            $termsAggregation->addParameter('size', $this->getSize());
131
        }
132
133
        $termsAggregation->addAggregation(
134
            new TermsAggregation('name', $this->getNameField())
135
        );
136
        $aggregation->addAggregation($termsAggregation);
137
        $filterAggregation = new FilterAggregation($name . '-filter');
138
        $filterAggregation->setFilter($relatedSearch->getPostFilters());
139
140
        if ($state->isActive()) {
141
            $this->valueArray = $state->getValue();
142
143
            foreach ($state->getValue() as $key => $term) {
144
                $terms = $state->getValue();
145
                array_splice($terms, $key, 1);
146
147
                if (!count($terms)) {
148
                    break;
149
                }
150
151
                $this->addSubFilterAggregation(
152
                    $filterAggregation,
153
                    $aggregation,
154
                    $terms,
155
                    $term
156
                );
157
            }
158
159
            $this->addSubFilterAggregation(
160
                $filterAggregation,
161
                $aggregation,
162
                $state->getValue(),
163
                'all-selected'
164
            );
165
        } else {
166
            $filterAggregation->addAggregation($aggregation);
167
        }
168
169
        $search->addAggregation($filterAggregation);
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175
    public function createViewData()
176
    {
177
        return new AggregateViewData();
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183
    public function getViewData(DocumentIterator $result, ViewData $data)
184
    {
185
        $unsortedChoices = [];
186
187
        /** @var AggregationValue $bucket */
188
        foreach ($this->fetchAggregation($result, $data->getName()) as $bucket) {
189
            $active = $this->isChoiceActive($bucket['key'], $data);
190
            $choice = new ViewData\Choice();
191
            $choice->setLabel($bucket->getValue('key'));
192
            $choice->setCount($bucket['doc_count']);
193
            $choice->setActive($active);
194 View Code Duplication
            if ($active) {
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...
195
                $choice->setUrlParameters($this->getUnsetUrlParameters($bucket['key'], $data));
196
            } else {
197
                $choice->setUrlParameters($this->getOptionUrlParameters($bucket['key'], $data));
198
            }
199
            $unsortedChoices[$bucket->getAggregation('name')->getBuckets()[0]['key']][] = $choice;
200
        }
201
202
        /** @var AggregateViewData $data */
203
        foreach ($unsortedChoices as $name => $choices) {
204
            $choiceViewData = new ViewData\ChoicesAwareViewData();
205
            $choiceViewData->setName($name);
206
            $choiceViewData->setChoices($choices);
207
            $choiceViewData->setUrlParameters([]);
208
            $choiceViewData->setResetUrlParameters([]);
209
            $data->addItem($choiceViewData);
210
        }
211
212
        return $data;
213
    }
214
215
    /**
216
     * {@inheritdoc}
217
     */
218
    public function isRelated()
219
    {
220
        return true;
221
    }
222
223
    /**
224
     * Fetches buckets from search results.
225
     *
226
     * @param DocumentIterator $result Search results.
227
     * @param string           $name   Filter name.
228
     *
229
     * @return array Buckets.
230
     */
231
    private function fetchAggregation(DocumentIterator $result, $name)
232
    {
233
        $data = [];
234
        $aggregation = $result->getAggregation(sprintf('%s-filter', $name));
235
236
        if ($result->getAggregation($name)) {
237
            $aggregation = $aggregation->find($name.'.query');
238
            $data['unfiltered'] = $aggregation;
239
240
            return $data;
241
        }
242
243
        if (isset($this->valueArray)) {
244
            foreach ($this->valueArray as $value) {
245
                $data[$value] = $aggregation->find($value.'.query');
246
            }
247
248
            $data['all-selected'] = $aggregation->find('all-selected.query');
249
250
            return $data;
251
        }
252
253
        return [];
254
    }
255
256
    /**
257
     * A method used to add an additional filter to the aggregations
258
     * in preProcessSearch
259
     *
260
     * @param FilterAggregation $filterAggregation
261
     * @param NestedAggregation $deepLevelAggregation
262
     * @param array             $terms Terms of additional filter
263
     * @param string            $aggName
264
     *
265
     * @return BuilderInterface
266
     */
267
    private function addSubFilterAggregation(
268
        $filterAggregation,
269
        $deepLevelAggregation,
270
        $terms,
271
        $aggName
272
    ) {
273
        list($path, $field) = explode('>', $this->getField());
274
        $innerFilterAggregation = new FilterAggregation(
275
            $aggName,
276
            new NestedQuery(
277
                $path,
278
                new TermsQuery($field, $terms)
279
            )
280
        );
281
        $innerFilterAggregation->addAggregation($deepLevelAggregation);
282
        $filterAggregation->addAggregation($innerFilterAggregation);
283
    }
284
285
    /**
286
     * @param string   $key
287
     * @param ViewData $data
288
     *
289
     * @return array
290
     */
291
    private function getOptionUrlParameters($key, ViewData $data)
292
    {
293
        $parameters = $data->getResetUrlParameters();
294
        $parameters[$this->getRequestField()][] = $key;
295
296
        return $parameters;
297
    }
298
299
    /**
300
     * Returns url with selected term disabled.
301
     *
302
     * @param string   $key
303
     * @param ViewData $data
304
     *
305
     * @return array
306
     */
307
    private function getUnsetUrlParameters($key, ViewData $data)
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
308
    {
309
        return $data->getResetUrlParameters();
310
    }
311
312
    /**
313
     * Returns whether choice with the specified key is active.
314
     *
315
     * @param string   $key
316
     * @param ViewData $data
317
     *
318
     * @return bool
319
     */
320
    private function isChoiceActive($key, ViewData $data)
321
    {
322
        return $data->getState()->isActive() && in_array($key, $data->getState()->getValue());
323
    }
324
}
325