ChunkListener   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 70
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A endObject() 0 15 3
A endDocument() 0 6 1
A processChunk() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace JsonCollectionParser;
6
7
class ChunkListener extends Listener
8
{
9
    /**
10
     * The size of the chunk.
11
     *
12
     * @var int
13
     */
14
    protected $size;
15
16
    /**
17
     * The callback processing the chunk.
18
     *
19
     * @var callable
20
     */
21
    protected $callback;
22
23
    /**
24
     * The chunk of objects.
25
     *
26
     * @var array
27
     */
28
    protected $chunk;
29
30
    /**
31
     * @param int               $size size of the chunk to collect before processing
32
     * @param callback|callable $callback callback for parsed collection item
33
     * @param bool              $assoc    When true, returned objects will be converted into associative arrays
34
     */
35
    public function __construct(int $size, callable $callback, bool $assoc = true)
36
    {
37
        parent::__construct($callback, $assoc);
38
39
        $this->size  = $size;
40
        $this->chunk = [];
41
    }
42
43
    public function endObject(): void
44
    {
45
        $this->endCommon();
46
47
        $this->objectLevel--;
48
        if ($this->objectLevel === 0) {
49
            $obj = array_pop($this->stack);
50
51
            $this->chunk[] = reset($obj);
52
        }
53
54
        if (count($this->chunk) === $this->size) {
55
            $this->processChunk();
56
        }
57
    }
58
59
    public function endDocument(): void
60
    {
61
        $this->processChunk();
62
63
        parent::endDocument();
64
    }
65
66
    protected function processChunk(): void
67
    {
68
        if (empty($this->chunk)) {
69
            return;
70
        }
71
72
        call_user_func($this->callback, $this->chunk);
73
74
        $this->chunk = [];
75
    }
76
}
77