JsonWriter   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 0
dl 0
loc 74
c 0
b 0
f 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __destruct() 0 4 1
A initialize() 0 10 2
A finalize() 0 9 2
A push() 0 18 5
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\Service\Json;
13
14
/**
15
 * Serializes records one by one. Outputs given metadata before first record.
16
 *
17
 * Sample output:
18
 * <p>
19
 * [
20
 * {"count":2},
21
 * {"_id":"doc1","title":"Document 1"},
22
 * {"_id":"doc2","title":"Document 2"}
23
 * ]
24
 * </p>
25
 */
26
class JsonWriter
27
{
28
    private $filename;
29
    private $handle;
30
    private $count;
31
    private $currentPosition = 0;
32
33
    public function __construct(string $filename, int $count)
34
    {
35
        $this->filename = $filename;
36
        $this->count = $count;
37
    }
38
39
    /**
40
     * Destructor. Closes file handler if open.
41
     */
42
    public function __destruct()
43
    {
44
        $this->finalize();
45
    }
46
47
    /**
48
     * Performs initialization.
49
     */
50
    protected function initialize()
51
    {
52
        if ($this->handle !== null) {
53
            return;
54
        }
55
56
        $this->handle = fopen($this->filename, 'w');
57
        fwrite($this->handle, "[\n");
58
        fwrite($this->handle, json_encode(['count' => $this->count]));
59
    }
60
61
    /**
62
     * Performs finalization.
63
     */
64
    public function finalize()
65
    {
66
        $this->initialize();
67
68
        if (is_resource($this->handle)) {
69
            fwrite($this->handle, "\n]");
70
            fclose($this->handle);
71
        }
72
    }
73
74
    /**
75
     * Writes single document to stream.
76
     *
77
     * @param mixed $document Object to insert into stream.
78
     *
79
     * @throws \OverflowException
80
     */
81
    public function push($document)
82
    {
83
        $this->initialize();
84
        $this->currentPosition++;
85
86
        if (isset($this->count) && $this->currentPosition > $this->count) {
87
            throw new \OverflowException(
88
                sprintf('This writer was set up to write %d documents, got more.', $this->count)
89
            );
90
        }
91
92
        fwrite($this->handle, ",\n");
93
        fwrite($this->handle, json_encode($document));
94
95
        if (isset($this->count) && $this->currentPosition == $this->count) {
96
            $this->finalize();
97
        }
98
    }
99
}
100