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 | 8 | public function __construct(array $results, callable $callback = null) |
|
29 | { |
||
30 | 8 | $this->results = $results; |
|
31 | 8 | $this->callback = $callback; |
|
32 | 8 | } |
|
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 | 7 | public function getIterator() |
|
42 | { |
||
43 | 7 | $hits = collect(); |
|
44 | 7 | if ($this->results['hits']['total']) { |
|
45 | 7 | $hits = $this->results['hits']['hits']; |
|
46 | 7 | $models = collect($hits)->groupBy('_source.__class_name') |
|
47 | ->map(function ($results, $class) { |
||
48 | 6 | $model = new $class; |
|
49 | 6 | $builder = new Builder($model, ''); |
|
50 | 6 | if (! empty($this->callback)) { |
|
51 | 1 | $builder->query($this->callback); |
|
52 | } |
||
53 | /* @var Searchable $model */ |
||
54 | 6 | return $models = $model->getScoutModelsByIds( |
|
0 ignored issues
–
show
Unused Code
introduced
by
![]() |
|||
55 | 6 | $builder, $results->pluck('_id')->all() |
|
56 | ); |
||
57 | 7 | }) |
|
58 | ->flatten()->keyBy(function ($model) { |
||
59 | 5 | return get_class($model).'::'.$model->getScoutKey(); |
|
60 | 7 | }); |
|
61 | $hits = collect($hits)->map(function ($hit) use ($models) { |
||
62 | 6 | $key = $hit['_source']['__class_name'].'::'.$hit['_id']; |
|
63 | |||
64 | 6 | return isset($models[$key]) ? $models[$key] : null; |
|
65 | 7 | })->filter()->all(); |
|
66 | } |
||
67 | |||
68 | 7 | return new \ArrayIterator((array) $hits); |
|
69 | } |
||
70 | } |
||
71 |