Skip to content

Commit

Permalink
[Functional] Add Either::getOrThrow method.
Browse files Browse the repository at this point in the history
  • Loading branch information
whsv26 committed Dec 28, 2021
1 parent 7e1b080 commit f0512e9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Fp/Functional/Either/Either.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,25 @@ public function getOrCall(callable $fallback): mixed
: $fallback();
}

/**
* ```php
* >>> Either::right(1)->getOrThrow(fn($err) => new RuntimeException($err));
* => 1
*
* >>> Either::left('error')->getOrThrow(fn($err) => new RuntimeException($err));
* RuntimeException with message 'error'
* ```
*
* @psalm-param callable(L): Throwable $fallback
* @psalm-return R
*/
public function getOrThrow(callable $fallback): mixed
{
return $this->isRight()
? $this->value
: throw $fallback($this->value);
}

/**
* Combine two Either into one
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Runtime/Classes/Either/EitherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Fp\Functional\Validated\Invalid;
use Fp\Functional\Validated\Valid;
use PHPUnit\Framework\TestCase;
use RuntimeException;

final class EitherTest extends TestCase
{
Expand Down Expand Up @@ -136,10 +137,21 @@ public function testGetOrElse(): void
{
$this->assertEquals(1, Either::right(1)->getOrElse(0));
$this->assertEquals(0, Either::left('err')->getOrElse(0));
}

public function testGetOrCall(): void
{
$this->assertEquals(1, Either::right(1)->getOrCall(fn() => 0));
$this->assertEquals(0, Either::left('err')->getOrCall(fn() => 0));
}

public function testGetOrThrow(): void
{
$this->assertEquals(1, Either::right(1)->getOrThrow(fn($err) => new RuntimeException($err)));
$this->expectExceptionMessage('err');
Either::left('err')->getOrThrow(fn($err) => new RuntimeException($err));
}

public function testOrElse(): void
{
$this->assertEquals(
Expand Down

0 comments on commit f0512e9

Please sign in to comment.