Skip to content

Commit

Permalink
Pass keys to Collection::unique callback (#16883)
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber authored and taylorotwell committed Dec 20, 2016
1 parent 43c81da commit dd778cb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
6 changes: 3 additions & 3 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1142,12 +1142,12 @@ public function unique($key = null, $strict = false)
return new static(array_unique($this->items, SORT_REGULAR));
}

$key = $this->valueRetriever($key);
$callback = $this->valueRetriever($key);

$exists = [];

return $this->reject(function ($item) use ($key, $strict, &$exists) {
if (in_array($id = $key($item), $exists, $strict)) {
return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {
if (in_array($id = $callback($item, $key), $exists, $strict)) {
return true;
}

Expand Down
16 changes: 13 additions & 3 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -556,9 +556,12 @@ public function testUnique()
public function testUniqueWithCallback()
{
$c = new Collection([
1 => ['id' => 1, 'first' => 'Taylor', 'last' => 'Otwell'], 2 => ['id' => 2, 'first' => 'Taylor', 'last' => 'Otwell'],
3 => ['id' => 3, 'first' => 'Abigail', 'last' => 'Otwell'], 4 => ['id' => 4, 'first' => 'Abigail', 'last' => 'Otwell'],
5 => ['id' => 5, 'first' => 'Taylor', 'last' => 'Swift'], 6 => ['id' => 6, 'first' => 'Taylor', 'last' => 'Swift'],
1 => ['id' => 1, 'first' => 'Taylor', 'last' => 'Otwell'],
2 => ['id' => 2, 'first' => 'Taylor', 'last' => 'Otwell'],
3 => ['id' => 3, 'first' => 'Abigail', 'last' => 'Otwell'],
4 => ['id' => 4, 'first' => 'Abigail', 'last' => 'Otwell'],
5 => ['id' => 5, 'first' => 'Taylor', 'last' => 'Swift'],
6 => ['id' => 6, 'first' => 'Taylor', 'last' => 'Swift'],
]);

$this->assertEquals([
Expand All @@ -573,6 +576,13 @@ public function testUniqueWithCallback()
], $c->unique(function ($item) {
return $item['first'].$item['last'];
})->all());

$this->assertEquals([
1 => ['id' => 1, 'first' => 'Taylor', 'last' => 'Otwell'],
2 => ['id' => 2, 'first' => 'Taylor', 'last' => 'Otwell'],
], $c->unique(function ($item, $key) {
return $key % 2;
})->all());
}

public function testUniqueStrict()
Expand Down

0 comments on commit dd778cb

Please sign in to comment.