Skip to content

Commit

Permalink
Merge pull request #16564 from fernandobandeira/master
Browse files Browse the repository at this point in the history
[5.4] refactoring mapWithKeys
  • Loading branch information
taylorotwell authored Nov 28, 2016
2 parents 872ca77 + 0c5dcb9 commit 67e84f1
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,17 @@ public function map(callable $callback)
*/
public function mapWithKeys(callable $callback)
{
return $this->flatMap($callback);
$result = [];

foreach ($this->items as $key => $value) {
$assoc = $callback($value, $key);

foreach ($assoc as $mapKey => $mapValue) {
$result[$mapKey] = $mapValue;
}
}

return new static($result);
}

/**
Expand Down
55 changes: 55 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,61 @@ public function testMapWithKeys()
);
}

public function testMapWithKeysIntegerKeys()
{
$data = new Collection([
['id' => 1, 'name' => 'A'],
['id' => 3, 'name' => 'B'],
['id' => 2, 'name' => 'C'],
]);
$data = $data->mapWithKeys(function ($item) {
return [$item['id'] => $item];
});
$this->assertSame(
[1, 3, 2],
$data->keys()->all()
);
}

public function testMapWithKeysMultipleRows()
{
$data = new Collection([
['id' => 1, 'name' => 'A'],
['id' => 2, 'name' => 'B'],
['id' => 3, 'name' => 'C'],
]);
$data = $data->mapWithKeys(function ($item) {
return [$item['id'] => $item['name'], $item['name'] => $item['id']];
});
$this->assertSame(
[
1 => 'A',
'A' => 1,
2 => 'B',
'B' => 2,
3 => 'C',
'C' => 3,
],
$data->all()
);
}

public function testMapWithKeysCallbackKey()
{
$data = new Collection([
3 => ['id' => 1, 'name' => 'A'],
5 => ['id' => 3, 'name' => 'B'],
4 => ['id' => 2, 'name' => 'C'],
]);
$data = $data->mapWithKeys(function ($item, $key) {
return [$key => $item['id']];
});
$this->assertSame(
[3, 5, 4],
$data->keys()->all()
);
}

public function testTransform()
{
$data = new Collection(['first' => 'taylor', 'last' => 'otwell']);
Expand Down

0 comments on commit 67e84f1

Please sign in to comment.