diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 54689cb840c2..526086378ba1 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1659,4 +1659,28 @@ public function __get($key) return new HigherOrderCollectionProxy($this, $key); } + + /** + * Replaces elements from passed arrays into the collection + * + * @param mixed $items + * @return static + * @see http://php.net/manual/en/function.array-replace-recursive.php + */ + public function replace($items) + { + return new static(array_replace($this->items, $this->getArrayableItems($items))); + } + + /** + * Replaces elements from passed arrays into the collection recursively + * + * @param mixed $items + * @return static + * @see http://php.net/manual/en/function.array-replace-recursive.php + */ + public function replaceRecursively($items) + { + return new static(array_replace_recursive($this->items, $this->getArrayableItems($items))); + } } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 5a40b19ecae9..9613f62c9237 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -2153,6 +2153,21 @@ public function testUnlessDefault() $this->assertSame(['michael', 'tom', 'taylor'], $collection->toArray()); } + + public function testReplace() + { + $c = new Collection(['foo' => 'x', 'bar' => 'y']); + $this->assertEquals(['foo' => 'f', 'bar' => 'y', 'baz' => 'z'], $c->replace(new Collection(['foo' => 'f', 'baz' => 'z']))->all()); + } + + public function testReplaceCollectionRecursively() + { + $base = ['citrus' => ["orange"], 'berries' => ["blackberry", "raspberry"],]; + $replacements = ['citrus' => ['pineapple'], 'berries' => ['blueberry']]; + $expect = ['citrus' => ['pineapple'], 'berries' => ['blueberry', 'raspberry']]; + $c = new Collection($base); + $this->assertEquals($expect, $c->replaceRecursively(new Collection($replacements))->all()); + } } class TestSupportCollectionHigherOrderItem