Skip to content

Commit

Permalink
[Functional] Option getOrThrow method.
Browse files Browse the repository at this point in the history
  • Loading branch information
whsv26 committed Dec 18, 2021
1 parent 03e76ae commit 7a0776b
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
5 changes: 5 additions & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,10 @@
</errorLevel>
</InternalProperty>
<UnusedClosureParam errorLevel="suppress"/>
<UnusedMethodCall errorLevel="suppress">
<errorLevel type="suppress">
<directory name="tests"/>
</errorLevel>
</UnusedMethodCall>
</issueHandlers>
</psalm>
24 changes: 23 additions & 1 deletion src/Fp/Functional/Option/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ public function getOrElse(mixed $fallback): mixed
* >>> Option::some(1)->getOrCall(fn() => 0);
* => 1
*
* >>> Option::none()->getOrElse(fn() => 0);
* >>> Option::none()->getOrCall(fn() => 0);
* => 0
* ```
*
Expand All @@ -486,6 +486,28 @@ public function getOrCall(callable $fallback): mixed
: $fallback();
}

/**
* Unwrap "the box" and get contained value
* or throw an exception if the box is empty
*
* ```php
* >>> Option::some(1)->getOrThrow(fn() => new RuntimeException('???'));
* => 1
*
* >>> Option::none()->getOrThrow(fn() => new RuntimeException('???'));
* RuntimeException with message '???'
* ```
*
* @psalm-param callable(): Throwable $fallback
* @psalm-return A
*/
public function getOrThrow(callable $fallback): mixed
{
return $this->isSome()
? $this->value
: throw $fallback();
}

/**
* Combine two Options into one
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Runtime/Classes/Option/OptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Fp\Functional\Option\Option;
use Fp\Functional\Option\Some;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use Tests\Mock\Bar;
use Tests\Mock\Foo;

Expand Down Expand Up @@ -108,10 +109,21 @@ public function testGetOrElse(): void
{
$this->assertEquals(1, Option::some(1)->getOrElse(0));
$this->assertEquals(0, Option::none()->getOrElse(0));
}

public function testGetOrCall(): void
{
$this->assertEquals(1, Option::some(1)->getOrCall(fn() => 0));
$this->assertEquals(0, Option::none()->getOrCall(fn() => 0));
}

public function testGetOrThrow(): void
{
$this->assertEquals(1, Option::some(1)->getOrThrow(fn() => new RuntimeException('???')));
$this->expectExceptionMessage('???');
Option::none()->getOrThrow(fn() => new RuntimeException('???'));
}

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

0 comments on commit 7a0776b

Please sign in to comment.