Skip to content

Commit

Permalink
feature: Add Result\ify()
Browse files Browse the repository at this point in the history
  • Loading branch information
mathroc committed Jul 20, 2023
1 parent 164c3e8 commit 9da2318
Show file tree
Hide file tree
Showing 3 changed files with 126 additions and 5 deletions.
8 changes: 6 additions & 2 deletions src/functions/option.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ function of(callable $callback, mixed $noneValue = null, bool $strict = true): O
* ```
*
* @template U
* @template E of \Throwable
* @param callable():U $callback
* @param class-string<E> $exceptionClass
* @return Option<U>
* @throws \Throwable
*/
Expand Down Expand Up @@ -154,7 +156,7 @@ function tryOf(
* ```
*
* @template U
* @param callable():U $callback
* @param callable(mixed...):U $callback
* @return \Closure(mixed...):Option<U>
*/
function ify(callable $callback, mixed $noneValue = null, bool $strict = true): \Closure
Expand Down Expand Up @@ -194,7 +196,9 @@ function ify(callable $callback, mixed $noneValue = null, bool $strict = true):
* ```
*
* @template U
* @param callable():U $callback
* @template E of \Throwable
* @param callable(mixed...):U $callback
* @param class-string<E> $exceptionClass
* @return \Closure(mixed...):Option<U>
*/
function tryIfy(
Expand Down
75 changes: 72 additions & 3 deletions src/functions/result.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,17 @@ function err(mixed $value): Result\Err
* ```
*
* @template U
* @param callable():U $callback
* @return Result<U,\Throwable>
* @template E of \Throwable
* @param callable(mixed...):U $callback
* @param class-string<E> $exceptionClass
* @return Result<U,E>
* @throws \Throwable
*/
#[ExamplesSetup(IgnoreUnusedResults::class)]
function trap(callable $callback, string $exceptionClass = \Exception::class): Result
{
try {
/** @var Result<U,\Throwable> */
/** @var Result<U,E> */
return Result\ok($callback());
} catch (\Throwable $th) {
if (\is_a($th, $exceptionClass)) {
Expand All @@ -94,6 +96,73 @@ function trap(callable $callback, string $exceptionClass = \Exception::class): R
}
}

/**
* Wrap a callable into one that transforms its returned value or thrown exception
* into a `Result` like `Result\trap()` does.
*
* # Examples
*
* Successful execution:
*
* ```
* self::assertEq(Result\ok(3), Result\ify(fn () => 3)());
* ```
*
* Checked exception:
*
* ```
* $x = Result\ify(fn () => new \DateTimeImmutable("2020-30-30 UTC"))();
* self::assertTrue($x->isErr());
* $x->unwrap();
* // @throws Exception Failed to parse time string (2020-30-30 UTC) at position 6 (0): Unexpected character
* ```
*
* Unchecked exception:
*
* ```
* Result\ify(fn () => 1/0)();
* // @throws DivisionByZeroError Division by zero
* ```
*
* Result-ify `strtotime()`:
*
* ```
* $strtotime = Result\ify(
* static fn (...$args)
* => \strtotime(...$args)
* ?: throw new \RuntimeException("Could not convert string to time"),
* );
*
* self::assertEq($strtotime("2015-09-21 UTC midnight")->unwrap(), 1442793600);
*
* $r = $strtotime("nope");
* self::assertTrue($r->isErr());
* $r->unwrap(); // @throws RuntimeException Could not convert string to time
* ```
*
* @template U
* @template E of \Throwable
* @param callable(mixed...):U $callback
* @param class-string<E> $exceptionClass
* @return \Closure(mixed...):Result<U,E>
*/
#[ExamplesSetup(IgnoreUnusedResults::class)]
function ify(callable $callback, string $exceptionClass = \Exception::class): \Closure
{
return static function (...$args) use ($callback, $exceptionClass): Result
{
try {
return Result\ok($callback(...$args));
} catch (\Throwable $th) {
if (\is_a($th, $exceptionClass)) {
return Result\err($th);
}

throw $th;
}
};
}

/**
* Converts from `Result<Result<T, E>, E>` to `Result<T, E>`.
*
Expand Down
48 changes: 48 additions & 0 deletions tests/Unit/Result/IfyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php declare(strict_types=1);

namespace TH\Maybe\Tests\Unit\Result;

use PHPUnit\Framework\TestCase;
use TH\Maybe\Result;
use TH\Maybe\Tests\Assert;
use TH\Maybe\Tests\Provider;

final class IfyTest extends TestCase
{
use Provider\Values;

/**
* @dataProvider values
*/
public function testIfyOk(mixed $value): void
{
$callback = static fn () => $value;

Assert::assertEquals($value, Result\ify($callback)()->unwrap());
}

public function testIfyCheckedException(): void
{
Assert::assertEquals(
new \Exception(
"Failed to parse time string (nope) at position 0 (n): The timezone could not be found in the database",
),
// @phpstan-ignore-next-line
Result\ify(static fn () => new \DateTimeImmutable("nope"))()->unwrapErr(),
);
}

public function testIfyUncheckedException(): void
{
try {
// @phpstan-ignore-next-line
Result\ify(static fn () => 1 / 0)();
Assert::fail("An exception should have been thrown");
} catch (\DivisionByZeroError $ex) {
Assert::assertEquals(
"Division by zero",
$ex->getMessage(),
);
}
}
}

0 comments on commit 9da2318

Please sign in to comment.