Skip to content

Commit 96a9bc7

Browse files
committed
Added when() method to InteractsWithInput trait
1 parent fdf3d4a commit 96a9bc7

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/Illuminate/Http/Concerns/InteractsWithInput.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,4 +430,20 @@ protected function retrieveItem($source, $key, $default)
430430

431431
return $this->$source->get($key, $default);
432432
}
433+
434+
/**
435+
* Apply the callback if the request contains a given input item key.
436+
*
437+
* @param string $key
438+
* @param callable|null $callback
439+
* @return $this
440+
*/
441+
public function when($key, callable $callback)
442+
{
443+
if ($this->has($key)) {
444+
$callback(data_get($this->all(), $key));
445+
}
446+
447+
return $this;
448+
}
433449
}

tests/Http/HttpRequestTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,37 @@ public function testHasMethod()
300300
$this->assertTrue($request->has('foo.baz'));
301301
}
302302

303+
public function testWhenMethod()
304+
{
305+
$request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => '', 'city' => null]);
306+
307+
$name = null;
308+
$age = null;
309+
$city = '';
310+
$foo = null;
311+
312+
$request->when('name', function ($value) use (&$name) {
313+
$name = $value;
314+
});
315+
316+
$request->when('age', function ($value) use (&$age) {
317+
$age = $value;
318+
});
319+
320+
$request->when('city', function ($value) use (&$city) {
321+
$city = $value;
322+
});
323+
324+
$request->when('foo', function () use (&$foo) {
325+
$foo = 'test';
326+
});
327+
328+
$this->assertSame('Taylor', $name);
329+
$this->assertSame('', $age);
330+
$this->assertNull($city);
331+
$this->assertNull($foo);
332+
}
333+
303334
public function testMissingMethod()
304335
{
305336
$request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => '', 'city' => null]);

0 commit comments

Comments
 (0)