File tree Expand file tree Collapse file tree 2 files changed +31
-0
lines changed
tests/Runtime/Classes/Either Expand file tree Collapse file tree 2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -65,6 +65,25 @@ public function getOrCall(callable $fallback): mixed
6565 : $ fallback ();
6666 }
6767
68+ /**
69+ * ```php
70+ * >>> Either::right(1)->getOrThrow(fn($err) => new RuntimeException($err));
71+ * => 1
72+ *
73+ * >>> Either::left('error')->getOrThrow(fn($err) => new RuntimeException($err));
74+ * RuntimeException with message 'error'
75+ * ```
76+ *
77+ * @psalm-param callable(L): Throwable $fallback
78+ * @psalm-return R
79+ */
80+ public function getOrThrow (callable $ fallback ): mixed
81+ {
82+ return $ this ->isRight ()
83+ ? $ this ->value
84+ : throw $ fallback ($ this ->value );
85+ }
86+
6887 /**
6988 * Combine two Either into one
7089 *
Original file line number Diff line number Diff line change 1111use Fp \Functional \Validated \Invalid ;
1212use Fp \Functional \Validated \Valid ;
1313use PHPUnit \Framework \TestCase ;
14+ use RuntimeException ;
1415
1516final class EitherTest extends TestCase
1617{
@@ -136,10 +137,21 @@ public function testGetOrElse(): void
136137 {
137138 $ this ->assertEquals (1 , Either::right (1 )->getOrElse (0 ));
138139 $ this ->assertEquals (0 , Either::left ('err ' )->getOrElse (0 ));
140+ }
141+
142+ public function testGetOrCall (): void
143+ {
139144 $ this ->assertEquals (1 , Either::right (1 )->getOrCall (fn () => 0 ));
140145 $ this ->assertEquals (0 , Either::left ('err ' )->getOrCall (fn () => 0 ));
141146 }
142147
148+ public function testGetOrThrow (): void
149+ {
150+ $ this ->assertEquals (1 , Either::right (1 )->getOrThrow (fn ($ err ) => new RuntimeException ($ err )));
151+ $ this ->expectExceptionMessage ('err ' );
152+ Either::left ('err ' )->getOrThrow (fn ($ err ) => new RuntimeException ($ err ));
153+ }
154+
143155 public function testOrElse (): void
144156 {
145157 $ this ->assertEquals (
You can’t perform that action at this time.
0 commit comments