Skip to content

Commit

Permalink
[5.3] Add uniqueStrict method (laravel#14661)
Browse files Browse the repository at this point in the history
* [5.3] Add uniqueStrict method

* Style fix
  • Loading branch information
mnabialek authored and tillkruss committed Aug 30, 2016
1 parent 43da826 commit 5a5eba6
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,31 @@ public function unique($key = null)
});
}

/**
* Return only unique items from the collection array using strict comparison.
*
* @param string|callable|null $key
* @return static
*/
public function uniqueStrict($key = null)
{
if (is_null($key)) {
return new static(array_unique($this->items, SORT_REGULAR));
}

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

$exists = [];

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

$exists[] = $id;
});
}

/**
* Reset the keys on the underlying array.
*
Expand Down
29 changes: 29 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,35 @@ public function testUniqueWithCallback()
})->all());
}

public function testUniqueStrict()
{
$c = new Collection([
[
'id' => '0',
'name' => 'zero',
],
[
'id' => '00',
'name' => 'double zero',
],
[
'id' => '0',
'name' => 'again zero',
],
]);

$this->assertEquals([
[
'id' => '0',
'name' => 'zero',
],
[
'id' => '00',
'name' => 'double zero',
],
], $c->uniqueStrict('id')->all());
}

public function testCollapse()
{
$data = new Collection([[$object1 = new StdClass], [$object2 = new StdClass]]);
Expand Down

0 comments on commit 5a5eba6

Please sign in to comment.