/
Filter.php
63 lines (57 loc) · 2.08 KB
/
Filter.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
<?php
declare(strict_types=1);
namespace loophp\collection\Operation;
use CallbackFilterIterator;
use Closure;
use Generator;
use Iterator;
/**
* @psalm-template TKey
* @psalm-template TKey of array-key
* @psalm-template T
*
* phpcs:disable Generic.Files.LineLength.TooLong
*/
final class Filter extends AbstractOperation
{
/**
* @psalm-return Closure((callable(T, TKey, Iterator<TKey, T>): bool)...): Closure(Iterator<TKey, T>): Generator<TKey, T>
*/
public function __invoke(): Closure
{
return
/**
* @psalm-param callable(T, TKey, Iterator<TKey, T>): 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 {
$defaultCallback =
/**
* @param mixed $value
* @param mixed $key
* @psalm-param T $value
* @psalm-param TKey $key
* @psalm-param Iterator<TKey, T> $iterator
*/
static function ($value, $key, Iterator $iterator): bool {
return (bool) $value;
};
$callbacks = [] === $callbacks ?
[$defaultCallback] :
$callbacks;
return yield from array_reduce(
$callbacks,
static function (Iterator $carry, callable $callback): CallbackFilterIterator {
return new CallbackFilterIterator($carry, $callback);
},
$iterator
);
};
};
}
}