Skip to content

Commit

Permalink
ValueAs::caught
Browse files Browse the repository at this point in the history
  • Loading branch information
bajb committed Feb 15, 2019
1 parent 20d0cf7 commit c50e9ce
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/ValueAs.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,4 +280,24 @@ public static function transformed($value, callable $callback, $default = null)
{
return $value ? self::coalesce($callback($value), $default) : $default;
}

/**
* Call a callable, catching any exception and returning default
*
* @param callable $callable
* @param mixed $default
*
* @return mixed
*/
public static function caught(callable $callable, $default = null)
{
try
{
return $callable();
}
catch(\Exception $e)
{
return is_callable($default) ? $default($e) : $default;
}
}
}
13 changes: 13 additions & 0 deletions tests/ValueAsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,17 @@ public function testTransformed()
$this->assertEquals('ab', ValueAs::transformed('1', $callback, 'ab'));
$this->assertEquals('ab', ValueAs::transformed(null, $callback, 'ab'));
}

public function testCaught()
{
$this->assertEquals('abc', ValueAs::caught(function () { throw new \Exception('e'); }, 'abc'));
$this->assertEquals(
'abcdef',
ValueAs::caught(
function () { throw new \Exception('abc'); },
function (\Exception $e) { return $e->getMessage() . 'def'; }
)
);
$this->assertEquals('xyz', ValueAs::caught(function () { return 'xyz'; }, 'abc'));
}
}

0 comments on commit c50e9ce

Please sign in to comment.