BufferJsonEncoder::next()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Violet\StreamingJsonEncoder;
4
5
/**
6
 * Encodes the given value as JSON and returns encoding result step by step.
7
 *
8
 * @author Riikka Kalliomäki <[email protected]>
9
 * @copyright Copyright (c) 2016-2020 Riikka Kalliomäki
10
 * @license http://opensource.org/licenses/mit-license.php MIT License
11
 */
12
class BufferJsonEncoder extends AbstractJsonEncoder
13
{
14
    /** @var string The encoded JSON in the current step */
15
    private $buffer;
16
17
    /**
18
     * Encodes the entire value as JSON and returns the value as a string.
19
     * @return string The encoded JSON
20
     */
21
    public function encode()
22
    {
23
        $json = [];
24
25
        foreach ($this as $string) {
26
            $json[] = $string;
27
        }
28
29
        return implode($json);
30
    }
31
32
    /** {@inheritdoc} */
33
    public function rewind()
34
    {
35
        $this->buffer = '';
36
37
        parent::rewind();
38
    }
39
40
    /** {@inheritdoc} */
41
    public function next()
42
    {
43
        $this->buffer = '';
44
45
        parent::next();
46
    }
47
48
    /**
49
     * Returns the JSON encoded in the current step.
50
     * @return string|null The currently encoded JSON or null if the state is not valid
51
     */
52
    public function current()
53
    {
54
        return $this->valid() ? $this->buffer : null;
55
    }
56
57
    /**
58
     * Writes the JSON output to the step buffer.
59
     * @param string $string The JSON string to write
60
     * @param int $token The type of the token
61
     */
62
    protected function write($string, $token)
63
    {
64
        $this->buffer .= $string;
65
    }
66
}
67