Skip to content

Commit

Permalink
Merge pull request #16 from petrknap/improved-or-else-throw
Browse files Browse the repository at this point in the history
feat: `orElseThrow` now does not require supplier
  • Loading branch information
petrknap authored May 24, 2024
2 parents 0aa7220 + f9ddf76 commit 8295a89
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 7 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ $optionalString = Optional::of('value');
echo $optionalString->isPresent() ? $optionalString->get() : 'empty';
echo $optionalString->orElse('empty');
echo $optionalString->orElseGet(fn () => 'empty');
echo $optionalString->orElseThrow(fn () => new \Exception());
echo $optionalString->orElseThrow();

$optionalString->ifPresent(function (string $value): void { echo $value; });

Expand Down
9 changes: 3 additions & 6 deletions src/Optional.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public function get(): mixed
if ($this->wasPresent === null) {
self::logNotice('Call `isPresent()` before accessing the value.');
}
return $this->orElseThrow(static fn (): Exception\CouldNotGetValueOfEmptyOptional => new Exception\CouldNotGetValueOfEmptyOptional()); // @todo use default supplier
return $this->orElseThrow();
}

public function ifPresent(callable $consumer): void
Expand Down Expand Up @@ -140,14 +140,11 @@ public function orElseGet(callable $otherSupplier): mixed
return static::isSupported($other) ? $other : throw new InvalidArgumentException('Other supplier must return supported other.');
}

/**
* @todo make supplier nullable
*/
public function orElseThrow(callable $exceptionSupplier): mixed
public function orElseThrow(?callable $exceptionSupplier = null): mixed
{
return $this->orElseGet(static function () use ($exceptionSupplier): never {
/** @var Throwable|mixed $exception */
$exception = $exceptionSupplier();
$exception = $exceptionSupplier === null ? new Exception\CouldNotGetValueOfEmptyOptional() : $exceptionSupplier();
if ($exception instanceof Throwable) {
throw $exception;
}
Expand Down

0 comments on commit 8295a89

Please sign in to comment.