Skip to content

Commit

Permalink
add ifPresent consumer for Option (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
akondas authored May 18, 2024
1 parent 07409b7 commit 134f1bc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Control/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ public function isPresent(): bool
return !$this->isEmpty();
}

/**
* @param callable(T): void $consumer
*/
public function ifPresent(callable $consumer): void
{
if ($this->isPresent()) {
$consumer($this->get());
}
}

/**
* @template U
*
Expand Down
6 changes: 6 additions & 0 deletions tests/Control/OptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,10 @@ public function testOptionIsPresent(): void
self::assertTrue(Option::some(null)->isPresent());
self::assertFalse(Option::none()->isPresent());
}

public function testOptionIfPresent(): void
{
Option::none()->ifPresent(fn ($v) => throw new \RuntimeException('impossible is nothing'));
Option::of('a')->ifPresent(fn ($v) => self::assertSame('a', $v));
}
}

0 comments on commit 134f1bc

Please sign in to comment.