|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* For the full copyright and license information, please view |
|
5
|
|
|
* the LICENSE file that was distributed with this source code. |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
declare(strict_types=1); |
|
9
|
|
|
|
|
10
|
|
|
namespace loophp\fpt; |
|
11
|
|
|
|
|
12
|
|
|
use Closure; |
|
13
|
|
|
use Generator; |
|
14
|
|
|
use ReflectionFunction; |
|
15
|
|
|
|
|
16
|
|
|
use function count; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Stateless "Curry" application. |
|
20
|
|
|
* |
|
21
|
|
|
* @psalm-immutable |
|
22
|
|
|
* |
|
23
|
|
|
* phpcs:disable Generic.Files.LineLength.TooLong |
|
24
|
|
|
*/ |
|
25
|
|
|
final class Curry |
|
26
|
|
|
{ |
|
27
|
|
|
/** |
|
28
|
|
|
* @psalm-pure |
|
29
|
4 |
|
*/ |
|
30
|
|
|
public static function of(): Closure |
|
31
|
|
|
{ |
|
32
|
|
|
return |
|
33
|
|
|
/** |
|
34
|
|
|
* @param Closure|callable-string $callable |
|
|
|
|
|
|
35
|
4 |
|
*/ |
|
36
|
|
|
static function (callable $callable, int $arity = 0, mixed ...$arguments): mixed { |
|
37
|
|
|
if (0 === $arity) { |
|
38
|
|
|
$reflection = (new ReflectionFunction($callable)); |
|
39
|
|
|
$parameters = $reflection->getNumberOfParameters(); |
|
40
|
|
|
$requiredParameters = $reflection->getNumberOfRequiredParameters(); |
|
41
|
4 |
|
} |
|
42
|
4 |
|
|
|
43
|
|
|
return self::curryN( |
|
44
|
4 |
|
$callable, |
|
45
|
4 |
|
$parameters ?? $arity, |
|
46
|
|
|
$requiredParameters ?? $arity, |
|
47
|
|
|
...$arguments |
|
48
|
|
|
); |
|
49
|
|
|
}; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @param Closure|callable-string $callable |
|
|
|
|
|
|
54
|
|
|
*/ |
|
55
|
|
|
private static function curryN(callable $callable, int $parameters, int $requiredParameters, mixed ...$arguments): mixed |
|
56
|
|
|
{ |
|
57
|
|
|
$countArguments = count($arguments); |
|
58
|
|
|
|
|
59
|
|
|
return match (true) { |
|
60
|
|
|
0 === $requiredParameters => static fn (): mixed => ($callable)(), |
|
61
|
4 |
|
$countArguments >= $parameters, $countArguments >= $requiredParameters => ($callable)(...$arguments), |
|
62
|
|
|
default => static fn (mixed ...$args): mixed => self::curryN($callable, $parameters, $requiredParameters, ...self::getArguments($arguments, $args)) |
|
63
|
4 |
|
}; |
|
64
|
4 |
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* @psalm-pure |
|
68
|
|
|
* |
|
69
|
|
|
* @psalm-param list<mixed> $args |
|
70
|
|
|
* @psalm-param list<mixed> $argsNext |
|
71
|
4 |
|
* |
|
72
|
|
|
* @psalm-return Generator<int, mixed> |
|
73
|
|
|
*/ |
|
74
|
|
|
private static function getArguments(array $args, array $argsNext): Generator |
|
75
|
|
|
{ |
|
76
|
|
|
return yield from array_merge($args, $argsNext); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|