From 1e83437ef8f07e99f295a6361c715d4a12334c3d Mon Sep 17 00:00:00 2001 From: Patrick Holberg Hesselberg Date: Fri, 18 Nov 2022 22:48:23 +0100 Subject: [PATCH] Add whenMissing() --- .../Http/Concerns/InteractsWithInput.php | 21 +++++++++++ tests/Http/HttpRequestTest.php | 35 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/Illuminate/Http/Concerns/InteractsWithInput.php b/src/Illuminate/Http/Concerns/InteractsWithInput.php index ae28ca268b2a..835753113cd0 100644 --- a/src/Illuminate/Http/Concerns/InteractsWithInput.php +++ b/src/Illuminate/Http/Concerns/InteractsWithInput.php @@ -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(); + } + + return $this; + } + /** * Determine if the given input key is an empty string for "has". * diff --git a/tests/Http/HttpRequestTest.php b/tests/Http/HttpRequestTest.php index b98bf4dc245c..bce0ed6217dc 100644 --- a/tests/Http/HttpRequestTest.php +++ b/tests/Http/HttpRequestTest.php @@ -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]);