Skip to content

Commit

Permalink
Merge pull request #31 from petrknap/if-present-else
Browse files Browse the repository at this point in the history
Added `else` argument to `ifPresent`
  • Loading branch information
petrknap authored Jan 22, 2025
2 parents 30d768f + a15fc34 commit 8c5c811
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ if ($optionalString->isPresent()) {
OptionalResource::ofFalsable(tmpfile())->ifPresent(function ($tmpFile): void {
fwrite($tmpFile, 'data');
fclose($tmpFile);
});
}, else: fn () => print('tmpfile() failed'));
```

### Create and use your own typed optional
Expand Down
4 changes: 3 additions & 1 deletion src/Optional.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,12 @@ public function get(): mixed
return $this->orElseThrow();
}

public function ifPresent(callable $consumer): void
public function ifPresent(callable $consumer, callable|null $else = null): void
{
if ($this->value !== null) {
$consumer($this->value);
} elseif ($else !== null) {
$else();
}
}

Expand Down
24 changes: 15 additions & 9 deletions tests/OptionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,22 +225,28 @@ public static function dataMethodGetWorks(): array
}

#[DataProvider('dataMethodIfPresentWorks')]
public function testMethodIfPresentWorks(Optional $optional, bool $expectedInvoke): void
public function testMethodIfPresentWorks(Optional $optional, string $expectedInvoked): void
{
$invoked = false;
$optional->ifPresent(static function (string $value) use (&$invoked) {
self::assertSame(self::VALUE, $value);
$invoked = true;
});
$invoked = null;
$optional->ifPresent(
consumer: static function (string $value) use (&$invoked) {
self::assertSame(self::VALUE, $value);
$invoked = 'consumer';
},
else: static function (mixed ...$args) use (&$invoked) {
self::assertSame([], $args);
$invoked = 'else';
},
);

self::assertSame($expectedInvoke, $invoked);
self::assertSame($expectedInvoked, $invoked);
}

public static function dataMethodIfPresentWorks(): array
{
return self::makeDataSet([
[true],
[false],
['consumer'],
['else'],
]);
}

Expand Down

0 comments on commit 8c5c811

Please sign in to comment.