Skip to content
This repository has been archived by the owner on Feb 5, 2023. It is now read-only.

Commit

Permalink
Fix sort results (#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
CasperLaiTW authored Sep 21, 2020
1 parent 9627c41 commit 6389e13
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Engines/ElasticsearchEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,16 @@ public function map(Builder $builder, $results, $model)

$keys = collect($results['hits']['hits'])->pluck('_id')->values()->all();

$modelIdPositions = array_flip($keys);

return $model->getScoutModelsByIds(
$builder,
$keys
)->filter(function ($model) use ($keys) {
return in_array($model->getScoutKey(), $keys);
});
})->sortBy(function ($model) use ($modelIdPositions) {
return $modelIdPositions[$model->getScoutKey()];
})->values();
}

/**
Expand Down
36 changes: 36 additions & 0 deletions tests/ElasticsearchEngineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,40 @@ public function test_map_correctly_maps_results_to_models()

$this->assertEquals(1, count($results));
}

public function test_map_correctly_maps_sort_results()
{
/** @var Client|MockInterface $client */
$client = Mockery::mock(Client::class);
$engine = new ElasticsearchEngine($client);

/** @var Builder|MockInterface $builder */
$builder = Mockery::mock(Builder::class);

/** @var Model|MockInterface $model */
$secondModel = Mockery::mock(Model::class);
$secondModel->shouldReceive('getScoutKey')->andReturn('2');

/** @var Model|MockInterface $model */
$model = Mockery::mock(Model::class);
$model->shouldReceive('getScoutKey')->andReturn('1');
$model->shouldReceive('getScoutModelsByIds')->once()->with($builder, ['2', '1'])->andReturn($models = Collection::make([$model, $secondModel]));
$model->shouldReceive('newCollection')->andReturn($models);

$results = $engine->map($builder, [
'hits' => [
'total' => '2',
'hits' => [
[
'_id' => '2'
],
[
'_id' => '1'
]
]
]
], $model);
$this->assertEquals($secondModel, $results[0]);
$this->assertEquals($model, $results[1]);
}
}

0 comments on commit 6389e13

Please sign in to comment.