Chunk::__invoke()   A
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 37
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 1
nop 0
dl 0
loc 37
ccs 18
cts 18
cp 1
crap 5
rs 9.3888
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace loophp\collection\Operation;
6
7
use Closure;
8
use Generator;
9
10
use function count;
11
12
/**
13
 * @immutable
14
 *
15
 * @template TKey
16
 * @template T
17
 */
18
final class Chunk extends AbstractOperation
19
{
20
    /**
21
     * @return Closure(int...): Closure(iterable<TKey, T>): Generator<int, non-empty-list<T>>
22
     */
23 20
    public function __invoke(): Closure
24
    {
25 20
        return
26
            /**
27
             * @return Closure(iterable<TKey, T>): Generator<int, non-empty-list<T>>
28
             */
29 20
            static fn (int ...$sizes): Closure =>
30
                /**
31
                 * @param iterable<TKey, T> $iterable
32
                 *
33
                 * @return Generator<int, non-empty-list<T>>
34
                 */
35 20
                static function (iterable $iterable) use ($sizes): Generator {
36 20
                    $sizesCount = count($sizes);
37 20
                    $chunkIndex = 0;
38 20
                    $chunk = [];
39
40 20
                    foreach ($iterable as $value) {
41 18
                        $size = $sizes[$chunkIndex % $sizesCount];
42
43 18
                        if (0 >= $size) {
44 2
                            return;
45
                        }
46
47 16
                        $chunk[] = $value;
48
49 16
                        if (count($chunk) >= $size) {
50 16
                            ++$chunkIndex;
51
52 16
                            yield $chunk;
53
54 16
                            $chunk = [];
55
                        }
56
                    }
57
58 18
                    if ([] !== $chunk) {
59 4
                        yield $chunk;
60
                    }
61 20
                };
62
    }
63
}
64