Skip to content

Commit e19dbdb

Browse files
author
Patrick
authored
Add whenMissing() (#45019)
1 parent 6182fdb commit e19dbdb

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Illuminate/Http/Concerns/InteractsWithInput.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,27 @@ public function missing($key)
224224
return ! $this->has($keys);
225225
}
226226

227+
/**
228+
* Apply the callback if the request is missing the given input item key.
229+
*
230+
* @param string $key
231+
* @param callable $callback
232+
* @param callable|null $default
233+
* @return $this|mixed
234+
*/
235+
public function whenMissing($key, callable $callback, callable $default = null)
236+
{
237+
if ($this->missing($key)) {
238+
return $callback(data_get($this->all(), $key)) ?: $this;
239+
}
240+
241+
if ($default) {
242+
return $default();
243+
}
244+
245+
return $this;
246+
}
247+
227248
/**
228249
* Determine if the given input key is an empty string for "has".
229250
*

tests/Http/HttpRequestTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,41 @@ public function testMissingMethod()
452452
$this->assertFalse($request->missing('foo.baz'));
453453
}
454454

455+
public function testWhenMissingMethod()
456+
{
457+
$request = Request::create('/', 'GET', ['bar' => null]);
458+
459+
$name = $age = $city = $foo = $bar = true;
460+
461+
$request->whenMissing('name', function ($value) use (&$name) {
462+
$name = 'Taylor';
463+
});
464+
465+
$request->whenMissing('age', function ($value) use (&$age) {
466+
$age = '';
467+
});
468+
469+
$request->whenMissing('city', function ($value) use (&$city) {
470+
$city = null;
471+
});
472+
473+
$request->whenMissing('foo', function () use (&$foo) {
474+
$foo = false;
475+
});
476+
477+
$request->whenMissing('bar', function () use (&$bar) {
478+
$bar = 'test';
479+
}, function () use (&$bar) {
480+
$bar = true;
481+
});
482+
483+
$this->assertSame('Taylor', $name);
484+
$this->assertSame('', $age);
485+
$this->assertNull($city);
486+
$this->assertFalse($foo);
487+
$this->assertTrue($bar);
488+
}
489+
455490
public function testHasAnyMethod()
456491
{
457492
$request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => '', 'city' => null]);

0 commit comments

Comments
 (0)