/
Until.php
85 lines (78 loc) · 3.16 KB
/
Until.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
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace loophp\collection\Operation;
use Closure;
use Generator;
use Iterator;
/**
* @psalm-template TKey
* @psalm-template TKey of array-key
* @psalm-template T
*
* phpcs:disable Generic.Files.LineLength.TooLong
* phpcs:disable Generic.WhiteSpace.ScopeIndent.IncorrectExact
*/
final class Until extends AbstractOperation
{
/**
* @psalm-return Closure((callable(T, TKey):bool)...): Closure(Iterator<TKey, T>): Generator<TKey, T>
*/
public function __invoke(): Closure
{
return
/**
* @psalm-param callable(T, TKey):bool ...$callbacks
*/
static function (callable ...$callbacks): Closure {
return
/**
* @psalm-param Iterator<TKey, T> $iterator
*
* @psalm-return Generator<TKey, T>
*/
static function (Iterator $iterator) use ($callbacks): Generator {
$reducerCallback =
/**
* @psalm-param TKey $key
*
* @psalm-return Closure(T): Closure(bool, callable(T, TKey): bool): bool
*
* @param mixed $key
*/
static function ($key): Closure {
return
/**
* @psalm-param T $value
*
* @psalm-return Closure(bool, callable(T, TKey): bool): bool
*
* @param mixed $value
*/
static function ($value) use ($key): Closure {
return
/**
* @psalm-param bool $carry
* @psalm-param callable(T, TKey): bool $callable
*/
static function (bool $carry, callable $callable) use ($key, $value): bool {
return ($callable($value, $key)) ?
$carry :
false;
};
};
};
foreach ($iterator as $key => $value) {
yield $key => $value;
$result = array_reduce(
$callbacks,
$reducerCallback($key)($value),
true
);
if (false !== $result) {
break;
}
}
};
};
}
}