Skip to content

Commit

Permalink
[5.3] Add containsStrict method (#14657)
Browse files Browse the repository at this point in the history
* Add containsStrict method

* Fix code style
  • Loading branch information
mnabialek authored and taylorotwell committed Aug 7, 2016
1 parent 1873943 commit 1d39e52
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,28 @@ public function contains($key, $value = null)
return in_array($key, $this->items);
}

/**
* Determine if an item exists in the collection using strict comparison.
*
* @param mixed $key
* @param mixed $value
* @return bool
*/
public function containsStrict($key, $value = null)
{
if (func_num_args() == 2) {
return $this->contains(function ($item) use ($key, $value) {
return data_get($item, $key) === $value;
});
}

if ($this->useAsCallable($key)) {
return ! is_null($this->first($key));
}

return in_array($key, $this->items, true);
}

/**
* Get the items in the collection that are not present in the given items.
*
Expand Down
30 changes: 30 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,36 @@ public function testContains()
$this->assertFalse($c->contains('foo'));
}

public function testContainsStrict()
{
$c = new Collection([1, 3, 5, '02']);

$this->assertTrue($c->containsStrict(1));
$this->assertFalse($c->containsStrict(2));
$this->assertTrue($c->containsStrict('02'));
$this->assertTrue($c->containsStrict(function ($value) {
return $value < 5;
}));
$this->assertFalse($c->containsStrict(function ($value) {
return $value > 5;
}));

$c = new Collection([['v' => 1], ['v' => 3], ['v' => '04'], ['v' => 5]]);

$this->assertTrue($c->containsStrict('v', 1));
$this->assertFalse($c->containsStrict('v', 2));
$this->assertFalse($c->containsStrict('v', 4));
$this->assertTrue($c->containsStrict('v', '04'));

$c = new Collection(['date', 'class', (object) ['foo' => 50], '']);

$this->assertTrue($c->containsStrict('date'));
$this->assertTrue($c->containsStrict('class'));
$this->assertFalse($c->containsStrict('foo'));
$this->assertFalse($c->containsStrict(null));
$this->assertTrue($c->containsStrict(''));
}

public function testGettingSumFromCollection()
{
$c = new Collection([(object) ['foo' => 50], (object) ['foo' => 50]]);
Expand Down

0 comments on commit 1d39e52

Please sign in to comment.