Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collection replace and replaceRecursively functions #20220

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link

@lk77 lk77 Jul 23, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's http://php.net/manual/en/function.array-replace.php
And why there is a non-used and non-documented $recursive parameter?

*/
public function replace($items, $recursive = false)
{
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)));
}
}
15 changes: 15 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down