Skip to content

Commit

Permalink
feat(Result): introduce unwrapResultOr()
Browse files Browse the repository at this point in the history
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
simPod committed Apr 19, 2024
1 parent 79eb271 commit b9c04ac
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/component/result.md
Expand Up @@ -15,6 +15,7 @@
- [collect_stats](./../../src/Psl/Result/collect_stats.php#L14)
- [reflect](./../../src/Psl/Result/reflect.php#L24)
- [try_catch](./../../src/Psl/Result/try_catch.php#L24)
- [unwrapResultOr](./../../src/Psl/Result/unwrapResultOr.php#L21)
- [wrap](./../../src/Psl/Result/wrap.php#L20)

#### `Interfaces`
Expand Down
1 change: 1 addition & 0 deletions src/Psl/Internal/Loader.php
Expand Up @@ -187,6 +187,7 @@ final class Loader
'Psl\\Math\\atan2' => 'Psl/Math/atan2.php',
'Psl\\Math\\to_base' => 'Psl/Math/to_base.php',
'Psl\\Result\\collect_stats' => 'Psl/Result/collect_stats.php',
'Psl\\Result\\unwrapResultOr' => 'Psl/Result/unwrapResultOr.php',
'Psl\\Result\\wrap' => 'Psl/Result/wrap.php',
'Psl\\Regex\\capture_groups' => 'Psl/Regex/capture_groups.php',
'Psl\\Regex\\every_match' => 'Psl/Regex/every_match.php',
Expand Down
24 changes: 24 additions & 0 deletions src/Psl/Result/unwrapResultOr.php
@@ -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 a `Success`, 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;
}
28 changes: 28 additions & 0 deletions tests/unit/Result/UnwrapResultOrTest.php
@@ -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);
}
}

0 comments on commit b9c04ac

Please sign in to comment.