Completed
Push — devel ( a06d0d...3b3966 )
by Alexey
02:12
created

SearchQuery::fork()   A

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