96 lines
2.8 KiB
PHP
96 lines
2.8 KiB
PHP
<?php
|
|
/**
|
|
* Copyright 2026 Kacper Donat
|
|
*
|
|
* @author Kacper "Kadet" Donat <kacper@kadet.net>
|
|
*
|
|
* Full license available in separate LICENSE file
|
|
*/
|
|
|
|
use Kadet\Functional as f;
|
|
use function Kadet\Functional\Internal\callback;
|
|
use const Kadet\Functional\_;
|
|
|
|
class CallbackTest extends \PHPUnit\Framework\TestCase
|
|
{
|
|
public function testInternalFunctionGetsValueOnly()
|
|
{
|
|
$this->assertSame('a', callback(trim(...))(' a ', 'xyz'));
|
|
}
|
|
|
|
public function testInternalStringCallableGetsValueOnly()
|
|
{
|
|
$this->assertSame('A', callback('strtoupper')('a', 'key'));
|
|
}
|
|
|
|
public function testSingleParamClosureIsNotWrapped()
|
|
{
|
|
// PHP drops the key on its own: a userland closure ignores arguments past its parameters.
|
|
$closure = fn ($v) => $v;
|
|
|
|
$this->assertSame($closure, callback($closure));
|
|
}
|
|
|
|
public function testDecoratedSingleParamClosureGetsValueOnly()
|
|
{
|
|
$this->assertSame([1], callback(f\memoize(function ($v) { return func_get_args(); }))(1, 'k'));
|
|
}
|
|
|
|
public function testPipelineStartingWithInternalFunctionGetsValueOnly()
|
|
{
|
|
$this->assertSame('a', callback(f\pipe(trim(...)))(' a ', 'xyz'));
|
|
}
|
|
|
|
public function testPipelineStartingWithTwoParamClosureGetsKey()
|
|
{
|
|
$this->assertSame('k=v', callback(f\pipe(fn ($v, $k) => "$k=$v"))('v', 'k'));
|
|
}
|
|
|
|
public function testCarryAndValueOnlyForTwoParamTarget()
|
|
{
|
|
$this->assertSame([1, 2], callback(f\memoize(function ($c, $v) { return func_get_args(); }), 2)(1, 2, 'k'));
|
|
}
|
|
|
|
public function testCarryValueAndKeyForThreeParamTarget()
|
|
{
|
|
$this->assertSame('1+2@k', callback(fn ($c, $v, $k) => "$c+$v@$k", 2)(1, 2, 'k'));
|
|
}
|
|
|
|
public function testTwoParamClosureGetsKey()
|
|
{
|
|
$this->assertSame('k=v', callback(fn ($v, $k) => "$k=$v")('v', 'k'));
|
|
}
|
|
|
|
public function testVariadicClosureGetsKey()
|
|
{
|
|
$this->assertSame(['v', 'k'], callback(fn (...$args) => $args)('v', 'k'));
|
|
}
|
|
|
|
public function testPartialOfInternalFunctionDoesNotGetKey()
|
|
{
|
|
$this->assertSame('a', callback(f\partial(trim(...), _, 'x'))('xax', 'key'));
|
|
}
|
|
|
|
public function testPartialOfInternalFunctionDoesNotFillOptionalParameterWithKey()
|
|
{
|
|
$this->assertSame(['a', 'b'], callback(f\partial(explode(...), ','))('a,b', 0));
|
|
}
|
|
|
|
public function testPartialOfInternalFunctionWithoutArgumentsGetsValueOnly()
|
|
{
|
|
$this->assertSame('a', callback(f\partial(trim(...)))(' a ', 'k'));
|
|
}
|
|
|
|
public function testCompiledMemoizedInternalFunctionGetsValueOnly()
|
|
{
|
|
$this->assertSame('a', callback(f\compile(f\memoize(trim(...))))(' a ', 'k'));
|
|
}
|
|
|
|
public function testDecoratorIsCompiled()
|
|
{
|
|
$callback = callback(f\partial(fn ($prefix, $v, $k) => "$prefix$k=$v", '>'));
|
|
|
|
$this->assertSame('>k=v', $callback('v', 'k'));
|
|
}
|
|
}
|