Test Failed
Push — master ( 131fc3...3e7ec2 )
by Serhii
18:02 queued 12:24
created

EloquentHitsIteratorAggregate   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 23
c 3
b 1
f 0
dl 0
loc 56
ccs 0
cts 25
cp 0
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getIterator() 0 28 4
A __construct() 0 4 1
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(
0 ignored issues
show
Unused Code introduced by
The assignment to $models is dead and can be removed.
Loading history...
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