SearchQuery::setType()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php namespace Bardex\Elastic;
2
3
/**
4
 * Fluent interface for ElasticSearch
5
 * @package Bardex\Elastic
6
 */
7
class SearchQuery extends Query
8
{
9
    /**
10
     * Параметры запроса
11
     * @var array
12
     */
13
    protected $params = [];
14
15
    /**
16
     * @var Where
17
     */
18
    protected $whereHelper;
19
20
21
    public function __clone()
22
    {
23
        $this->whereHelper = new Where($this);
24
    }
25
26
    /**
27
     * @return SearchQuery
28
     */
29
    public function fork()
30
    {
31
        $copy = clone $this;
32
        return $copy;
33
    }
34
35
    /**
36
     * Установить имя индекса для поиска
37
     * @param $index
38
     * @return self $this
39
     */
40
    public function setIndex($index)
41
    {
42
        $this->params['index'] = (string)$index;
43
        return $this;
44
    }
45
46
    /**
47
     * Установить имя типа для поиска
48
     * @param $type
49
     * @return self $this
50
     */
51
    public function setType($type)
52
    {
53
        $this->params['type'] = (string)$type;
54
        return $this;
55
    }
56
57
58
    /**
59
     * Выводить перечисленные поля.
60
     * (не обязательный метод, по-умолчанию, выводятся все)
61
     * Методы select() и exclude() могут работать совместно.
62
     * @param array $fields
63
     * @return self $this;
64
     * @example $query->select(['id', 'title', 'brand.id', 'brand.title']);
65
     */
66
    public function select(array $fields)
67
    {
68
        $this->params['body']['_source']['includes'] = $fields;
69
        return $this;
70
    }
71
72
73
    /**
74
     * Добавить в результаты вычисляемое поле, на скриптовом языке painless или groovy
75
     * @param string $fieldName - имя поля в результатах (если такое поле уже есть в документе, то оно будет заменено)
76
     * @param Script $script - скрипт
77
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/search-request-script-fields.html
78
     * @return self $this
79
     */
80
    public function addScriptField($fieldName, Script $script)
81
    {
82
        $this->params['body']['script_fields'][$fieldName] = $script->compile();
83
        return $this;
84
    }
85
86
87
    /**
88
     * Удалить из выборки поля.
89
     * (не обязательный метод, по-умолчанию, выводятся все)
90
     * Методы select() и exclude() могут работать совместно.
91
     * @param array $fields
92
     * @return self $this;
93
     * @example $query->exclude(['anons', '*.anons']);
94
     */
95
    public function exclude(array $fields)
96
    {
97
        $this->params['body']['_source']['excludes'] = $fields;
98
        return $this;
99
    }
100
101
102
    /**
103
     * Добавить фильтр в raw формате, если готовые методы фильтрации не подходят.
104
     *
105
     * @param string $type - тип фильтрации (term|terms|match|range)
106
     * @param $filter - фильтр
107
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/query-dsl-terms-query.html
108
     * @return self $this
109
     */
110 View Code Duplication
    public function addFilter($type, $filter)
111
    {
112
        if (!isset($this->params['body']['query']['bool']['must'])) {
113
            $this->params['body']['query']['bool']['must'] = [];
114
        }
115
        $this->params['body']['query']['bool']['must'][] = [$type => $filter];
116
        return $this;
117
    }
118
119
    /**
120
     * Добавить отрицательный фильтр в raw формате, если готовые методы фильтрации не подходят.
121
     *
122
     * @param string $type - тип фильтрации (term|terms|match|range)
123
     * @param $filter - фильтр
124
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html
125
     * @return self $this
126
     */
127 View Code Duplication
    public function addNotFilter($type, $filter)
128
    {
129
        if (!isset($this->params['body']['query']['bool']['must_not'])) {
130
            $this->params['body']['query']['bool']['must_not'] = [];
131
        }
132
        $this->params['body']['query']['bool']['must_not'][] = [$type => $filter];
133
        return $this;
134
    }
135
136
137
    /**
138
     * Создать фильтр.
139
     *
140
     * @param $field - поле по которому фильтруем (id, page.categoryId...)
141
     * @example $query->where('channel')->equal(1)->where('page.categoryId')->in([10,12]);
142
     * @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...
143
     */
144
    public function where($field)
145
    {
146
        if (null === $this->whereHelper) {
147
            $this->whereHelper = new Where($this);
148
        }
149
        $this->whereHelper->setField($field);
150
        return $this->whereHelper;
151
    }
152
153
154
    /**
155
     * Добавить в фильтр сложное условие с вычислениями, на скриптовом языке painless или groovy.
156
     * Использование параметров рекомендуется, для увеличения производительности скриптов.
157
     *
158
     * @param Script $script - скрипт
159
     * @return self $this;
160
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/query-dsl-script-query.html
161
     * @link https://www.elastic.co/guide/en/elasticsearch/reference/5.0/modules-scripting-painless.html
162
     */
163
    public function whereScript(Script $script)
164
    {
165
        $this->addFilter('script', $script->compile());
166
        return $this;
167
    }
168
169
170
    /**
171
     * Установить поле сортировки.
172
     * Для сортировки по релевантности существует псевдополе _score (значение больше - релевантность лучше)
173
     * @param $field - поле сортировки
174
     * @param string $order - направление сортировки asc|desc
175
     * @example $query->setOrderBy('_score', 'desc');
176
     * @return self $this
177
     */
178
    public function setOrderBy($field, $order = 'asc')
179
    {
180
        $this->params['body']['sort'] = [];
181
        $this->addOrderBy($field, $order);
182
        return $this;
183
    }
184
185
    /**
186
     * Добавить поле сортировки.
187
     * Для сортировки по релевантности существует псевдополе _score (значение больше - релевантность лучше)
188
     * @param $field - поле сортировки
189
     * @param string $order - направление сортировки asc|desc
190
     * @example $query->addOrderBy('_score', 'desc');
191
     * @example $query->addOrderBy('seller.rating', 'desc');
192
     * @return self $this
193
     */
194
    public function addOrderBy($field, $order = 'asc')
195
    {
196
        $field = (string)$field;
197
        $order = (string)$order;
198
        if (!isset($this->params['body']['sort'])) {
199
            $this->params['body']['sort'] = [];
200
        }
201
        $this->params['body']['sort'][] = [$field => ['order' => $order]];
202
        return $this;
203
    }
204
205
206
    /**
207
     * Установить лимиты выборки
208
     * @param $limit - сколько строк выбирать
209
     * @param int $offset - сколько строк пропустить
210
     * @return self $this;
211
     */
212
    public function limit($limit, $offset = 0)
213
    {
214
        $this->params['body']['size'] = (int)$limit;
215
        $this->params['body']['from'] = (int)$offset;
216
        return $this;
217
    }
218
219
    /**
220
     * Получить собранный запрос
221
     * @return array
222
     */
223
    public function getQuery()
224
    {
225
        $params = $this->params;
226
227
        if (!isset($params['body']['_source'])) {
228
            $params['body']['_source'] = true;
229
        }
230
231
        return $params;
232
    }
233
234
    protected function executeQuery(array $query)
235
    {
236
        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...
237
    }
238
}
239