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 array_slice; |
17
|
|
|
use function count; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Stateless "Curry" application. |
21
|
|
|
* |
22
|
|
|
* @psalm-immutable |
23
|
|
|
* |
24
|
|
|
* phpcs:disable Generic.Files.LineLength.TooLong |
25
|
|
|
*/ |
26
|
|
|
final class Curry |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
4 |
|
* @pure |
30
|
|
|
*/ |
31
|
|
|
public static function of(): Closure |
32
|
|
|
{ |
33
|
|
|
return |
34
|
|
|
/** |
35
|
4 |
|
* @param Closure|callable-string $callable |
|
|
|
|
36
|
|
|
*/ |
37
|
|
|
static function (callable $callable, int $arity = 0, mixed ...$arguments): mixed { |
38
|
|
|
if (0 === $arity) { |
39
|
|
|
$reflection = (new ReflectionFunction($callable)); |
40
|
|
|
$parameters = $reflection->getNumberOfParameters(); |
41
|
4 |
|
$requiredParameters = $reflection->getNumberOfRequiredParameters(); |
42
|
4 |
|
$arity = $parameters === $requiredParameters ? $parameters : $arity; |
43
|
|
|
} |
44
|
4 |
|
|
45
|
4 |
|
return self::curryN( |
46
|
|
|
$callable, |
47
|
|
|
$arity, |
48
|
|
|
$parameters ?? $arity, |
49
|
|
|
$requiredParameters ?? $arity, |
50
|
|
|
...$arguments |
51
|
|
|
); |
52
|
|
|
}; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param Closure|callable-string $callable |
|
|
|
|
57
|
|
|
*/ |
58
|
|
|
private static function curryN(callable $callable, int $arity, int $parameters, int $requiredParameters, mixed ...$arguments): mixed |
59
|
|
|
{ |
60
|
|
|
$countArguments = count($arguments); |
61
|
4 |
|
|
62
|
|
|
return match (true) { |
63
|
4 |
|
0 === $requiredParameters => static fn (): mixed => ($callable)(), |
64
|
4 |
|
$countArguments >= $parameters, $countArguments >= $requiredParameters => ($callable)(...array_slice($arguments, 0, 0 !== $arity ? $arity : $countArguments)), |
65
|
|
|
default => static fn (mixed ...$args): mixed => self::curryN($callable, $arity, $parameters, $requiredParameters, ...self::getArguments($arguments, $args)) |
66
|
|
|
}; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @pure |
71
|
4 |
|
* |
72
|
|
|
* @param list<mixed> $args |
73
|
|
|
* @param list<mixed> $argsNext |
|
|
|
|
74
|
|
|
* |
75
|
|
|
* @return Generator<int, mixed> |
76
|
|
|
*/ |
77
|
|
|
private static function getArguments(array $args, array $argsNext): Generator |
78
|
|
|
{ |
79
|
|
|
return yield from array_merge($args, $argsNext); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|