Test Failed
Pull Request — master (#170)
by Serhii
13:10
created

ElasticSearchEngine   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 169
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
eloc 44
c 7
b 0
f 0
dl 0
loc 169
rs 10
ccs 52
cts 52
cp 1
wmc 18

13 Methods

Rating   Name   Duplication   Size   Complexity  
A mapIds() 0 3 1
A map() 0 11 1
A update() 0 8 3
A search() 0 3 1
A flush() 0 9 2
A __construct() 0 3 1
A deleteIndex() 0 2 1
A getTotalCount() 0 3 1
A lazyMap() 0 3 1
A performSearch() 0 19 3
A paginate() 0 5 1
A delete() 0 5 1
A createIndex() 0 2 1
1
<?php
2
3
namespace Matchish\ScoutElasticSearch\Engines;
4
5
use Elasticsearch\Common\Exceptions\ServerErrorResponseException;
6
use Illuminate\Database\Eloquent\Collection;
7
use Illuminate\Support\LazyCollection;
8
use Laravel\Scout\Builder as BaseBuilder;
9
use Laravel\Scout\Engines\Engine;
10
use Matchish\ScoutElasticSearch\ElasticSearch\HitsIteratorAggregate;
11
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Bulk;
12
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Indices\Refresh;
13
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Search as SearchParams;
14
use Matchish\ScoutElasticSearch\ElasticSearch\SearchFactory;
15
use Matchish\ScoutElasticSearch\ElasticSearch\SearchResults;
16
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
17
use ONGR\ElasticsearchDSL\Search;
18
use Laravel\Scout\Builder;
19
20
final class ElasticSearchEngine extends Engine
21
{
22
    /**
23
     * The ElasticSearch client.
24
     *
25
     * @var \Elasticsearch\Client
26
     */
27
    protected $elasticsearch;
28
29
    /**
30
     * Create a new engine instance.
31
     *
32
     * @param \Elasticsearch\Client $elasticsearch
33 27
     * @return void
34
     */
35 27
    public function __construct(\Elasticsearch\Client $elasticsearch)
36 27
    {
37
        $this->elasticsearch = $elasticsearch;
38
    }
39
40
    /**
41 20
     * {@inheritdoc}
42
     */
43 20
    public function update($models)
44 20
    {
45 20
        $params = new Bulk();
46 20
        $params->index($models);
47 1
        $response = $this->elasticsearch->bulk($params->toArray());
48 1
        if (array_key_exists('errors', $response) && $response['errors']) {
49
            $error = new ServerErrorResponseException(json_encode($response, JSON_PRETTY_PRINT));
50 19
            throw new \Exception('Bulk update error', $error->getCode(), $error);
51
        }
52
    }
53
54
    /**
55 1
     * {@inheritdoc}
56
     */
57 1
    public function delete($models)
58 1
    {
59 1
        $params = new Bulk();
60 1
        $params->delete($models);
61
        $this->elasticsearch->bulk($params->toArray());
62
    }
63
64
    /**
65 2
     * {@inheritdoc}
66
     */
67 2
    public function flush($model)
68 2
    {
69 2
        $indexName = $model->searchableAs();
70 2
        $exist = $this->elasticsearch->indices()->exists(['index' => $indexName]);
71 2
        if ($exist) {
72 2
            $body = (new Search())->addQuery(new MatchAllQuery())->toArray();
73 2
            $params = new SearchParams($indexName, $body);
74
            $this->elasticsearch->deleteByQuery($params->toArray());
75 2
            $this->elasticsearch->indices()->refresh((new Refresh($indexName))->toArray());
76
        }
77
    }
78
79
    /**
80 6
     * {@inheritdoc}
81
     */
82 6
    public function search(BaseBuilder $builder)
83
    {
84
        return $this->performSearch($builder, []);
85
    }
86
87
    /**
88 1
     * {@inheritdoc}
89
     */
90 1
    public function paginate(BaseBuilder $builder, $perPage, $page)
91 1
    {
92 1
        return $this->performSearch($builder, [
93
            'from' => ($page - 1) * $perPage,
94
            'size' => $perPage,
95
        ]);
96
    }
97
98
    /**
99 1
     * {@inheritdoc}
100
     */
101 1
    public function mapIds($results)
102
    {
103
        return collect($results['hits']['hits'])->pluck('_id');
104
    }
105
106
    /**
107 7
     * {@inheritdoc}
108
     */
109 7
    public function map(BaseBuilder $builder, $results, $model)
110 7
    {
111
        $hits = app()->makeWith(
112 7
            HitsIteratorAggregate::class,
113 7
            [
114
                'results'  => $results,
115
                'callback' => $builder->queryCallback,
116
            ]
117 7
        );
118
119
        return new Collection($hits);
120
    }
121
122
    /**
123 1
     * Map the given results to instances of the given model via a lazy collection.
124
     *
125 1
     * @param  \Laravel\Scout\Builder  $builder
126
     * @param  mixed  $results
127
     * @param  \Illuminate\Database\Eloquent\Model  $model
128
     * @return \Illuminate\Support\LazyCollection
129
     */
130
    public function lazyMap(Builder $builder, $results, $model)
0 ignored issues
show
Unused Code introduced by
The parameter $model is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

130
    public function lazyMap(Builder $builder, $results, /** @scrutinizer ignore-unused */ $model)

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

Loading history...
Unused Code introduced by
The parameter $builder is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

130
    public function lazyMap(/** @scrutinizer ignore-unused */ Builder $builder, $results, $model)

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

Loading history...
Unused Code introduced by
The parameter $results is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

130
    public function lazyMap(Builder $builder, /** @scrutinizer ignore-unused */ $results, $model)

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

Loading history...
131
    {
132
        throw new \Error('Not implemented');
133 7
    }
134
135 7
        /**
136 7
     * Create a search index.
137
     *
138 2
     * @param  string  $name
139
     * @param  array  $options
140 2
     * @return mixed
141 2
     */
142 2
    public function createIndex($name, array $options = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

142
    public function createIndex(/** @scrutinizer ignore-unused */ $name, array $options = []) {

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

Loading history...
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

142
    public function createIndex($name, /** @scrutinizer ignore-unused */ array $options = []) {

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

Loading history...
143
        throw new \Error('Not implemented');
144
    }
145
146
    /**
147 5
     * Delete a search index.
148 5
     *
149 5
     * @param  string  $name
150
     * @return mixed
151 5
     */
152
    public function deleteIndex($name) {
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

152
    public function deleteIndex(/** @scrutinizer ignore-unused */ $name) {

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

Loading history...
153
        throw new \Error('Not implemented');
154
    }
155
156
157
    /**
158
     * {@inheritdoc}
159
     */
160
    public function getTotalCount($results)
161
    {
162
        return $results['hits']['total']['value'];
163
    }
164
165
    /**
166
     * @param BaseBuilder $builder
167
     * @param array $options
168
     * @return SearchResults|mixed
169
     */
170
    private function performSearch(BaseBuilder $builder, $options = [])
171
    {
172
        $searchBody = SearchFactory::create($builder, $options);
173
        if ($builder->callback) {
174
            /** @var callable */
175
            $callback = $builder->callback;
176
177
            return call_user_func(
178
                $callback,
179
                $this->elasticsearch,
180
                $searchBody
181
            );
182
        }
183
184
        $model = $builder->model;
185
        $indexName = $builder->index ?: $model->searchableAs();
186
        $params = new SearchParams($indexName, $searchBody->toArray());
0 ignored issues
show
Bug introduced by
It seems like $indexName can also be of type Illuminate\Database\Eloquent\Builder; however, parameter $index of Matchish\ScoutElasticSea...s\Search::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

186
        $params = new SearchParams(/** @scrutinizer ignore-type */ $indexName, $searchBody->toArray());
Loading history...
187
188
        return $this->elasticsearch->search($params->toArray());
189
    }
190
}
191