Sync::handle()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 0
dl 0
loc 18
ccs 10
cts 10
cp 1
crap 4
rs 9.9332
c 0
b 0
f 0
1
<?php
2
namespace Triadev\Leopard\Console\Commands\Index;
3
4
use Illuminate\Console\Command;
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
use Triadev\Leopard\Business\Helper\IsModelSearchable;
8
use Triadev\Leopard\Facade\Leopard;
9
use Triadev\Leopard\Searchable;
10
11
class Sync extends Command
12
{
13
    const MAX_CHUNK_SIZE = 1000;
14
    
15
    use IsModelSearchable;
16
    
17
    /**
18
     * The console command name.
19
     *
20
     * @var string
21
     */
22
    protected $signature = 'triadev:index:sync {--index=}';
23
    
24
    /**
25
     * The console command description.
26
     *
27
     * @var string
28
     */
29
    protected $description = 'Sync the elasticsearch index with persist data.';
30
    
31
    /**
32
     * Execute the console command.
33
     */
34 2
    public function handle()
35
    {
36 2
        $index = $this->option('index') ?: Leopard::getEsDefaultIndex();
37
        
38 2
        if (!Leopard::getEsClient()->indices()->exists(['index' => $index])) {
39 1
            $this->error(sprintf('The index does not exist: %s', $index));
40 1
            return;
41
        }
42
        
43 1
        $chunkSize = $this->getChunkSize();
44
        
45 1
        foreach ($this->getModelsToSync($index) as $modelClass => $model) {
46 1
            $this->line(sprintf('Sync index with model: %s', $modelClass));
47
            
48
            $model::chunk($chunkSize, function ($models) {
49
                /** @var Collection $models */
50 1
                Leopard::repository()->bulkSave($models);
51 1
                $this->line(sprintf('Indexing a chunk of %s documents ...', count($models)));
52 1
            });
53
        }
54 1
    }
55
    
56
    /**
57
     * @return int
58
     */
59 1
    private function getChunkSize() : int
60
    {
61 1
        $chunkSize = config('leopard.sync.chunkSize');
62
        
63 1
        return $chunkSize > self::MAX_CHUNK_SIZE ? self::MAX_CHUNK_SIZE : $chunkSize;
64
    }
65
    
66
    /**
67
     * @param string $index
68
     * @return Model|Searchable[]
69
     */
70 1
    private function getModelsToSync(string $index) : array
71
    {
72 1
        $models = [];
73
    
74 1
        foreach (config(sprintf('leopard.sync.models.%s', $index), []) as $modelClass) {
75
            /** @var Model|Searchable $model */
76 1
            $model = new $modelClass();
77 1
            if ($model instanceof Model) {
78 1
                $this->isModelSearchable($model);
79
                
80 1
                $models[$modelClass] = $model;
81
            }
82
        }
83
        
84 1
        return $models;
85
    }
86
}
87