Skip to content
This repository has been archived by the owner on Nov 4, 2021. It is now read-only.

Commit

Permalink
Ensure Eloquent\Collection returned after filtering (#354)
Browse files Browse the repository at this point in the history
* Ensure Eloquent\Collection returned after filtering

* Add test to assert Database\Collection returned
  • Loading branch information
gtjamesa authored Apr 2, 2020
1 parent cdd6a4b commit 05d3fc6
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/ElasticEngine.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ public function map(Builder $builder, $results, $model)
->get($columns)
->keyBy($scoutKeyName);

return Collection::make($results['hits']['hits'])
$values = Collection::make($results['hits']['hits'])
->map(function ($hit) use ($models) {
$id = $hit['_id'];

Expand All @@ -331,6 +331,8 @@ public function map(Builder $builder, $results, $model)
})
->filter()
->values();

return $values instanceof Collection ? $values : Collection::make($values);
}

/**
Expand Down
77 changes: 77 additions & 0 deletions tests/ElasticEngineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace ScoutElastic\Tests;

use Illuminate\Database\Eloquent\Collection;
use ScoutElastic\Builders\FilterBuilder;
use ScoutElastic\Builders\SearchBuilder;
use ScoutElastic\ElasticEngine;
Expand Down Expand Up @@ -440,6 +441,82 @@ public function testMapWithTrashed()
);
}

public function testMapReturnDatabaseCollection()
{
$this->markTestSkipped();

$results = [
'hits' => [
'total' => 2,
'hits' => [
[
'_id' => 1,
'_source' => [
'title' => 'foo',
],
],
[
'_id' => 2,
'_source' => [
'title' => 'bar',
],
],
],
],
];

$model = $this->mockModel([
'key' => 2,
'methods' => [
'usesSoftDelete',
'newQuery',
'whereIn',
'get',
'keyBy',
],
]);

$model
->method('usesSoftDelete')
->willReturn(false);

$model
->method('newQuery')
->willReturn($model);

$model
->method('whereIn')
->willReturn($model);

$model
->method('get')
->willReturn($model);

// The mocked `newQuery` chain will return an array of a single model (ID: 2)
// When mapping `$results['hits']['hits']`, the first item (ID: 1) will return null in `Collection::map()`
// This will result in `Collection::toBase()` being called, converting to a `Support\Collection`
$model
->method('keyBy')
->willReturn([
2 => $model,
]);

$builder = $this
->getMockBuilder(FilterBuilder::class)
->disableOriginalConstructor()
->getMock();

$collection = $this->engine->map($builder, $results, $model);

$this->assertSame(
[$model],
$collection->all()
);

// Assert that an `Eloquent\Database\Collection` is returned
$this->assertInstanceOf(Collection::class, $collection);
}

public function testGetTotalCount()
{
$results = [
Expand Down

0 comments on commit 05d3fc6

Please sign in to comment.