Skip to content

Commit

Permalink
Add keys to eachSpread and mapSpread callback (#20723)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastiandedeyne authored and taylorotwell committed Aug 24, 2017
1 parent f8db604 commit 2f2886e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,9 @@ public function each(callable $callback)
*/
public function eachSpread(callable $callback)
{
return $this->each(function ($chunk) use ($callback) {
return $this->each(function ($chunk, $key) use ($callback) {
array_push($chunk, $key);

return $callback(...$chunk);
});
}
Expand Down Expand Up @@ -837,7 +839,9 @@ public function map(callable $callback)
*/
public function mapSpread(callable $callback)
{
return $this->map(function ($chunk) use ($callback) {
return $this->map(function ($chunk, $key) use ($callback) {
array_push($chunk, $key);

return $callback(...$chunk);
});
}
Expand Down
11 changes: 11 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,12 @@ public function testEachSpread()
return false;
});
$this->assertEquals([[1, 'a']], $result);

$result = [];
$c->eachSpread(function ($number, $character, $key) use (&$result) {
$result[] = [$number, $character, $key];
});
$this->assertEquals([[1, 'a', 0], [2, 'b', 1]], $result);
}

public function testIntersectNull()
Expand Down Expand Up @@ -1201,6 +1207,11 @@ public function testMapSpread()
return "{$number}-{$character}";
});
$this->assertEquals(['1-a', '2-b'], $result->all());

$result = $c->mapSpread(function ($number, $character, $key) use (&$result) {
return "{$number}-{$character}-{$key}";
});
$this->assertEquals(['1-a-0', '2-b-1'], $result->all());
}

public function testFlatMap()
Expand Down

2 comments on commit 2f2886e

@mkarnicki
Copy link

Choose a reason for hiding this comment

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

Hi @sebastiandedeyne ,

Please see:

>>> $a = collect([1, 2]);
=> Illuminate\Support\Collection {#785
     all: [
       1,
       2,
     ],
   }
>>> $b = collect(['a', 'b']);
=> Illuminate\Support\Collection {#769
     all: [
       "a",
       "b",
     ],
   }
>>> $a->zip($b)->eachSpread(function ($x, $y, $key) { echo $x.$y; });
PHP warning:  array_push() expects parameter 1 to be array, object given

Can you please advise? FTR this used to work before adding array_push($chunk, $key);

Thanks.

@sebastiandedeyne
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sorry about that, just submitted a PR that fixes it! #20962

Please sign in to comment.