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

[9.x] Add whenMissing() method to InteractsWithInput trait #45019

Merged
merged 1 commit into from
Nov 19, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Illuminate/Http/Concerns/InteractsWithInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,27 @@ public function missing($key)
return ! $this->has($keys);
}

/**
* Apply the callback if the request is missing the given input item key.
*
* @param string $key
* @param callable $callback
* @param callable|null $default
* @return $this|mixed
*/
public function whenMissing($key, callable $callback, callable $default = null)
{
if ($this->missing($key)) {
return $callback(data_get($this->all(), $key)) ?: $this;
}

if ($default) {
return $default();
phh marked this conversation as resolved.
Show resolved Hide resolved
}

return $this;
}

/**
* Determine if the given input key is an empty string for "has".
*
Expand Down
35 changes: 35 additions & 0 deletions tests/Http/HttpRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,41 @@ public function testMissingMethod()
$this->assertFalse($request->missing('foo.baz'));
}

public function testWhenMissingMethod()
{
$request = Request::create('/', 'GET', ['bar' => null]);

$name = $age = $city = $foo = $bar = true;

$request->whenMissing('name', function ($value) use (&$name) {
$name = 'Taylor';
});

$request->whenMissing('age', function ($value) use (&$age) {
$age = '';
});

$request->whenMissing('city', function ($value) use (&$city) {
$city = null;
});

$request->whenMissing('foo', function () use (&$foo) {
$foo = false;
});

$request->whenMissing('bar', function () use (&$bar) {
$bar = 'test';
}, function () use (&$bar) {
$bar = true;
});

$this->assertSame('Taylor', $name);
$this->assertSame('', $age);
$this->assertNull($city);
$this->assertFalse($foo);
$this->assertTrue($bar);
}

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