From 7a42ba6d82aa55740d7bcf5662692dd3421ffeec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Nabia=C5=82ek?= Date: Sun, 7 Aug 2016 19:37:16 +0200 Subject: [PATCH] [5.3] Add containsStrict method (#14657) * Add containsStrict method * Fix code style --- src/Illuminate/Support/Collection.php | 22 ++++++++++++++++++ tests/Support/SupportCollectionTest.php | 30 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index a4714336aa14..ea34c1746964 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -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. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 52069e8bb24c..60acb3a90832 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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]]);