Skip to content

Commit

Permalink
Merge pull request #29084 from iamgergo/5.8
Browse files Browse the repository at this point in the history
[5.8] Add mergeRecursive() method on collections
  • Loading branch information
taylorotwell committed Jul 5, 2019
2 parents c4be803 + bbb840e commit 5dafefb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Illuminate/Support/Collection.php
Expand Up @@ -1258,6 +1258,17 @@ public function merge($items)
return new static(array_merge($this->items, $this->getArrayableItems($items)));
}

/**
* Recursively merge the collection with the given items.
*
* @param mixed $items
* @return static
*/
public function mergeRecursive($items)
{
return new static(array_merge_recursive($this->items, $this->getArrayableItems($items)));
}

/**
* Create a collection by using this collection for keys and another for its values.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -666,6 +666,27 @@ public function testMergeCollection()
$this->assertEquals(['name' => 'World', 'id' => 1], $c->merge(new Collection(['name' => 'World', 'id' => 1]))->all());
}

public function testMergeRecursiveNull()
{
$c = new Collection(['name' => 'Hello']);
$this->assertEquals(['name' => 'Hello'], $c->mergeRecursive(null)->all());
}

public function testMergeRecursiveArray()
{
$c = new Collection(['name' => 'Hello', 'id' => 1]);
$this->assertEquals(['name' => 'Hello', 'id' => [1, 2]], $c->mergeRecursive(['id' => 2])->all());
}

public function testMergeRecursiveCollection()
{
$c = new Collection(['name' => 'Hello', 'id' => 1, 'meta' => ['tags' => ['a', 'b'], 'roles' => 'admin']]);
$this->assertEquals(
['name' => 'Hello', 'id' => 1, 'meta' => ['tags' => ['a', 'b', 'c'], 'roles' => ['admin', 'editor']]],
$c->mergeRecursive(new Collection(['meta' => ['tags' => ['c'], 'roles' => 'editor']]))->all()
);
}

public function testUnionNull()
{
$c = new Collection(['name' => 'Hello']);
Expand Down

0 comments on commit 5dafefb

Please sign in to comment.