Completed
Pull Request — master (#22)
by Sergey
20:44 queued 05:45
created

Bulk   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 37
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B index() 0 29 5
1
<?php
2
3
namespace Isswp101\Persimmon\Helpers;
4
5
use Elasticsearch\Client;
6
use Exception;
7
use Isswp101\Persimmon\CollectionParser\ElasticsearchCollectionParser;
8
use Isswp101\Persimmon\Model\IElasticsearchModel;
9
10
class Bulk
11
{
12
    /**
13
     * @param Client $client
14
     * @param IElasticsearchModel[] $models
15
     * @param int $chunk
16
     */
17
    public static function index(Client $client, array $models, int $chunk = 1000): void
18
    {
19
        $i = 1;
20
        $params = ['body' => []];
21
        foreach ($models as $model) {
22
            try {
23
                $id = $model->getPrimaryKey();
24
            } catch (Exception $e) {
25
                $id = $i++;
26
            }
27
            $collection = new ElasticsearchCollectionParser($model::getCollection());
28
            $params['body'][] = [
29
                'index' => [
30
                    '_index' => $collection->getIndex(),
31
                    '_type' => $collection->getType(),
32
                    '_id' => $id
33
                ]
34
            ];
35
            $params['body'][] = $model->toArray();
36
            if ($i % $chunk == 0) {
37
                $responses = $client->bulk($params);
38
                $params = ['body' => []];
39
                unset($responses);
40
            }
41
        }
42
        if (!empty($params['body'])) {
43
            $client->bulk($params);
44
        }
45
    }
46
}