Passed
Push — master ( 6f062f...02e88d )
by Pol
11:29 queued 09:22
created

Curry   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 45
ccs 10
cts 10
cp 1
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A curryN() 0 10 2
A of() 0 15 1
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 ReflectionFunction;
14
15
use function count;
16
17
/**
18
 * @psalm-immutable
19
 *
20
 * phpcs:disable Generic.Files.LineLength.TooLong
21
 */
22
abstract class Curry
23
{
24
    /**
25
     * @template T
26
     * @psalm-pure
27
     */
28 4
    public static function of(): Closure
29
    {
30
        return
31
            /**
32
             * @psalm-param positive-int|null $arity
33
             */
34 4
            static fn (callable $callable, ?int $arity = null): Closure =>
35
            /**
36
             * @psalm-param mixed ...$args
37
             * @return mixed
38
             */
39 4
            static fn (...$args) => static::curryN(
40 4
                ($arity ?? (new ReflectionFunction($callable))->getNumberOfRequiredParameters()) - count($args),
41
                $callable,
42 4
                static::getArguments([], $args)
43 4
            );
44
    }
45
46
    /**
47
     * @psalm-pure
48
     *
49
     * @psalm-param list<mixed> $args
50
     * @psalm-param list<mixed> $argsNext
51
     */
52
    abstract protected static function getArguments(array $args = [], array $argsNext = []): array;
53
54
    /**
55
     * @return mixed
56
     */
57 4
    private static function curryN(int $numberOfArguments, callable $function, array $args = [])
58
    {
59 4
        return (0 >= $numberOfArguments)
60 4
            ? $function(...$args)
61
            :
62
            /**
63
             * @psalm-param mixed ...$argsNext
64
             * @return mixed
65
             */
66 4
            static fn (...$argsNext) => self::curryN($numberOfArguments - count($argsNext), $function, static::getArguments($args, $argsNext));
67
    }
68
}
69