From fc8103d1407b94bed6ced6031e8128e048d7f8ae Mon Sep 17 00:00:00 2001 From: Toon Verwerft Date: Wed, 29 May 2024 12:51:54 +0200 Subject: [PATCH] Add missing Option::orElse method --- src/Psl/Option/Option.php | 18 ++++++++++++++++++ tests/unit/Option/NoneTest.php | 8 ++++++++ tests/unit/Option/SomeTest.php | 8 ++++++++ 3 files changed, 34 insertions(+) diff --git a/src/Psl/Option/Option.php b/src/Psl/Option/Option.php index 4ac1575c..a5703173 100644 --- a/src/Psl/Option/Option.php +++ b/src/Psl/Option/Option.php @@ -193,6 +193,24 @@ public function or(Option $option): Option return $option; } + /** + * Returns the option if it contains a value, otherwise calls $closure and returns the result. + * + * @param (Closure(): Option) $closure + * + * @param-immediately-invoked-callable $closure + * + * @return Option + */ + public function orElse(Closure $closure): Option + { + if ($this->option !== null) { + return $this; + } + + return $closure(); + } + /** * Returns none if the option is none, otherwise calls `$predicate` with the wrapped value and returns: * - Option::some() if `$predicate` returns true (where t is the wrapped value), and diff --git a/tests/unit/Option/NoneTest.php b/tests/unit/Option/NoneTest.php index 57c8372f..bf570099 100644 --- a/tests/unit/Option/NoneTest.php +++ b/tests/unit/Option/NoneTest.php @@ -71,6 +71,14 @@ public function testOr(): void static::assertFalse(Option\none()->or(Option\some(4))->isNone()); } + public function testOrElse(): void + { + static::assertFalse(Option\none()->orElse(static fn () => Option\none())->isSome()); + static::assertTrue(Option\none()->orElse(static fn () => Option\some(4))->isSome()); + static::assertTrue(Option\none()->orElse(static fn () => Option\none())->isNone()); + static::assertFalse(Option\none()->orElse(static fn () => Option\some(4))->isNone()); + } + public function testFilter(): void { $option = Option\none(); diff --git a/tests/unit/Option/SomeTest.php b/tests/unit/Option/SomeTest.php index fbcf2581..a2439b05 100644 --- a/tests/unit/Option/SomeTest.php +++ b/tests/unit/Option/SomeTest.php @@ -68,6 +68,14 @@ public function testOr(): void static::assertFalse(Option\some(2)->or(Option\some(4))->isNone()); } + public function testOrElse(): void + { + static::assertTrue(Option\some(2)->orElse(static fn () => Option\none())->isSome()); + static::assertTrue(Option\some(2)->orElse(static fn () => Option\some(4))->isSome()); + static::assertFalse(Option\some(2)->orElse(static fn () => Option\none())->isNone()); + static::assertFalse(Option\some(2)->orElse(static fn () => Option\some(4))->isNone()); + } + public function testFilter(): void { $option = Option\some(2);