Passed
Push — master ( f6033e...966d85 )
by kacper
05:24
created

JsonBinaryDecoderFormatter::escapeJsonString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace MySQLReplication\JsonBinaryDecoder;
5
6
/**
7
 * Class JsonBinaryDecoderFormatter
8
 * @package MySQLReplication\JsonBinaryDecoder
9
 */
10
class JsonBinaryDecoderFormatter
11
{
12
    /**
13
     * @var string
14
     */
15
    public $jsonString = '';
16
17
    /**
18
     * @param bool $bool
19
     */
20
    public function formatValueBool($bool)
21
    {
22
        $this->jsonString .= var_export($bool, true);
23
    }
24
25
    /**
26
     * @param int $val
27
     */
28
    public function formatValueNumeric($val)
29
    {
30
        $this->jsonString .= $val;
31
    }
32
33
    /**
34
     * @param string $val
35
     */
36
    public function formatValue($val)
37
    {
38
        $this->jsonString .= '"' . self::escapeJsonString($val) . '"';
39
    }
40
41
    public function formatEndObject()
42
    {
43
        $this->jsonString .= '}';
44
    }
45
46
    public function formatBeginArray()
47
    {
48
        $this->jsonString .= '[';
49
    }
50
51
    public function formatEndArray()
52
    {
53
        $this->jsonString .= ']';
54
    }
55
56
    public function formatBeginObject()
57
    {
58
        $this->jsonString .= '{';
59
    }
60
61
    public function formatNextEntry()
62
    {
63
        $this->jsonString .= ',';
64
    }
65
66
    /**
67
     * @param string $name
68
     */
69
    public function formatName($name)
70
    {
71
        $this->jsonString .= '"' . $name . '":';
72
    }
73
74
    public function formatValueNull()
75
    {
76
        $this->jsonString .= 'null';
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function getJsonString()
83
    {
84
        return $this->jsonString;
85
    }
86
87
    /**
88
     * Some characters needs to be escaped
89
     * @see http://www.json.org/
90
     * @see https://stackoverflow.com/questions/1048487/phps-json-encode-does-not-escape-all-json-control-characters
91
     * @param string $value
92
     * @return string
93
     */
94
    private static function escapeJsonString($value)
95
    {
96
        return str_replace(
97
            ["\\", '/', '"', "\n", "\r", "\t", "\x08", "\x0c"],
98
            ["\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b"],
99
            $value
100
        );
101
    }
102
}