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.5] Rescue helper #21010

Merged
merged 5 commits into from
Sep 6, 2017
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
18 changes: 18 additions & 0 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,24 @@ function preg_replace_array($pattern, array $replacements, $subject)
}
}

if (! function_exists('rescue')) {
/**
* Catch a potential exception and return a default.
*
* @param callable $rescuee
* @param mixed $rescuer
* @return mixed
*/
function rescue(callable $rescuee, $rescuer)
{
try {
return $rescuee();
} catch (Throwable $e) {
return is_callable($rescuer) ? $rescuer() : $rescuer;
}
}
}

if (! function_exists('retry')) {
/**
* Retry an operation a given number of times.
Expand Down
28 changes: 28 additions & 0 deletions tests/Support/SupportHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,34 @@ public function something()
})->present()->something());
}

public function testRescue()
{
$this->assertEquals(rescue(function () {
throw new Exception;
}, 'rescued!'), 'rescued!');

$this->assertEquals(rescue(function () {
throw new Exception;
}, function () {
return 'rescued!';
}), 'rescued!');

$this->assertEquals(rescue(function () {
return 'no need to rescue';
}, 'rescued!'), 'no need to rescue');

$testClass = new class {
public function test(int $a)
{
return $a;
}
};

$this->assertEquals(rescue(function () use ($testClass) {
$testClass->test([]);
}, 'rescued!'), 'rescued!');
}

public function testTransform()
{
$this->assertEquals(10, transform(5, function ($value) {
Expand Down