-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParameters.php
76 lines (66 loc) · 1.99 KB
/
Parameters.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace JsonLogic;
use Closure;
class Parameters
{
private $params;
public static function from(array &$params): Parameters
{
return new static(
...array_map(
[Rule::class, 'make'],
$params
)
);
}
public function __construct(Closure &...$params)
{
$this->params = $params;
}
public function every(callable $fn, &$data): bool
{
return $this->recurseEvery($fn, $data, ...$this->params);
}
public function everyPairs(callable $fn, &$data): bool
{
return $this->recurseEveryPairs(
$fn,
$data,
$this->params[0]($data),
...array_slice($this->params, 1)
);
}
public function reduce(callable $fn, &$data, $init = null)
{
return is_null($init)
? array_reduce(
array_slice($this->params, 1),
function ($curry, $closure) use (&$data, &$fn) {
return $fn($curry, $closure($data));
},
$this->params[0]($data)
)
: array_reduce($this->params, function ($curry, $closure) use (&$data, &$fn) {
return $fn($curry, $closure($data));
}, $init);
}
public function values(&$data): array
{
return array_map(function ($getter) use (&$data) {
return $getter($data);
}, $this->params);
}
private function recurseEvery(callable &$fn, &$data, Closure &$getter = null, Closure &...$rest): bool
{
return $getter
&& $fn($getter($data))
&& $this->recurseEvery($fn, $data, ...$rest);
}
private function recurseEveryPairs(callable &$fn, &$data, $curr, Closure &$getter = null, Closure &...$rest): bool
{
$next = $getter($data);
return count($rest)
? $fn($curr, $next) && $this->recurseEveryPairs($fn, $data, $next, ...$rest)
: $fn($curr, $next);
}
}