Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.4] refactoring mapWithKeys #16564

Merged
merged 10 commits into from
Nov 28, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assertSame should be considered instead, as it does strict comparison thus also compares array orders. See Array Operators.

}

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