diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 78ae4b6ef5f1..8e236b4306cd 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1529,6 +1529,28 @@ public function reject($callback = true) }); } + /** + * Replace the collection items with the given items. + * + * @param mixed $items + * @return static + */ + public function replace($items) + { + return new static(array_replace($this->items, $this->getArrayableItems($items))); + } + + /** + * Recursively replace the collection items with the given items. + * + * @param mixed $items + * @return static + */ + public function replaceRecursive($items) + { + return new static(array_replace_recursive($this->items, $this->getArrayableItems($items))); + } + /** * Reverse items order. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index becea14de46e..467f5e89104c 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -687,6 +687,48 @@ public function testMergeRecursiveCollection() ); } + public function testReplaceNull() + { + $c = new Collection(['a', 'b', 'c']); + $this->assertEquals(['a', 'b', 'c'], $c->replace(null)->all()); + } + + public function testReplaceArray() + { + $c = new Collection(['a', 'b', 'c']); + $this->assertEquals(['a', 'd', 'e'], $c->replace([1 => 'd', 2 => 'e'])->all()); + } + + public function testReplaceCollection() + { + $c = new Collection(['a', 'b', 'c']); + $this->assertEquals( + ['a', 'd', 'e'], + $c->replace(new Collection([1 => 'd', 2 => 'e']))->all() + ); + } + + public function testReplaceRecursiveNull() + { + $c = new Collection(['a', 'b', ['c', 'd']]); + $this->assertEquals(['a', 'b', ['c', 'd']], $c->replaceRecursive(null)->all()); + } + + public function testReplaceRecursiveArray() + { + $c = new Collection(['a', 'b', ['c', 'd']]); + $this->assertEquals(['z', 'b', ['c', 'e']], $c->replaceRecursive(['z', 2 => [1 => 'e']])->all()); + } + + public function testReplaceRecursiveCollection() + { + $c = new Collection(['a', 'b', ['c', 'd']]); + $this->assertEquals( + ['z', 'b', ['c', 'e']], + $c->replaceRecursive(new Collection(['z', 2 => [1 => 'e']]))->all() + ); + } + public function testUnionNull() { $c = new Collection(['name' => 'Hello']);