Skip to content

Commit 134f1bc

Browse files
authored
add ifPresent consumer for Option (#98)
1 parent 07409b7 commit 134f1bc

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Control/Option.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,16 @@ public function isPresent(): bool
7070
return !$this->isEmpty();
7171
}
7272

73+
/**
74+
* @param callable(T): void $consumer
75+
*/
76+
public function ifPresent(callable $consumer): void
77+
{
78+
if ($this->isPresent()) {
79+
$consumer($this->get());
80+
}
81+
}
82+
7383
/**
7484
* @template U
7585
*

tests/Control/OptionTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,4 +182,10 @@ public function testOptionIsPresent(): void
182182
self::assertTrue(Option::some(null)->isPresent());
183183
self::assertFalse(Option::none()->isPresent());
184184
}
185+
186+
public function testOptionIfPresent(): void
187+
{
188+
Option::none()->ifPresent(fn ($v) => throw new \RuntimeException('impossible is nothing'));
189+
Option::of('a')->ifPresent(fn ($v) => self::assertSame('a', $v));
190+
}
185191
}

0 commit comments

Comments
 (0)