Skip to content

Commit fc8103d

Browse files
committed
Add missing Option::orElse method
1 parent fbbff2e commit fc8103d

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

src/Psl/Option/Option.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,24 @@ public function or(Option $option): Option
193193
return $option;
194194
}
195195

196+
/**
197+
* Returns the option if it contains a value, otherwise calls $closure and returns the result.
198+
*
199+
* @param (Closure(): Option<T>) $closure
200+
*
201+
* @param-immediately-invoked-callable $closure
202+
*
203+
* @return Option<T>
204+
*/
205+
public function orElse(Closure $closure): Option
206+
{
207+
if ($this->option !== null) {
208+
return $this;
209+
}
210+
211+
return $closure();
212+
}
213+
196214
/**
197215
* Returns none if the option is none, otherwise calls `$predicate` with the wrapped value and returns:
198216
* - Option<T>::some() if `$predicate` returns true (where t is the wrapped value), and

tests/unit/Option/NoneTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,14 @@ public function testOr(): void
7171
static::assertFalse(Option\none()->or(Option\some(4))->isNone());
7272
}
7373

74+
public function testOrElse(): void
75+
{
76+
static::assertFalse(Option\none()->orElse(static fn () => Option\none())->isSome());
77+
static::assertTrue(Option\none()->orElse(static fn () => Option\some(4))->isSome());
78+
static::assertTrue(Option\none()->orElse(static fn () => Option\none())->isNone());
79+
static::assertFalse(Option\none()->orElse(static fn () => Option\some(4))->isNone());
80+
}
81+
7482
public function testFilter(): void
7583
{
7684
$option = Option\none();

tests/unit/Option/SomeTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ public function testOr(): void
6868
static::assertFalse(Option\some(2)->or(Option\some(4))->isNone());
6969
}
7070

71+
public function testOrElse(): void
72+
{
73+
static::assertTrue(Option\some(2)->orElse(static fn () => Option\none())->isSome());
74+
static::assertTrue(Option\some(2)->orElse(static fn () => Option\some(4))->isSome());
75+
static::assertFalse(Option\some(2)->orElse(static fn () => Option\none())->isNone());
76+
static::assertFalse(Option\some(2)->orElse(static fn () => Option\some(4))->isNone());
77+
}
78+
7179
public function testFilter(): void
7280
{
7381
$option = Option\some(2);

0 commit comments

Comments
 (0)