From 7a0776bfb7bfc22dce0d083e094d83ecbd197b7a Mon Sep 17 00:00:00 2001 From: whsv26 Date: Sat, 18 Dec 2021 03:01:54 +0300 Subject: [PATCH] [Functional] Option getOrThrow method. --- psalm.xml | 5 +++++ src/Fp/Functional/Option/Option.php | 24 ++++++++++++++++++++- tests/Runtime/Classes/Option/OptionTest.php | 12 +++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/psalm.xml b/psalm.xml index 1e27b1c2..79d6af27 100644 --- a/psalm.xml +++ b/psalm.xml @@ -58,5 +58,10 @@ + + + + + diff --git a/src/Fp/Functional/Option/Option.php b/src/Fp/Functional/Option/Option.php index 05859dbe..b4231683 100644 --- a/src/Fp/Functional/Option/Option.php +++ b/src/Fp/Functional/Option/Option.php @@ -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 * ``` * @@ -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 * diff --git a/tests/Runtime/Classes/Option/OptionTest.php b/tests/Runtime/Classes/Option/OptionTest.php index 2ade0c0f..d889ae2b 100644 --- a/tests/Runtime/Classes/Option/OptionTest.php +++ b/tests/Runtime/Classes/Option/OptionTest.php @@ -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; @@ -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(