Skip to content

Commit

Permalink
feat(Result): introduce Result::unwrapOr()
Browse files Browse the repository at this point in the history
I'd like to introduce a function that allows to get inner value from Result if success and allows to bypass throwing an exception from Failure by providing a default value.
  • Loading branch information
simPod committed Apr 25, 2024
1 parent 79eb271 commit 9d6bebf
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Psl/Result/Failure.php
Expand Up @@ -44,6 +44,20 @@ public function getResult(): void
throw $this->throwable;
}

/**
* Unwrap the Result if it is succeeded or return $default value.
*
* @param D $default
*
* @return T|D
*
* @template D
*/
public function unwrapOr(mixed $default): mixed
{
return $default;
}

/**
* Since this is a failed result wrapper, this always returns the `Throwable` thrown during the operation.
*
Expand Down
11 changes: 11 additions & 0 deletions src/Psl/Result/ResultInterface.php
Expand Up @@ -95,6 +95,17 @@ public function always(Closure $always): ResultInterface;
*/
public function getResult();

/**
* Unwrap the Result if it is succeeded or return $default value.
*
* @param D $default
*
* @return T|D
*
* @template D
*/
public function unwrapOr(mixed $default): mixed;

/**
* Return the underlying throwable, or fail with a invariant violation exception.
*
Expand Down
14 changes: 14 additions & 0 deletions src/Psl/Result/Success.php
Expand Up @@ -44,6 +44,20 @@ public function getResult(): mixed
return $this->value;
}

/**
* Unwrap the Result if it is succeeded or return $default value.
*
* @param D $default
*
* @return T|D
*
* @template D
*/
public function unwrapOr(mixed $default): mixed
{
return $this->value;
}

/**
* Since this is a successful result wrapper, this always throws a
* `Psl\Exception\InvariantViolationException` saying that there was no exception thrown from the operation.
Expand Down
8 changes: 8 additions & 0 deletions tests/unit/Result/FailureTest.php
Expand Up @@ -33,6 +33,14 @@ public function testGetResult(): void
$wrapper->getResult();
}

public function testUnwrapFailure(): void
{
$result = new Failure(new Exception());
$value = $result->unwrapOr(null);

static::assertNull($value);
}

public function testGetException(): void
{
$exception = new Exception('bar');
Expand Down
8 changes: 8 additions & 0 deletions tests/unit/Result/SuccessTest.php
Expand Up @@ -31,6 +31,14 @@ public function testGetResult(): void
static::assertSame('hello', $wrapper->getResult());
}

public function testUnwrap(): void
{
$result = new Success('foo');
$value = $result->unwrapOr(null);

static::assertSame('foo', $value);
}

public function testGetException(): void
{
$wrapper = new Success('hello');
Expand Down

0 comments on commit 9d6bebf

Please sign in to comment.