BatchWriter::prepare()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Ddeboer\DataImport\Writer;
4
5
use Ddeboer\DataImport\Writer;
6
7
/**
8
 * @author Markus Bachmann <[email protected]>
9
 */
10
class BatchWriter implements Writer
11
{
12
    private $delegate;
13
14
    private $size;
15
16
    private $queue;
17
18 2
    public function __construct(Writer $delegate, $size = 20)
19
    {
20 2
        $this->delegate = $delegate;
21 2
        $this->size = $size;
22 2
    }
23
24 2
    public function prepare()
25
    {
26 2
        $this->delegate->prepare();
27
28 2
        $this->queue = new \SplQueue();
29 2
        $this->queue->setIteratorMode(\SplDoublyLinkedList::IT_MODE_DELETE);
30 2
    }
31
32 2
    public function writeItem(array $item)
33
    {
34 2
        $this->queue->push($item);
35
36 2
        if (count($this->queue) >= $this->size) {
37 1
            $this->flush();
38 1
        }
39 2
    }
40
41
    public function finish()
42
    {
43
        $this->flush();
44
45
        $this->delegate->finish();
46
    }
47
48 1
    private function flush()
49
    {
50 1
        foreach ($this->queue as $item) {
51 1
            $this->delegate->writeItem($item);
52 1
        }
53
54 1
        if ($this->delegate instanceof FlushableWriter) {
55
            $this->delegate->flush();
56
        }
57 1
    }
58
}
59