|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Baethon\Phln; |
|
5
|
|
|
|
|
6
|
|
|
final class Phln |
|
7
|
|
|
{ |
|
8
|
|
|
const __ = '_phln_fn_partial_placeholder'; |
|
9
|
|
|
|
|
10
|
|
|
protected static $macros = []; |
|
11
|
|
|
|
|
12
|
|
|
private function __construct() |
|
13
|
|
|
{ |
|
14
|
|
|
} |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Makes an alias for given macro |
|
18
|
|
|
* |
|
19
|
|
|
* @param string $macroName |
|
20
|
|
|
* @param string $targetMacro |
|
21
|
|
|
*/ |
|
22
|
|
|
public static function alias(string $macroName, string $targetMacro) |
|
23
|
|
|
{ |
|
24
|
|
|
static::macro($macroName, static::raw($targetMacro)); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Returns "reference" to one of Phln macros or methods |
|
29
|
|
|
* |
|
30
|
|
|
* @param string $macroName |
|
31
|
|
|
* @return callable |
|
32
|
|
|
*/ |
|
33
|
|
|
public static function raw(string $macroName): callable |
|
34
|
|
|
{ |
|
35
|
|
|
return static::hasMacro($macroName) |
|
36
|
|
|
? static::$macros[$macroName] |
|
37
|
|
|
: sprintf('%s::%s', static::class, $macroName); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public static function arity(callable $fn): int |
|
41
|
|
|
{ |
|
42
|
|
|
return ($fn instanceof FixedArityInterface) |
|
43
|
|
|
? $fn->getArity() |
|
44
|
|
|
: (new \ReflectionFunction($fn))->getNumberOfParameters(); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public static function curry(callable $fn, array $args = []) |
|
48
|
|
|
{ |
|
49
|
|
|
return CurriedFn::of($fn)(...$args); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public static function curryN(int $n, callable $fn, array $args = []) |
|
53
|
|
|
{ |
|
54
|
|
|
return CurriedFn::ofN($n, $fn)(...$args); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public static function macro(string $name, callable $macro) |
|
58
|
|
|
{ |
|
59
|
|
|
static::$macros[$name] = $macro; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
public static function hasMacro(string $name): bool |
|
63
|
|
|
{ |
|
64
|
|
|
return isset(static::$macros[$name]); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public static function __callStatic($method, $parameters) |
|
68
|
|
|
{ |
|
69
|
|
|
if (! static::hasMacro($method)) { |
|
70
|
|
|
throw new \BadMethodCallException("Method {$method} does not exist."); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
return static::curry(static::$macros[$method], $parameters); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|