Completed
Push — master ( 7d3672...a34d6f )
by Simonas
357:48 queued 292:56
created

FuzzySearch::modifySearch()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
rs 8.8571
cc 5
eloc 11
nc 4
nop 3
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\Search;
13
14
use ONGR\ElasticsearchDSL\Query\BoolQuery;
15
use ONGR\ElasticsearchDSL\Query\FuzzyQuery;
16
use ONGR\ElasticsearchDSL\Search;
17
use ONGR\FilterManagerBundle\Filter\FilterState;
18
use ONGR\FilterManagerBundle\Search\SearchRequest;
19
20
/**
21
 * This class runs match search.
22
 */
23
class FuzzySearch extends AbstractSingleValue
24
{
25
    /**
26
     * @var array Fuzzy query parameters.
27
     */
28
    private $parameters = [];
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function modifySearch(Search $search, FilterState $state = null, SearchRequest $request = null)
34
    {
35
        if ($state && $state->isActive()) {
36
            if (strpos($this->getField(), ',') !== false) {
37
                $subQuery = new BoolQuery();
38
                foreach (explode(',', $this->getField()) as $field) {
39
                    $subQuery->add(new FuzzyQuery($field, $state->getValue(), $this->getParameters()), 'should');
40
                }
41
                $search->addQuery($subQuery, 'must');
42
            } else {
43
                $search->addQuery(
44
                    new FuzzyQuery($this->getField(), $state->getValue(), $this->getParameters()),
45
                    'must'
46
                );
47
            }
48
        }
49
    }
50
51
    /**
52
     * @return array
53
     */
54
    public function getParameters()
55
    {
56
        return array_filter($this->parameters);
57
    }
58
59
    /**
60
     * The maximum edit distance.
61
     *
62
     * @param string|int|float $fuzziness
63
     */
64
    public function setFuzziness($fuzziness)
65
    {
66
        $this->parameters['fuzziness'] = $fuzziness;
67
    }
68
69
    /**
70
     * The number of initial characters which will not be “fuzzified”.
71
     *
72
     * @param int $prefixLength
73
     */
74
    public function setPrefixLength($prefixLength)
75
    {
76
        $this->parameters['prefix_length'] = $prefixLength;
77
    }
78
79
    /**
80
     * The maximum number of terms that the fuzzy query will expand to.
81
     *
82
     * @param int $maxExpansions
83
     */
84
    public function setMaxExpansions($maxExpansions)
85
    {
86
        $this->parameters['max_expansions'] = $maxExpansions;
87
    }
88
}
89