Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/add back ify funtions #26

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"psr-4": {
"TH\\Maybe\\": "src/"
},
"files": ["src/functions/option.php", "src/functions/result.php"]
"files": ["src/functions/option.php", "src/functions/result.php", "src/functions/internal.php"]
},
"autoload-dev": {
"psr-4": {
Expand Down
1 change: 1 addition & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<exclude name="SlevomatCodingStandard.Functions.DisallowNamedArguments" />
<exclude name="SlevomatCodingStandard.Functions.DisallowTrailingCommaInCall" />
<exclude name="SlevomatCodingStandard.Functions.DisallowTrailingCommaInDeclaration" />
<exclude name="SlevomatCodingStandard.Functions.DisallowTrailingCommaInClosureUse" />
<exclude name="SlevomatCodingStandard.Functions.UnusedParameter" />
<exclude name="SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation" />
<exclude name="SlevomatCodingStandard.Namespaces.FullyQualifiedExceptions" />
Expand Down
89 changes: 89 additions & 0 deletions src/functions/option.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace TH\Maybe\Option;

use TH\DocTest\Attributes\ExamplesSetup;
use TH\Maybe\Internal;
use TH\Maybe\Option;
use TH\Maybe\Result;
use TH\Maybe\Tests\Helpers\IgnoreUnusedResults;
Expand Down Expand Up @@ -137,6 +138,94 @@ function tryOf(
}
}

/**
* Wrap a callable into one that transforms its result into an `Option`.
* It will be a `Some` option containing the result if it is different from `$noneValue` (default `null`).
*
* # Examples
*
* Successful execution:
*
* ```
* self::assertEq(Option\ify(strtolower(...))("FRUITS"), Option\some("fruits"));
* ```
*
* Convertion of `null` to `Option\None`:
*
* ```
* self::assertEq(Option\ify(fn() => null)(), Option\none());
* ```
*
* @template U
* @param callable(mixed...):U $callback
* @return \Closure(mixed...):Option<U>
*/
function ify(callable $callback, mixed $noneValue = null, bool $strict = true): \Closure
{
return static fn (...$args) => Option\fromValue($callback(...$args), $noneValue, $strict);
}

/**
* Wrap a callable into one that transforms its result into an `Option` like `Option\ify()` does
* but also return `Option\None` if it an exception matching $exceptionClass was thrown.
*
* # Examples
*
* Successful execution:
*
* ```
* self::assertEq(Option\tryIfy(strtolower(...))("FRUITS"), Option\some("fruits"));
* ```
*
* Convertion of `null` to `Option\None`:
*
* ```
* self::assertEq(Option\tryIfy(fn() => null)(), Option\none());
* ```
*
* Checked Exception:
*
* ```
* self::assertEq(Option\tryIfy(fn () => new \DateTimeImmutable("nope"))(), Option\none());
* ```
*
* Unchecked Exception:
*
* ```
* self::assertEq(Option\tryIfy(fn () => 1 / 0)(), Option\none());
* // @throws DivisionByZeroError Division by zero
* ```
*
* @template U
* @template E of \Throwable
* @param callable(mixed...):U $callback
* @param class-string<E> $exceptionClass
* @param class-string<E> $additionalExceptionClasses
* @return \Closure(mixed...):Option<U>
*/
function tryIfy(
callable $callback,
mixed $noneValue = null,
bool $strict = true,
string $exceptionClass = \Exception::class,
string ...$additionalExceptionClasses,
): \Closure
{
return static function (...$args) use (
$callback,
$noneValue,
$strict,
$exceptionClass,
$additionalExceptionClasses,
): mixed {
try {
return Option\fromValue($callback(...$args), $noneValue, $strict);
} catch (\Throwable $th) {
return Internal\trap($th, Option\none(...), $exceptionClass, ...$additionalExceptionClasses);
}
};
}

/**
* Converts from `Option<Option<T>>` to `Option<T>`.
*
Expand Down
84 changes: 77 additions & 7 deletions src/functions/result.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace TH\Maybe\Result;

use TH\DocTest\Attributes\ExamplesSetup;
use TH\Maybe\Internal;
use TH\Maybe\Option;
use TH\Maybe\Result;
use TH\Maybe\Tests\Helpers\IgnoreUnusedResults;
Expand Down Expand Up @@ -79,24 +80,93 @@ function err(mixed $value): Result\Err
* @template E of \Throwable
* @param callable(mixed...):U $callback
* @param class-string<E> $exceptionClass
* @param class-string<E> $additionalExceptionClasses
* @return Result<U,E>
* @throws \Throwable
*/
#[ExamplesSetup(IgnoreUnusedResults::class)]
function trap(callable $callback, string $exceptionClass = \Exception::class): Result
{
function trap(
callable $callback,
string $exceptionClass = \Exception::class,
string ...$additionalExceptionClasses,
): Result {
try {
/** @var Result<U,E> */
return Result\ok($callback());
} catch (\Throwable $th) {
if (\is_a($th, $exceptionClass)) {
return Result\err($th);
}

throw $th;
/** @var Result\Err<E> */
return Internal\trap($th, Result\err(...), $exceptionClass, ...$additionalExceptionClasses);
}
}

/**
* Wrap a callable into one that transforms its returned value or thrown exception
* into a `Result` like `Result\trap()` does, but without executing it.
*
* # 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
* @param class-string<E> $additionalExceptionClasses
* @return \Closure(mixed...):Result<U,E>
*/
#[ExamplesSetup(IgnoreUnusedResults::class)]
function ify(
callable $callback,
string $exceptionClass = \Exception::class,
string ...$additionalExceptionClasses,
): \Closure {
return static function (...$args) use ($callback, $exceptionClass, $additionalExceptionClasses): Result
{
try {
return Result\ok($callback(...$args));
} catch (\Throwable $th) {
/** @var Result\Err<E> */
return Internal\trap($th, Result\err(...), $exceptionClass, ...$additionalExceptionClasses);
}
};
}

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

namespace TH\Maybe\Tests\Unit\Option;

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

final class IfyTest extends TestCase
{
use Provider\Options;

/**
* @dataProvider fromValueMatrix
* @param Option<mixed> $expected
*/
public function testIfy(Option $expected, mixed $value, mixed $noneValue, bool $strict = true): void
{
Assert::assertEquals($expected, Option\ify(static fn () => $value, $noneValue, strict: $strict)());
}

/**
* @dataProvider fromValueMatrix
* @param Option<mixed> $expected
*/
public function testTryOf(Option $expected, mixed $value, mixed $noneValue, bool $strict = true): void
{
Assert::assertEquals($expected, Option\tryIfy(static fn () => $value, $noneValue, strict: $strict)());
}

public function testOfDefaultToNull(): void
{
Assert::assertEquals(Option\none(), Option\ify(static fn () => null)());
Assert::assertEquals(Option\some(1), Option\ify(static fn () => 1)());
}

public function testTryOfDefaultToNull(): void
{
Assert::assertEquals(Option\none(), Option\tryIfy(static fn () => null)());
Assert::assertEquals(Option\some(1), Option\tryIfy(static fn () => 1)());
}

public function testOfDefaultToStrict(): void
{
$o = (object)[];

Assert::assertEquals(Option\none(), Option\ify(static fn () => $o, (object)[], strict: false)());
Assert::assertEquals($o, Option\ify(static fn () => $o, (object)[])()->unwrap());
}

public function testTryOfDefaultToStrict(): void
{
$o = (object)[];

Assert::assertEquals(Option\none(), Option\tryIfy(static fn () => $o, (object)[], strict: false)());
Assert::assertEquals($o, Option\tryIfy(static fn () => $o, (object)[])()->unwrap());
}

public function testTryOfExeptions(): void
{
// @phpstan-ignore-next-line
Assert::assertEquals(Option\none(), Option\tryIfy(static fn () => new \DateTimeImmutable("nope"))());

try {
// @phpstan-ignore-next-line
Option\tryIfy(static fn () => 1 / 0)();
Assert::fail("An exception should have been thrown");
} catch (\DivisionByZeroError) {
}
}
}
66 changes: 66 additions & 0 deletions tests/Unit/Result/IfyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?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
{
$this->expectExceptionObject(
new \Exception(
"Failed to parse time string (nope) at position 0 (n): The timezone could not be found in the database",
),
);

Result\ify(
// @phpstan-ignore-next-line
static fn () => new \DateTimeImmutable("nope"),
)()->unwrap();
}

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(),
);
}
}

/**
* @dataProvider values
*/
public function testIfyWithArguments(mixed $value): void
{
$fileGetContents = Result\ify(
callback: static fn (string $filename): string => match ($content = \file_get_contents($filename)) {
false => throw new \RuntimeException("Can't get content from $filename"),
default => $content,
},
);

Assert::assertIsCallable($fileGetContents);
}
}
Loading