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

[8.x] Add a mergeIfMissing method to the Illuminate Http Request class #40116

Merged
merged 4 commits into from
Dec 22, 2021
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
13 changes: 13 additions & 0 deletions src/Illuminate/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,19 @@ public function merge(array $input)
return $this;
}

/**
* Merge new input into the request's input, but only when that key is missing from the request.
*
* @param array $input
* @return $this
*/
public function mergeIfMissing(array $input)
{
return $this->merge(collect($input)->filter(function ($value, $key) {
return $this->missing($key);
})->toArray());
}

/**
* Replace the input for the current request.
*
Expand Down
15 changes: 15 additions & 0 deletions tests/Http/HttpRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,21 @@ public function testMergeMethod()
$this->assertSame('Dayle', $request->input('buddy'));
}

public function testMergeIfMissingMethod()
{
$request = Request::create('/', 'GET', ['name' => 'Taylor']);
$merge = ['boolean_setting' => 0];
$request->mergeIfMissing($merge);
$this->assertSame('Taylor', $request->input('name'));
$this->assertSame(0, $request->input('boolean_setting'));

$request = Request::create('/', 'GET', ['name' => 'Taylor', 'boolean_setting' => 1]);
$merge = ['boolean_setting' => 0];
$request->mergeIfMissing($merge);
$this->assertSame('Taylor', $request->input('name'));
$this->assertSame(1, $request->input('boolean_setting'));
}

public function testReplaceMethod()
{
$request = Request::create('/', 'GET', ['name' => 'Taylor']);
Expand Down