Passed
Pull Request — master (#129)
by Serhii
13:55
created

ElasticSearchEngine::flush()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 9
ccs 8
cts 8
cp 1
crap 2
rs 10
c 4
b 0
f 0
1
<?php
2
3
namespace Matchish\ScoutElasticSearch\Engines;
4
5
use Elasticsearch\Common\Exceptions\ServerErrorResponseException;
6
use Illuminate\Database\Eloquent\Collection;
7
use Laravel\Scout\Builder as BaseBuilder;
8
use Laravel\Scout\Engines\Engine;
9
use Matchish\ScoutElasticSearch\ElasticSearch\HitsIteratorAggregate;
10
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Bulk;
11
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Indices\Refresh;
12
use Matchish\ScoutElasticSearch\ElasticSearch\Params\Search as SearchParams;
13
use Matchish\ScoutElasticSearch\ElasticSearch\SearchFactory;
14
use Matchish\ScoutElasticSearch\ElasticSearch\SearchResults;
15
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
16
use ONGR\ElasticsearchDSL\Search;
17
18
final class ElasticSearchEngine extends Engine
19
{
20
    /**
21
     * The ElasticSearch client.
22
     *
23
     * @var \Elasticsearch\Client
24
     */
25
    protected $elasticsearch;
26
27
    /**
28
     * Create a new engine instance.
29
     *
30
     * @param \Elasticsearch\Client $elasticsearch
31
     * @return void
32
     */
33 27
    public function __construct(\Elasticsearch\Client $elasticsearch)
34
    {
35 27
        $this->elasticsearch = $elasticsearch;
36 27
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41 20
    public function update($models)
42
    {
43 20
        $params = new Bulk();
44 20
        $params->index($models);
45 20
        $response = $this->elasticsearch->bulk($params->toArray());
46 20
        if (array_key_exists('errors', $response) && $response['errors']) {
47 1
            $error = new ServerErrorResponseException(json_encode($response, JSON_PRETTY_PRINT));
48 1
            throw new \Exception('Bulk update error', $error->getCode(), $error);
49
        }
50 19
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 1
    public function delete($models)
56
    {
57 1
        $params = new Bulk();
58 1
        $params->delete($models);
59 1
        $this->elasticsearch->bulk($params->toArray());
60 1
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 2
    public function flush($model)
66
    {
67 2
        $indexName = $model->searchableAs();
68 2
        $exist = $this->elasticsearch->indices()->exists(['index' => $indexName]);
69 2
        if ($exist) {
70 2
            $body = (new Search())->addQuery(new MatchAllQuery())->toArray();
71 2
            $params = new SearchParams($indexName, $body);
72 2
            $this->elasticsearch->deleteByQuery($params->toArray());
73 2
            $this->elasticsearch->indices()->refresh((new Refresh($indexName))->toArray());
74
        }
75 2
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 6
    public function search(BaseBuilder $builder)
81
    {
82 6
        return $this->performSearch($builder, []);
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 1
    public function paginate(BaseBuilder $builder, $perPage, $page)
89
    {
90 1
        return $this->performSearch($builder, [
91 1
            'from' => ($page - 1) * $perPage,
92 1
            'size' => $perPage,
93
        ]);
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 1
    public function mapIds($results)
100
    {
101 1
        return collect($results['hits']['hits'])->pluck('_id');
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107 7
    public function map(BaseBuilder $builder, $results, $model)
108
    {
109 7
        $hits = app()->makeWith(
110 7
            HitsIteratorAggregate::class,
111
            [
112 7
                'results'  => $results,
113 7
                'callback' => $builder->queryCallback,
114
            ]
115
        );
116
117 7
        return new Collection($hits);
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 1
    public function getTotalCount($results)
124
    {
125 1
        return $results['hits']['total']['value'];
126
    }
127
128
    /**
129
     * @param BaseBuilder $builder
130
     * @param array $options
131
     * @return SearchResults|mixed
132
     */
133 7
    private function performSearch(BaseBuilder $builder, $options = [])
134
    {
135 7
        $searchBody = SearchFactory::create($builder, $options);
136 7
        if ($builder->callback) {
137
            /** @var callable */
138 2
            $callback = $builder->callback;
139
140 2
            return call_user_func(
141 2
                $callback,
142 2
                $this->elasticsearch,
143
                $searchBody
144
            );
145
        }
146
147 5
        $model = $builder->model;
148 5
        $indexName = $builder->index ?: $model->searchableAs();
149 5
        $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

149
        $params = new SearchParams(/** @scrutinizer ignore-type */ $indexName, $searchBody->toArray());
Loading history...
150
151 5
        return $this->elasticsearch->search($params->toArray());
152
    }
153
}
154