Skip to content

Commit

Permalink
Add callback support to "optional" (#23688)
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber authored and taylorotwell committed Mar 25, 2018
1 parent 64fb6f7 commit cb6e308
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Illuminate/Support/helpers.php
Expand Up @@ -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);
}
}
}

Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportHelpersTest.php
Expand Up @@ -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']);
Expand Down

0 comments on commit cb6e308

Please sign in to comment.