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

[5.8] Add replace() and replaceRecursive() methods on collections #29088

Merged
merged 2 commits into from
Jul 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 22 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
42 changes: 42 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down