-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathAbstractJsonEncoder.php
More file actions
476 lines (402 loc) · 13.2 KB
/
AbstractJsonEncoder.php
File metadata and controls
476 lines (402 loc) · 13.2 KB
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
<?php
namespace Violet\StreamingJsonEncoder;
/**
* Abstract encoder for encoding JSON iteratively.
*
* @author Riikka Kalliomäki <riikka.kalliomaki@gmail.com>
* @copyright Copyright (c) 2016-2020 Riikka Kalliomäki
* @license http://opensource.org/licenses/mit-license.php MIT License
*/
abstract class AbstractJsonEncoder implements \Iterator
{
/** @var \Iterator[] Current value stack in encoding */
private $stack;
/** @var bool[] True for every object in the stack, false for an array */
private $stackType;
/** @var array Stack of values being encoded */
private $valueStack;
/** @var bool Whether the next value is the first value in an array or an object */
private $first;
/** @var int The JSON encoding options */
private $options;
/** @var bool Whether next token should be preceded by new line or not */
private $newLine;
/** @var string Indent to use for indenting JSON output */
private $indent;
/** @var string[] Errors that occurred in encoding */
private $errors;
/** @var int Number of the current line in output */
private $line;
/** @var int Number of the current column in output */
private $column;
/** @var mixed The initial value to encode as JSON */
private $initialValue;
/** @var int|null The current step of the encoder */
private $step;
/**
* AbstractJsonEncoder constructor.
* @param mixed $value The value to encode as JSON
*/
public function __construct($value)
{
$this->initialValue = $value;
$this->options = 0;
$this->errors = [];
$this->indent = ' ';
}
/**
* Sets the JSON encoding options.
* @param int $options The JSON encoding options that are used by json_encode
* @return $this Returns self for call chaining
* @throws \RuntimeException If changing encoding options during encoding operation
*/
public function setOptions($options)
{
if ($this->step !== null) {
throw new \RuntimeException('Cannot change encoding options during encoding');
}
$this->options = (int) $options;
return $this;
}
/**
* Sets the indent for the JSON output.
* @param string|int $indent A string to use as indent or the number of spaces
* @return $this Returns self for call chaining
* @throws \RuntimeException If changing indent during encoding operation
*/
public function setIndent($indent)
{
if ($this->step !== null) {
throw new \RuntimeException('Cannot change indent during encoding');
}
$this->indent = is_int($indent) ? str_repeat(' ', $indent) : (string) $indent;
return $this;
}
/**
* Returns the list of errors that occurred during the last encoding process.
* @return string[] List of errors that occurred during encoding
*/
public function getErrors()
{
return $this->errors;
}
/**
* Returns the current encoding value stack.
* @return array The current encoding value stack
*/
protected function getValueStack()
{
return $this->valueStack;
}
/**
* Initializes the iterator if it has not been initialized yet.
*/
private function initialize()
{
if (!isset($this->stack)) {
$this->rewind();
}
}
/**
* Returns the current number of step in the encoder.
* @return int|null The current step number as integer or null if the current state is not valid
*/
#[\ReturnTypeWillChange]
public function key()
{
$this->initialize();
return $this->step;
}
/**
* Tells if the encoder has a valid current state.
* @return bool True if the iterator has a valid state, false if not
*/
#[\ReturnTypeWillChange]
public function valid()
{
$this->initialize();
return $this->step !== null;
}
/**
* Returns the current value or state from the encoder.
* @return mixed The current value or state from the encoder
*/
#[\ReturnTypeWillChange]
abstract public function current();
/**
* Returns the JSON encoding to the beginning.
*/
#[\ReturnTypeWillChange]
public function rewind()
{
if ($this->step === 0) {
return;
}
$this->stack = [];
$this->stackType = [];
$this->valueStack = [];
$this->errors = [];
$this->newLine = false;
$this->first = true;
$this->line = 1;
$this->column = 1;
$this->step = 0;
$this->processValue($this->initialValue);
}
/**
* Iterates the next token or tokens to the output stream.
*/
#[\ReturnTypeWillChange]
public function next()
{
$this->initialize();
if (!empty($this->stack)) {
$this->step++;
$iterator = end($this->stack);
if ($iterator->valid()) {
$this->processStack($iterator, end($this->stackType));
$iterator->next();
} else {
$this->popStack();
}
} else {
$this->step = null;
}
}
/**
* Handles the next value from the iterator to be encoded as JSON.
* @param \Iterator $iterator The iterator used to generate the next value
* @param bool $isObject True if the iterator is being handled as an object, false if not
*/
private function processStack(\Iterator $iterator, $isObject)
{
if ($isObject) {
if (!$this->processKey($iterator->key())) {
return;
}
} elseif (!$this->first) {
$this->outputLine(',', JsonToken::T_COMMA);
}
$this->first = false;
$this->processValue($iterator->current());
}
/**
* Handles the given value key into JSON.
* @param mixed $key The key to process
* @return bool True if the key is valid, false if not
*/
private function processKey($key)
{
if (!is_int($key) && !is_string($key)) {
$this->addError('Only string or integer keys are supported');
return false;
}
if (!$this->first) {
$this->outputLine(',', JsonToken::T_COMMA);
}
$this->outputJson((string) $key, JsonToken::T_NAME);
$this->output(':', JsonToken::T_COLON);
if ($this->options & JSON_PRETTY_PRINT) {
$this->output(' ', JsonToken::T_WHITESPACE);
}
return true;
}
/**
* Handles the given JSON value appropriately depending on it's type.
* @param mixed $value The value that should be encoded as JSON
*/
private function processValue($value)
{
$this->valueStack[] = $value;
$value = $this->resolveValue($value);
if (is_array($value) || is_object($value)) {
$this->pushStack($value);
} else {
$this->outputJson($value, JsonToken::T_VALUE);
array_pop($this->valueStack);
}
}
/**
* Resolves the actual value of any given value that is about to be processed.
* @param mixed $value The value to resolve
* @return mixed The resolved value
*/
protected function resolveValue($value)
{
do {
if ($value instanceof \JsonSerializable) {
$value = $value->jsonSerialize();
} elseif ($value instanceof \Closure) {
$value = $value();
} else {
break;
}
} while (true);
return $value;
}
/**
* Adds an JSON encoding error to the list of errors.
* @param string $message The error message to add
* @throws EncodingException If the encoding should not continue due to the error
*/
private function addError($message)
{
$errorMessage = sprintf('Line %d, column %d: %s', $this->line, $this->column, $message);
$this->errors[] = $errorMessage;
if ($this->options & JSON_PARTIAL_OUTPUT_ON_ERROR) {
return;
}
$this->stack = [];
$this->step = null;
throw new EncodingException($errorMessage);
}
/**
* Pushes the given iterable to the value stack.
* @param object|array $iterable The iterable value to push to the stack
*/
private function pushStack($iterable)
{
$iterator = $this->getIterator($iterable);
$isObject = $this->isObject($iterable, $iterator);
if ($isObject) {
$this->outputLine('{', JsonToken::T_LEFT_BRACE);
} else {
$this->outputLine('[', JsonToken::T_LEFT_BRACKET);
}
$this->first = true;
$this->stack[] = $iterator;
$this->stackType[] = $isObject;
}
/**
* Creates a generator from the given iterable using a foreach loop.
* @param object|array $iterable The iterable value to iterate
* @return \Generator The generator using the given iterable
*/
private function getIterator($iterable)
{
foreach ($iterable as $key => $value) {
yield $key => $value;
}
}
/**
* Tells if the given iterable should be handled as a JSON object or not.
* @param object|array $iterable The iterable value to test
* @param \Iterator $iterator An Iterator created from the iterable value
* @return bool True if the given iterable should be treated as object, false if not
*/
private function isObject($iterable, \Iterator $iterator)
{
if ($this->options & JSON_FORCE_OBJECT) {
return true;
}
if ($iterable instanceof \Traversable) {
return $iterator->valid() && $iterator->key() !== 0;
}
return is_object($iterable) || $this->isAssociative($iterable);
}
/**
* Tells if the given array is an associative array.
* @param array $array The array to test
* @return bool True if the array is associative, false if not
*/
private function isAssociative(array $array)
{
if ($array === []) {
return false;
}
$expected = 0;
foreach ($array as $key => $_) {
if ($key !== $expected++) {
return true;
}
}
return false;
}
/**
* Removes the top element of the value stack.
*/
private function popStack()
{
if (!$this->first) {
$this->newLine = true;
}
$this->first = false;
array_pop($this->stack);
if (array_pop($this->stackType)) {
$this->output('}', JsonToken::T_RIGHT_BRACE);
} else {
$this->output(']', JsonToken::T_RIGHT_BRACKET);
}
array_pop($this->valueStack);
}
/**
* Encodes the given value as JSON and passes it to output stream.
* @param mixed $value The value to output as JSON
* @param int $token The token type of the value
*/
private function outputJson($value, $token)
{
$encoded = json_encode($value, $this->options);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
$this->addError(sprintf('%s (%s)', json_last_error_msg(), $this->getJsonErrorConstantName($error)));
}
$this->output($encoded, $token);
}
/**
* Returns the name of the JSON error constant.
* @param int $error The error code to find
* @return string The name for the error code
*/
private function getJsonErrorConstantName($error)
{
$matches = array_keys(get_defined_constants(true)['json'], $error, true);
$prefix = 'JSON_ERROR_';
$prefixLength = strlen($prefix);
$name = 'UNKNOWN_ERROR';
foreach ($matches as $match) {
if (is_string($match) && strncmp($match, $prefix, $prefixLength) === 0) {
$name = $match;
break;
}
}
return $name;
}
/**
* Passes the given token to the output stream and ensures the next token is preceded by a newline.
* @param string $string The token to write to the output stream
* @param int $token The type of the token
*/
private function outputLine($string, $token)
{
$this->output($string, $token);
$this->newLine = true;
}
/**
* Passes the given token to the output stream.
* @param string $string The token to write to the output stream
* @param int $token The type of the token
*/
private function output($string, $token)
{
if ($this->newLine && $this->options & JSON_PRETTY_PRINT) {
$indent = str_repeat($this->indent, count($this->stack));
$this->write("\n", JsonToken::T_WHITESPACE);
if ($indent !== '') {
$this->write($indent, JsonToken::T_WHITESPACE);
}
$this->line++;
$this->column = strlen($indent) + 1;
}
$this->newLine = false;
$this->write($string, $token);
$this->column += strlen($string);
}
/**
* Actually handles the writing of the given token to the output stream.
* @param string $string The given token to write
* @param int $token The type of the token
* @return void
*/
abstract protected function write($string, $token);
}