Skip to content

Commit d3b4950

Browse files
committed
Revert "Revert "feature: Add Result\ify()""
This reverts commit b2c07d2.
1 parent 8a7d3c3 commit d3b4950

File tree

3 files changed

+136
-2
lines changed

3 files changed

+136
-2
lines changed

src/functions/option.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,9 @@ function of(callable $callback, mixed $noneValue = null, bool $strict = true): O
114114
* ```
115115
*
116116
* @template U
117+
* @template E of \Throwable
117118
* @param callable():U $callback
119+
* @param class-string<E> $exceptionClass
118120
* @return Option<U>
119121
* @throws \Throwable
120122
*/
@@ -154,7 +156,7 @@ function tryOf(
154156
* ```
155157
*
156158
* @template U
157-
* @param callable():U $callback
159+
* @param callable(mixed...):U $callback
158160
* @return \Closure(mixed...):Option<U>
159161
*/
160162
function ify(callable $callback, mixed $noneValue = null, bool $strict = true): \Closure
@@ -194,7 +196,9 @@ function ify(callable $callback, mixed $noneValue = null, bool $strict = true):
194196
* ```
195197
*
196198
* @template U
197-
* @param callable():U $callback
199+
* @template E of \Throwable
200+
* @param callable(mixed...):U $callback
201+
* @param class-string<E> $exceptionClass
198202
* @return \Closure(mixed...):Option<U>
199203
*/
200204
function tryIfy(

src/functions/result.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,73 @@ function trap(callable $callback, string $exceptionClass = \Exception::class): R
9797
}
9898
}
9999

100+
/**
101+
* Wrap a callable into one that transforms its returned value or thrown exception
102+
* into a `Result` like `Result\trap()` does.
103+
*
104+
* # Examples
105+
*
106+
* Successful execution:
107+
*
108+
* ```
109+
* self::assertEq(Result\ok(3), Result\ify(fn () => 3)());
110+
* ```
111+
*
112+
* Checked exception:
113+
*
114+
* ```
115+
* $x = Result\ify(fn () => new \DateTimeImmutable("2020-30-30 UTC"))();
116+
* self::assertTrue($x->isErr());
117+
* $x->unwrap();
118+
* // @throws Exception Failed to parse time string (2020-30-30 UTC) at position 6 (0): Unexpected character
119+
* ```
120+
*
121+
* Unchecked exception:
122+
*
123+
* ```
124+
* Result\ify(fn () => 1/0)();
125+
* // @throws DivisionByZeroError Division by zero
126+
* ```
127+
*
128+
* Result-ify `strtotime()`:
129+
*
130+
* ```
131+
* $strtotime = Result\ify(
132+
* static fn (...$args)
133+
* => \strtotime(...$args)
134+
* ?: throw new \RuntimeException("Could not convert string to time"),
135+
* );
136+
*
137+
* self::assertEq($strtotime("2015-09-21 UTC midnight")->unwrap(), 1442793600);
138+
*
139+
* $r = $strtotime("nope");
140+
* self::assertTrue($r->isErr());
141+
* $r->unwrap(); // @throws RuntimeException Could not convert string to time
142+
* ```
143+
*
144+
* @template U
145+
* @template E of \Throwable
146+
* @param callable(mixed...):U $callback
147+
* @param class-string<E> $exceptionClass
148+
* @return \Closure(mixed...):Result<U,E>
149+
*/
150+
#[ExamplesSetup(IgnoreUnusedResults::class)]
151+
function ify(callable $callback, string $exceptionClass = \Exception::class): \Closure
152+
{
153+
return static function (...$args) use ($callback, $exceptionClass): Result
154+
{
155+
try {
156+
return Result\ok($callback(...$args));
157+
} catch (\Throwable $th) {
158+
if (\is_a($th, $exceptionClass)) {
159+
return Result\err($th);
160+
}
161+
162+
throw $th;
163+
}
164+
};
165+
}
166+
100167
/**
101168
* Converts from `Result<Result<T, E>, E>` to `Result<T, E>`.
102169
*

tests/Unit/Result/IfyTest.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace TH\Maybe\Tests\Unit\Result;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use TH\Maybe\Result;
7+
use TH\Maybe\Tests\Assert;
8+
use TH\Maybe\Tests\Provider;
9+
10+
final class IfyTest extends TestCase
11+
{
12+
use Provider\Values;
13+
14+
/**
15+
* @dataProvider values
16+
*/
17+
public function testIfyOk(mixed $value): void
18+
{
19+
$callback = static fn () => $value;
20+
21+
Assert::assertEquals($value, Result\ify($callback)()->unwrap());
22+
}
23+
24+
public function testIfyCheckedException(): void
25+
{
26+
Assert::assertEquals(
27+
new \Exception(
28+
"Failed to parse time string (nope) at position 0 (n): The timezone could not be found in the database",
29+
),
30+
// @phpstan-ignore-next-line
31+
Result\ify(static fn () => new \DateTimeImmutable("nope"))()->unwrapErr(),
32+
);
33+
}
34+
35+
public function testIfyUncheckedException(): void
36+
{
37+
try {
38+
// @phpstan-ignore-next-line
39+
Result\ify(static fn () => 1 / 0)();
40+
Assert::fail("An exception should have been thrown");
41+
} catch (\DivisionByZeroError $ex) {
42+
Assert::assertEquals(
43+
"Division by zero",
44+
$ex->getMessage(),
45+
);
46+
}
47+
}
48+
49+
/**
50+
* @dataProvider values
51+
*/
52+
public function testIfyWithArguments(mixed $value): void
53+
{
54+
$fileGetContents = Result\ify(
55+
callback: static fn (string $filename) => match ($content = \file_get_contents($filename)) {
56+
false => throw new \RuntimeException("Can't get content from $filename"),
57+
default => $content,
58+
},
59+
);
60+
61+
Assert::assertIsCallable($fileGetContents);
62+
}
63+
}

0 commit comments

Comments
 (0)