From 4fc0ea5389424876bdbd858bbb3df97e9adc0b28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateus=20Guimar=C3=A3es?= Date: Mon, 22 May 2017 12:28:01 -0300 Subject: [PATCH] add intersect by keys method to collections --- src/Illuminate/Support/Collection.php | 11 +++++++++++ tests/Support/SupportCollectionTest.php | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index ad3d258f0656..cb5868218160 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -658,6 +658,17 @@ public function intersect($items) return new static(array_intersect($this->items, $this->getArrayableItems($items))); } + /** + * Intersect the collection with the given items by key + * + * @param mixed $items + * @return static + */ + public function intersectByKeys($items) + { + return new static(array_intersect_key($this->items, $this->getArrayableItems($items))); + } + /** * Determine if the collection is empty or not. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index f02d55053606..59fdafbb8f09 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -570,6 +570,18 @@ public function testIntersectCollection() $this->assertEquals(['first_word' => 'Hello'], $c->intersect(new Collection(['first_world' => 'Hello', 'last_word' => 'World']))->all()); } + public function testIntersectByKeysNull() + { + $c = new Collection(['name' => 'Mateus', 'age' => 18]); + $this->assertEquals([], $c->intersectByKeys(null)->all()); + } + + public function testIntersectByKeys() + { + $c = new Collection(['name' => 'Mateus', 'age' => 18]); + $this->assertEquals(['name' => 'Mateus'], $c->intersectByKeys(new Collection(['name' => 'Mateus', 'surname' => 'Guimaraes']))->all()); + } + public function testUnique() { $c = new Collection(['Hello', 'World', 'World']);