Completed
Branch master (c971cd)
by Andrea Marco
03:24 queued 01:30
created

ChunkListener::endObject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Cerbero\JsonObjects\Listeners;
4
5
/**
6
 * The chunk listener.
7
 *
8
 */
9
class ChunkListener extends AbstractListener
10
{
11
    /**
12
     * The size of the chunk.
13
     *
14
     * @var int
15
     */
16
    protected $size;
17
18
    /**
19
     * The callback processing the chunk.
20
     *
21
     * @var callable
22
     */
23
    protected $callback;
24
25
    /**
26
     * The chunk of objects.
27
     *
28
     * @var array
29
     */
30
    protected $chunk = [];
31
32
    /**
33
     * Set the dependencies.
34
     *
35
     * @param int $size
36
     * @param callable $callback
37
     */
38 9
    public function __construct(int $size, callable $callback)
39
    {
40 9
        $this->size = $size;
41 9
        $this->callback = $callback;
42 9
    }
43
44
    /**
45
     * Listen to the end of the object.
46
     *
47
     * @return void
48
     */
49 9
    public function endObject() : void
50
    {
51 9
        parent::endObject();
52
53 9
        if (count($this->chunk) === $this->size) {
54 9
            call_user_func($this->callback, $this->chunk);
55
            $this->chunk = [];
56
        }
57 9
    }
58
59
    /**
60
     * Process the given extracted object.
61
     *
62
     * @param array $object
63
     * @return void
64
     */
65 9
    protected function processExtractedObject(array $object) : void
66
    {
67 9
        $this->chunk[] = $object;
68 9
    }
69
70
    /**
71
     * Listen to the end of the document.
72
     *
73
     * @return void
74
     */
75
    public function endDocument() : void
76
    {
77
        if (!empty($this->chunk)) {
78
            call_user_func($this->callback, $this->chunk);
79
            $this->chunk = [];
80
        }
81
82
        parent::endDocument();
83
    }
84
}
85