diff --git a/src/Illuminate/Support/helpers.php b/src/Illuminate/Support/helpers.php index ddcbbed302dd..0c6966c18a6f 100755 --- a/src/Illuminate/Support/helpers.php +++ b/src/Illuminate/Support/helpers.php @@ -718,11 +718,16 @@ function object_get($object, $key, $default = null) * Provide access to optional objects. * * @param mixed $value + * @param callable|null $callback * @return mixed */ - function optional($value = null) + function optional($value = null, callable $callback = null) { - return new Optional($value); + if (is_null($callback)) { + return new Optional($value); + } elseif (! is_null($value)) { + return $callback($value); + } } } diff --git a/tests/Support/SupportHelpersTest.php b/tests/Support/SupportHelpersTest.php index 1e612741b5ad..e1ab3d9c3389 100755 --- a/tests/Support/SupportHelpersTest.php +++ b/tests/Support/SupportHelpersTest.php @@ -784,6 +784,19 @@ public function something() })->something()); } + public function testOptionalWithCallback() + { + $this->assertNull(optional(null, function () { + throw new RuntimeException( + 'The optional callback should not be called for null' + ); + })); + + $this->assertEquals(10, optional(5, function ($number) { + return $number * 2; + })); + } + public function testOptionalWithArray() { $this->assertEquals('here', optional(['present' => 'here'])['present']);