Passed
Pull Request — master (#3)
by Dmitry
02:34
created

BatchProcessing::callListeners()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SymfonyBundles\Pattern\BatchProcessing;
4
5
/**
6
 * Class BatchProcessing.
7
 *
8
 * @author Dmitry Khaperets <[email protected]>
9
 */
10
class BatchProcessing implements BatchProcessingInterface
11
{
12
    /**
13
     * @var int
14
     */
15
    protected $count = 0;
16
17
    /**
18
     * @var array
19
     */
20
    protected $elements = [];
21
22
    /**
23
     * @var iterable
24
     */
25
    protected $iterator;
26
27
    /**
28
     * @var array
29
     */
30
    protected $listeners = [];
31
32
    /**
33
     * @var int
34
     */
35
    protected $batchSize = 0;
36
37
    /**
38
     * @param int      $batchSize
39
     * @param iterable $iterator
40
     */
41 2
    public function __construct(int $batchSize, iterable $iterator)
42
    {
43 2
        $this->setIterator($iterator);
44 2
        $this->setBatchSize($batchSize);
45 2
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 2
    public function setIterator(iterable $iterator): void
51
    {
52 2
        $this->iterator = $iterator;
53 2
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 2
    public function addListener(callable $listener): void
59
    {
60 2
        $this->listeners[] = $listener;
61 2
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 2
    public function setBatchSize(int $batchSize): void
67
    {
68 2
        $this->batchSize = $batchSize;
69 2
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74 2
    public function process(): \Generator
75
    {
76 2
        foreach ($this->iterator as $element) {
77 2
            $this->elements[] = $element;
78
79 2
            if (++$this->count >= $this->batchSize) {
80 2
                yield from $this->callListeners();
81
            }
82
        }
83
84 2
        if ($this->count > 0) {
85 2
            yield from $this->callListeners();
86
        }
87 2
    }
88
89
    /**
90
     * @return \Generator
91
     */
92 2
    protected function callListeners(): \Generator
93
    {
94 2
        foreach ($this->listeners as $listener) {
95 2
            yield $listener($this->elements);
96
        }
97
98 2
        $this->count = 0;
99 2
        $this->elements = [];
100 2
    }
101
}
102