-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonEncoder.php
124 lines (107 loc) · 2.9 KB
/
JsonEncoder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Json;
/**
* JSON Encoder will encode data to a json string.
*
* @author Joshua Estes <[email protected]>
*/
class JsonEncoder extends AbstractEncoderDecoder
{
public function encode($value): string
{
$return = json_encode($value, $this->flags, $this->depth);
if (\JSON_ERROR_NONE !== json_last_error()) {
throw new JsonException(json_last_error_msg(), json_last_error());
}
return $return;
}
/**
* Outputs an object rather than an array when a non-associative array is
* used. Especially useful when the recipient of the output is expecting an
* object and the array is empty.
*/
public function forceObject(): static
{
return $this->withFlags(\JSON_FORCE_OBJECT);
}
/**
* All " are converted to \u0022.
*/
public function hexQuot(): static
{
return $this->withFlags(\JSON_HEX_QUOT);
}
/**
* All < and > are converted to \u003C and \u003E.
*/
public function hexTag(): static
{
return $this->withFlags(\JSON_HEX_TAG);
}
/**
* All & are converted to \u0026.
*/
public function hexAmp(): static
{
return $this->withFlags(\JSON_HEX_AMP);
}
/**
* All ' are converted to \u0027.
*/
public function hexApos(): static
{
return $this->withFlags(\JSON_HEX_APOS);
}
/**
* Encodes numeric strings as numbers.
*/
public function numericCheck(): static
{
return $this->withFlags(\JSON_NUMERIC_CHECK);
}
/**
* Substitute some unencodable values instead of failing.
*/
public function partialOutputOnError(): static
{
return $this->withFlags(\JSON_PARTIAL_OUTPUT_ON_ERROR);
}
/**
* Ensures that float values are always encoded as a float value.
*/
public function preserveZeroFraction(): static
{
return $this->withFlags(\JSON_PRESERVE_ZERO_FRACTION);
}
/**
* Use whitespace in returned data to format it.
*/
public function prettyPrint(): static
{
return $this->withFlags(\JSON_PRETTY_PRINT);
}
/**
* The line terminators are kept unescaped when JSON_UNESCAPED_UNICODE is
* supplied. It uses the same behaviour as it was before PHP 7.1 without
* this constant. Available as of PHP 7.1.0.
*/
public function unescapedLineTerminators(): static
{
return $this->withFlags(\JSON_UNESCAPED_LINE_TERMINATORS);
}
/**
* Don't escape /.
*/
public function unescapedSlashes(): static
{
return $this->withFlags(\JSON_UNESCAPED_SLASHES);
}
/**
* Encode multibyte Unicode characters literally (default is to escape as \uXXXX).
*/
public function unescapedUnicode(): static
{
return $this->withFlags(\JSON_UNESCAPED_UNICODE);
}
}