mirror of
https://github.com/danog/endtoend-test-psl.git
synced 2024-11-26 20:34:59 +01:00
[Fun] add when function (#85)
This commit is contained in:
parent
2336e5624e
commit
d1c54e429e
36
src/Psl/Fun/when.php
Normal file
36
src/Psl/Fun/when.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Psl\Fun;
|
||||
|
||||
/**
|
||||
* Creates a callback that can run a left or right function based on a condition.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* $greet = Fun\when(
|
||||
* static fn(string $name): bool => $name === 'Jos',
|
||||
* static fn(string $name): string => 'Bonjour Jos!',
|
||||
* static fn(string $name): string => 'Hello ' . $name . '!'
|
||||
* );
|
||||
*
|
||||
* $greet('World')
|
||||
* => Str('Hello World!');
|
||||
*
|
||||
* $greet('Jos')
|
||||
* => Str('Bonjour Jos!');
|
||||
*
|
||||
* @template Ti
|
||||
* @template To
|
||||
*
|
||||
* @psalm-param (callable(Ti): bool) $condition
|
||||
* @psalm-param (callable(Ti): To) $then
|
||||
* @psalm-param (callable(Ti): To) $else
|
||||
*
|
||||
* @psalm-return (callable(Ti): To)
|
||||
*/
|
||||
function when(callable $condition, callable $then, callable $else): callable
|
||||
{
|
||||
return fn ($value) => $condition($value) ? $then($value) : $else($value);
|
||||
}
|
@ -99,6 +99,7 @@ final class Loader
|
||||
'Psl\Fun\passthrough',
|
||||
'Psl\Fun\pipe',
|
||||
'Psl\Fun\rethrow',
|
||||
'Psl\Fun\when',
|
||||
'Psl\Internal\boolean',
|
||||
'Psl\Internal\type',
|
||||
'Psl\Internal\validate_offset',
|
||||
|
33
tests/Psl/Fun/WhenTest.php
Normal file
33
tests/Psl/Fun/WhenTest.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Psl\Tests\Fun;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psl\Fun;
|
||||
|
||||
final class WhenTest extends TestCase
|
||||
{
|
||||
public function testItRunsLeftFunction(): void
|
||||
{
|
||||
$greet = Fun\when(
|
||||
static fn(string $name): bool => $name === 'Jos',
|
||||
static fn(string $name): string => 'Bonjour ' . $name . '!',
|
||||
static fn(string $name): string => 'Hello ' . $name . '!'
|
||||
);
|
||||
|
||||
self::assertSame('Bonjour Jos!', $greet('Jos'));
|
||||
}
|
||||
|
||||
public function testItRunsRightfunction(): void
|
||||
{
|
||||
$greet = Fun\when(
|
||||
static fn(string $name): bool => $name === 'Jos',
|
||||
static fn(string $name): string => 'Bonjour ' . $name . '!',
|
||||
static fn(string $name): string => 'Hello ' . $name . '!'
|
||||
);
|
||||
|
||||
self::assertSame('Hello World!', $greet('World'));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user