forked from azjezz/psl
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(Result): introduce
unwrapResultOr()
I'd like to introduce a function that allows to get inner value from Result if success and allows to bypass throwing an exception from Failure by providing a default value.
- Loading branch information
Showing
4 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Psl\Result; | ||
|
||
use Closure; | ||
use Throwable; | ||
|
||
/** | ||
* Unwrap the given Result if it is succeeded or return $default value | ||
* | ||
* @param ResultInterface<T> $r | ||
* @param F $f | ||
* | ||
* @return T|F | ||
* | ||
* @template T | ||
* @template F | ||
*/ | ||
function unwrapResultOr(ResultInterface $r, mixed $f) | ||
{ | ||
return $r->isSucceeded() ? $r->getResult() : $f; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Psl\Tests\Unit\Result; | ||
|
||
use Exception; | ||
use PHPUnit\Framework\TestCase; | ||
use Psl\Result; | ||
|
||
final class UnwrapResultOrTest extends TestCase | ||
{ | ||
public function testUnwrapSuccess(): void | ||
{ | ||
$result = new Result\Success('foo'); | ||
$value = Result\unwrapResultOr($result, null); | ||
|
||
self::assertSame('foo', $value); | ||
} | ||
|
||
public function testUnwrapFailure(): void | ||
{ | ||
$result = new Result\Failure(new Exception()); | ||
$value = Result\unwrapResultOr($result, null); | ||
|
||
self::assertNull($value); | ||
} | ||
} |