Passed
Pull Request — master (#33)
by Serhii
06:45 queued 01:44
created

DefaultImportSource::chunked()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 10
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 2
rs 9.9332
1
<?php
2
3
namespace Matchish\ScoutElasticSearch\Searchable;
4
5
use Matchish\ScoutElasticSearch\Database\Scopes\PageScope;
6
7
final class DefaultImportSource implements ImportSource
8
{
9
    const DEFAULT_CHUNK_SIZE = 500;
10
11
    private $className;
12
    private $scopes;
13
14
    /**
15
     * DefaultImportSource constructor.
16
     * @param string $className
17
     * @param array $scopes
18
     */
19 28
    public function __construct(string $className, array $scopes = [])
20
    {
21 28
        $this->className = $className;
22 28
        $this->scopes = $scopes;
23 28
    }
24
25 12
    public function syncWithSearchUsingQueue()
26
    {
27 12
        return $this->model()->syncWithSearchUsingQueue();
28
    }
29
30 12
    public function syncWithSearchUsing()
31
    {
32 12
        return $this->model()->syncWithSearchUsing();
33
    }
34
35 20
    public function searchableAs(): string
36
    {
37 20
        return $this->model()->searchableAs();
38
    }
39
40 18
    public function chunked()
41
    {
42 18
        $query = $this->newQuery();
43 18
        $totalSearchables = $query->count();
44 18
        if ($totalSearchables) {
45 13
            $chunkSize = (int) config('scout.chunk.searchable', self::DEFAULT_CHUNK_SIZE);
46 13
            $totalChunks = (int) ceil($totalSearchables / $chunkSize);
47
48
            return collect(range(1, $totalChunks))->map(function ($page) use ($chunkSize) {
49 13
                $chunkScope = new PageScope($page, $chunkSize);
50
51 13
                return new static($this->className, array_merge($this->scopes, [$chunkScope]));
52 13
            });
53
        } else {
54 13
            return collect();
55
        }
56
    }
57
58
    /**
59
     * @return mixed
60
     */
61 28
    private function model()
62
    {
63 28
        return new $this->className;
64
    }
65
66 23
    private function newQuery()
67
    {
68 23
        $query = $this->model()->newQuery();
69 23
        $softDelete = config('scout.soft_delete', false);
70
        $query
71
            ->when($softDelete, function ($query) {
72 2
                return $query->withTrashed();
73 23
            })
74 23
            ->orderBy($this->model()->getKeyName());
75 23
        $scopes = $this->scopes;
76
77
        return collect($scopes)->reduce(function ($instance, $scope) {
78 13
            $instance->withGlobalScope(get_class($scope), $scope);
79
80 13
            return $instance;
81 23
        }, $query);
82
    }
83
84 17
    public function get()
85
    {
86 17
        return $this->newQuery()->get();
87
    }
88
}
89