Skip to content
This repository was archived by the owner on Jun 26, 2025. It is now read-only.

Commit d681e91

Browse files
committed
Merge pull request #1 from 2dotstwice/feature/III-484
III-484: Add contains method.
2 parents 2323504 + 87b27be commit d681e91

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/AbstractCollection.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,23 @@ public function withoutKey($key)
6767
return $copy;
6868
}
6969

70+
/**
71+
* @inheritdoc
72+
*/
73+
public function contains($item)
74+
{
75+
$this->guardObjectType($item);
76+
77+
$filtered = array_filter(
78+
$this->items,
79+
function ($itemToCompare) use ($item) {
80+
return ($item == $itemToCompare);
81+
}
82+
);
83+
84+
return !empty($filtered);
85+
}
86+
7087
/**
7188
* @inheritdoc
7289
*/

src/CollectionInterface.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,17 @@ public function without($item);
6161
*/
6262
public function withoutKey($key);
6363

64+
/**
65+
* @param mixed $item
66+
* Item to check if it's present in the collection.
67+
*
68+
* @return bool
69+
*
70+
* @throws \InvalidArgumentException
71+
* When the provided item is of an incorrect type.
72+
*/
73+
public function contains($item);
74+
6475
/**
6576
* @param string $key
6677
* Key to find the corresponding item for.

tests/CollectionTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,28 @@ public function it_throws_an_exception_when_removing_by_unknown_key()
180180
$collection->withoutKey('foo3');
181181
}
182182

183+
/**
184+
* @test
185+
*/
186+
public function it_can_check_if_the_collection_contains_a_given_item()
187+
{
188+
$collection = (new FooCollection())
189+
->withKey('foo1', $this->foo1);
190+
191+
$this->assertTrue($collection->contains($this->foo1));
192+
}
193+
194+
/**
195+
* @test
196+
*/
197+
public function it_can_check_if_the_collection_does_not_contain_a_given_item()
198+
{
199+
$collection = (new FooCollection())
200+
->withKey('foo1', $this->foo1);
201+
202+
$this->assertFalse($collection->contains($this->foo2));
203+
}
204+
183205
/**
184206
* @test
185207
*/

0 commit comments

Comments
 (0)