1 | <?php |
||
6 | |||
7 | final class CurriedFn implements FixedArityInterface |
||
8 | { |
||
9 | /** |
||
10 | * @var callable |
||
11 | */ |
||
12 | private $fn; |
||
13 | |||
14 | private int $arity; |
||
|
|||
15 | |||
16 | /** |
||
17 | * @var array<int, mixed> $args |
||
18 | */ |
||
19 | private array $args = []; |
||
20 | |||
21 | /** |
||
22 | * @param int $arity |
||
23 | * @param callable $fn, |
||
24 | * @param mixed[] $args |
||
25 | */ |
||
26 | private function __construct(int $arity, callable $fn, array $args = []) |
||
27 | { |
||
28 | $this->arity = $arity; |
||
29 | $this->fn = $fn; |
||
30 | $this->args = $args; |
||
31 | } |
||
32 | |||
33 | public static function of(callable $fn): self |
||
34 | { |
||
35 | return ($fn instanceof static) |
||
36 | ? new static($fn->arity, $fn->fn, $fn->args) |
||
37 | : static::ofN(Phln::arity($fn), $fn); |
||
38 | } |
||
39 | |||
40 | public static function ofN(int $arity, callable $fn): self |
||
41 | { |
||
42 | return new static($arity, $fn); |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @param array<int, mixed> ...$args |
||
47 | * @return CurriedFn|mixed |
||
48 | */ |
||
49 | public function __invoke(...$args) |
||
50 | { |
||
51 | $allArgs = array_merge($this->args, $args); |
||
52 | |||
53 | return ($this->arity > count($allArgs)) |
||
54 | ? new static($this->arity, $this->fn, $allArgs) |
||
55 | : call_user_func_array($this->fn, $allArgs); |
||
56 | } |
||
63 |