1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Matchish\ScoutElasticSearch\ElasticSearch; |
4
|
|
|
|
5
|
|
|
use IteratorAggregate; |
6
|
|
|
use Laravel\Scout\Builder; |
7
|
|
|
use Laravel\Scout\Searchable; |
8
|
|
|
use Traversable; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @internal |
12
|
|
|
*/ |
13
|
|
|
final class EloquentHitsIteratorAggregate implements IteratorAggregate |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var array |
17
|
|
|
*/ |
18
|
|
|
private $results; |
19
|
|
|
/** |
20
|
|
|
* @var callable|null |
21
|
|
|
*/ |
22
|
|
|
private $callback; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param array $results |
26
|
|
|
* @param callable|null $callback |
27
|
|
|
*/ |
28
|
|
|
public function __construct(array $results, callable $callback = null) |
29
|
|
|
{ |
30
|
|
|
$this->results = $results; |
31
|
|
|
$this->callback = $callback; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Retrieve an external iterator. |
36
|
|
|
* @link https://php.net/manual/en/iteratoraggregate.getiterator.php |
37
|
|
|
* @return Traversable An instance of an object implementing <b>Iterator</b> or |
38
|
|
|
* <b>Traversable</b> |
39
|
|
|
* @since 5.0.0 |
40
|
|
|
*/ |
41
|
|
|
public function getIterator() |
42
|
|
|
{ |
43
|
|
|
$hits = collect(); |
44
|
|
|
if ($this->results['hits']['total']) { |
45
|
|
|
$hits = $this->results['hits']['hits']; |
46
|
|
|
$models = collect($hits)->groupBy('_source.__class_name') |
47
|
|
|
->map(function ($results, $class) { |
48
|
|
|
$model = new $class; |
49
|
|
|
$builder = new Builder($model, ''); |
50
|
|
|
if (! empty($this->callback)) { |
51
|
|
|
$builder->query($this->callback); |
52
|
|
|
} |
53
|
|
|
/* @var Searchable $model */ |
54
|
|
|
return $models = $model->getScoutModelsByIds( |
|
|
|
|
55
|
|
|
$builder, $results->pluck('_id')->all() |
56
|
|
|
); |
57
|
|
|
}) |
58
|
|
|
->flatten()->keyBy(function ($model) { |
59
|
|
|
return get_class($model).'::'.$model->getScoutKey(); |
60
|
|
|
}); |
61
|
|
|
$hits = collect($hits)->map(function ($hit) use ($models) { |
62
|
|
|
$key = $hit['_source']['__class_name'].'::'.$hit['_id']; |
63
|
|
|
|
64
|
|
|
return isset($models[$key]) ? $models[$key] : null; |
65
|
|
|
})->filter()->all(); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return new \ArrayIterator((array) $hits); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|