Passed
Push — main ( 6ea3e4...b736ca )
by Pol
02:08
created

ChunkIterableAggregate   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 12
c 1
b 0
f 1
dl 0
loc 38
ccs 12
cts 12
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getIterator() 0 17 3
A __construct() 0 4 1
1
<?php
2
3
/**
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 */
7
8
declare(strict_types=1);
9
10
namespace loophp\iterators;
11
12
use Generator;
13
use IteratorAggregate;
14
use function count;
15
16
/**
17
 * @template TKey
18
 * @template T
19
 *
20
 * @implements IteratorAggregate<int, list<T>>
21
 */
22
final class ChunkIterableAggregate implements IteratorAggregate
23
{
24
    private int $chunkSize;
25
26
    /**
27
     * @var iterable<TKey, T>
28
     */
29
    private iterable $iterable;
30
31
    /**
32
     * @param iterable<TKey, T> $iterable
33
     */
34 1
    public function __construct(iterable $iterable, int $chunkSize)
35
    {
36 1
        $this->iterable = $iterable;
37 1
        $this->chunkSize = $chunkSize;
38
    }
39
40
    /**
41
     * @return Generator<int, list<T>>
42
     */
43 1
    public function getIterator(): Generator
44
    {
45 1
        $values = [];
46
47 1
        foreach ($this->iterable as $key => $value) {
48 1
            if (count($values) !== $this->chunkSize) {
49 1
                $values[] = $value;
50
51 1
                continue;
52
            }
53
54 1
            yield $values;
55
56 1
            $values = [$value];
57
        }
58
59 1
        yield $values;
60
    }
61
}
62