Completed
Push — devel ( 3908d4...2f2813 )
by Alexey
02:14
created

SearchQuery   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 209
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 4

Importance

Changes 0
Metric Value
wmc 18
lcom 3
cbo 4
dl 0
loc 209
rs 10
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __clone() 0 4 1
A setIndex() 0 5 1
A setType() 0 5 1
A select() 0 5 1
A addScriptField() 0 5 1
A exclude() 0 5 1
A addFilter() 0 8 2
A where() 0 8 2
A whereScript() 0 5 1
A setOrderBy() 0 6 1
A addOrderBy() 0 10 2
A limit() 0 6 1
A getQuery() 0 10 2
A executeQuery() 0 4 1
1
<?php
2
3
namespace Bardex\Elastic;
4
5
use Bardex\Elastic\SearchResult;
6
7
8
/**
9
 * Fluent interface for ElasticSearch
10
 * @package Bardex\Elastic
11
 */
12
class SearchQuery extends Query
13
{
14
    /**
15
     * Параметры запроса
16
     * @var array
17
     */
18
    protected $params = [];
19
20
    /**
21
     * @var Where
22
     */
23
    protected $whereHelper;
24
25
26
    function __clone()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
27
    {
28
        $this->whereHelper = new Where($this);
29
    }
30
31
32
    /**
33
     * Установить имя индекса для поиска
34
     * @param $index
35
     * @return self $this
36
     */
37
    public function setIndex($index)
38
    {
39
        $this->params['index'] = (string) $index;
40
        return $this;
41
    }
42
43
    /**
44
     * Установить имя типа для поиска
45
     * @param $type
46
     * @return self $this
47
     */
48
    public function setType($type)
49
    {
50
        $this->params['type'] = (string) $type;
51
        return $this;
52
    }
53
54
55
    /**
56
     * Выводить перечисленные поля.
57
     * (не обязательный метод, по-умолчанию, выводятся все)
58
     * Методы select() и exclude() могут работать совместно.
59
     * @param array $fields
60
     * @return self $this;
61
     * @example $query->select(['id', 'title', 'brand.id', 'brand.title']);
62
     */
63
    public function select(array $fields)
64
    {
65
        $this->params['body']['_source']['includes'] = $fields;
66
        return $this;
67
    }
68
69
70
    /**
71
     * Добавить в результаты вычисляемое поле, на скриптовом языке painless или groovy
72
     * @param string $fieldName - имя поля в результатах (если такое поле уже есть в документе, то оно будет заменено)
73
     * @param Script $script - скрипт
74
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/search-request-script-fields.html
75
     * @return self $this
76
     */
77
    public function addScriptField($fieldName, Script $script)
78
    {
79
        $this->params['body']['script_fields'][$fieldName] = $script->compile();
80
        return $this;
81
    }
82
83
84
    /**
85
     * Удалить из выборки поля.
86
     * (не обязательный метод, по-умолчанию, выводятся все)
87
     * Методы select() и exclude() могут работать совместно.
88
     * @param array $fields
89
     * @return self $this;
90
     * @example $query->exclude(['anons', '*.anons']);
91
     */
92
    public function exclude(array $fields)
93
    {
94
        $this->params['body']['_source']['excludes'] = $fields;
95
        return $this;
96
    }
97
98
99
    /**
100
     * Добавить фильтр в raw формате, если готовые методы фильтрации не подходят.
101
     * Для удобства используй готовые методы фильтрации: where(), whereIn(), whereBetween(), whereMatch()
102
     * whereLess() и другие методы where*()
103
     *
104
     * @param string $type - тип фильтрации (term|terms|match|range)
105
     * @param $filter - фильтр
106
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/query-dsl-terms-query.html
107
     * @return self $this
108
     */
109
    public function addFilter($type, $filter)
110
    {
111
        if (!isset($this->params['body']['query']['bool']['must'])) {
112
            $this->params['body']['query']['bool']['must'] = [];
113
        }
114
        $this->params['body']['query']['bool']['must'][] = [$type => $filter];
115
        return $this;
116
    }
117
118
119
    /**
120
     * Создать фильтр.
121
     *
122
     * @param $field - поле по которому фильтруем (id, page.categoryId...)
123
     * @example $query->where('channel')->equal(1)->where('page.categoryId')->in([10,12]);
124
     * @return Where;
0 ignored issues
show
Documentation introduced by
The doc-type Where; could not be parsed: Expected "|" or "end of type", but got ";" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
125
     */
126
    public function where($field)
127
    {
128
        if (null === $this->whereHelper) {
129
            $this->whereHelper = new Where($this);
130
        }
131
        $this->whereHelper->setField($field);
132
        return $this->whereHelper;
133
    }
134
135
136
    /**
137
     * Добавить в фильтр сложное условие с вычислениями, на скриптовом языке painless или groovy.
138
     * Использование параметров рекомендуется, для увеличения производительности и эффективности компилирования скриптов.
139
     *
140
     * @param Script $script - скрипт
141
     * @return self $this;
142
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/query-dsl-script-query.html
143
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/modules-scripting-painless.html
144
     */
145
    public function whereScript(Script $script)
146
    {
147
        $this->addFilter('script', $script->compile());
148
        return $this;
149
    }
150
151
152
    /**
153
     * Установить поле сортировки.
154
     * Для сортировки по релевантности существует псевдополе _score (значение больше - релевантность лучше)
155
     * @param $field - поле сортировки
156
     * @param string $order - направление сортировки asc|desc
157
     * @example $query->setOrderBy('_score', 'desc');
158
     * @return self $this
159
     */
160
    public function setOrderBy($field, $order = 'asc')
161
    {
162
        $this->params['body']['sort'] = [];
163
        $this->addOrderBy($field, $order);
164
        return $this;
165
    }
166
167
    /**
168
     * Добавить поле сортировки.
169
     * Для сортировки по релевантности существует псевдополе _score (значение больше - релевантность лучше)
170
     * @param $field - поле сортировки
171
     * @param string $order - направление сортировки asc|desc
172
     * @example $query->addOrderBy('_score', 'desc');
173
     * @example $query->addOrderBy('seller.rating', 'desc');
174
     * @return self $this
175
     */
176
    public function addOrderBy($field, $order = 'asc')
177
    {
178
        $field = (string) $field;
179
        $order = (string) $order;
180
        if (!isset($this->params['body']['sort'])) {
181
            $this->params['body']['sort'] = [];
182
        }
183
        $this->params['body']['sort'][] = [$field => ['order' => $order]];
184
        return $this;
185
    }
186
187
188
    /**
189
     * Установить лимиты выборки
190
     * @param $limit - сколько строк выбирать
191
     * @param int $offset - сколько строк пропустить
192
     * @return self $this;
193
     */
194
    public function limit($limit, $offset = 0)
195
    {
196
        $this->params['body']['size'] = (int) $limit;
197
        $this->params['body']['from'] = (int) $offset;
198
        return $this;
199
    }
200
201
    /**
202
     * Получить собранный запрос
203
     * @return array
204
     */
205
    public function getQuery()
206
    {
207
        $params = $this->params;
208
209
        if (!isset($params['body']['_source'])) {
210
            $params['body']['_source'] = true;
211
        }
212
213
        return $params;
214
    }
215
216
    protected function executeQuery(array $query)
217
    {
218
        return $this->elastic->search($query);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->elastic->search($query); (callable) is incompatible with the return type declared by the abstract method Bardex\Elastic\Query::executeQuery of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
219
    }
220
}