Skip to content

Commit

Permalink
Introduce Result::all()
Browse files Browse the repository at this point in the history
  • Loading branch information
someniatko committed Jun 20, 2023
1 parent ef33ea6 commit ebde759
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,25 @@ public static function extractErrors(array $results): array
[],
);
}

/**
* If all given results are Success,
* returns a Success with array of extracted Success values.
* Otherwise, if at least one is an Error
* returns an Error with array of extracted Error values.
*
* @psalm-pure
* @template T
* @template E
* @param list<ResultInterface<T, E>> $results
* @return ResultInterface<list<T>, list<E>>
*/
public static function all(array $results): ResultInterface
{
$errors = self::extractErrors($results);

return empty($errors)
? self::success(self::extractSuccesses($results))
: self::error($errors);
}
}
31 changes: 31 additions & 0 deletions test/ResultTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,35 @@ public function testEnsureErrorDoesNotChangePreviousError(): void
$ensured = $result->ensure(fn(int $i) => $i > 100, 'new error');
self::assertEquals('old error', $ensured->get());
}

public function testAllWhenOnlySuccesses(): void
{
$resultA = Result::success('A');
$resultB = Result::success(23);

$all = Result::all([ $resultA, $resultB ]);
self::assertInstanceOf(Success::class, $all);
self::assertEquals([ 'A', 23 ], $all->get());
}

public function testAllWhenOnlyErrors(): void
{
$resultA = Result::error(1);
$resultB = Result::error('B');

$all = Result::all([ $resultA, $resultB ]);
self::assertInstanceOf(Error::class, $all);
self::assertEquals([ 1, 'B' ], $all->get());
}

public function testAllWhenMixedErrorsAndSuccesses(): void
{
$resultA = Result::error(1);
$resultB = Result::success('B');
$resultC = Result::error(false);

$all = Result::all([ $resultA, $resultB, $resultC ]);
self::assertInstanceOf(Error::class, $all);
self::assertEquals([ 1, false ], $all->get());
}
}

0 comments on commit ebde759

Please sign in to comment.