Skip to content

Commit

Permalink
Turn the collection into a base collection if mapWithKeys loses models (
Browse files Browse the repository at this point in the history
  • Loading branch information
nuernbergerA committed Nov 9, 2020
1 parent 957232c commit 4f86853
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Illuminate/Database/Eloquent/Collection.php
Expand Up @@ -258,6 +258,23 @@ public function map(callable $callback)
}) ? $result->toBase() : $result;
}

/**
* Run an associative map over each of the items.
*
* The callback should return an associative array with a single key / value pair.
*
* @param callable $callback
* @return \Illuminate\Support\Collection|static
*/
public function mapWithKeys(callable $callback)
{
$result = parent::mapWithKeys($callback);

return $result->contains(function ($item) {
return ! $item instanceof Model;
}) ? $result->toBase() : $result;
}

/**
* Reload a fresh model instance from the database for all the entities.
*
Expand Down
29 changes: 29 additions & 0 deletions tests/Database/DatabaseEloquentCollectionTest.php
Expand Up @@ -228,6 +228,35 @@ public function testMappingToNonModelsReturnsABaseCollection()
$this->assertEquals(BaseCollection::class, get_class($c));
}

public function testMapWithKeys()
{
$one = m::mock(Model::class);
$two = m::mock(Model::class);

$c = new Collection([$one, $two]);

$key = 0;
$cAfterMap = $c->mapWithKeys(function ($item) use (&$key) {
return [$key++ => $item];
});

$this->assertEquals($c->all(), $cAfterMap->all());
$this->assertInstanceOf(Collection::class, $cAfterMap);
}

public function testMapWithKeysToNonModelsReturnsABaseCollection()
{
$one = m::mock(Model::class);
$two = m::mock(Model::class);

$key = 0;
$c = (new Collection([$one, $two]))->mapWithKeys(function ($item) use (&$key) {
return [$key++ => 'not-a-model'];
});

$this->assertEquals(BaseCollection::class, get_class($c));
}

public function testCollectionDiffsWithGivenCollection()
{
$one = m::mock(Model::class);
Expand Down

0 comments on commit 4f86853

Please sign in to comment.