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
|
|
|
return collect(range(1, $totalChunks))->map(function ($page) use ($chunkSize) { |
48
|
13 |
|
$chunkScope = new PageScope($page, $chunkSize); |
49
|
13 |
|
return new static($this->className, array_merge($this->scopes, [$chunkScope])); |
50
|
13 |
|
}); |
51
|
|
|
} else { |
52
|
13 |
|
return collect(); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @return mixed |
58
|
|
|
*/ |
59
|
28 |
|
private function model() |
60
|
|
|
{ |
61
|
28 |
|
return new $this->className; |
62
|
|
|
} |
63
|
|
|
|
64
|
23 |
|
private function newQuery() |
65
|
|
|
{ |
66
|
23 |
|
$query = $this->model()->newQuery(); |
67
|
23 |
|
$softDelete = config('scout.soft_delete', false); |
68
|
|
|
$query |
69
|
|
|
->when($softDelete, function ($query) { |
70
|
2 |
|
return $query->withTrashed(); |
71
|
23 |
|
}) |
72
|
23 |
|
->orderBy($this->model()->getKeyName()); |
73
|
23 |
|
$scopes = $this->scopes; |
74
|
|
|
|
75
|
|
|
return collect($scopes)->reduce(function ($instance, $scope) { |
76
|
13 |
|
$instance->withGlobalScope(get_class($scope), $scope); |
77
|
|
|
|
78
|
13 |
|
return $instance; |
79
|
23 |
|
}, $query); |
80
|
|
|
} |
81
|
|
|
|
82
|
17 |
|
public function get() |
83
|
|
|
{ |
84
|
17 |
|
return $this->newQuery()->get(); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|