Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Add callback support to "optional" #23688

Merged
merged 1 commit into from
Mar 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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