JsonEncoder::encode()   F
last analyzed

Complexity

Conditions 24
Paths > 20000

Size

Total Lines 101
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 24.0445

Importance

Changes 7
Bugs 3 Features 1
Metric Value
c 7
b 3
f 1
dl 0
loc 101
ccs 45
cts 47
cp 0.9574
rs 2
cc 24
eloc 49
nc 103681
nop 2
crap 24.0445

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the Webmozart JSON package.
5
 *
6
 * (c) Bernhard Schussek <[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 Webmozart\Json;
13
14
/**
15
 * Encodes data as JSON.
16
 *
17
 * @since  1.0
18
 *
19
 * @author Bernhard Schussek <[email protected]>
20
 */
21
class JsonEncoder
22
{
23
    /**
24
     * Encode a value as JSON array.
25
     */
26
    const JSON_ARRAY = 1;
27
28
    /**
29
     * Encode a value as JSON object.
30
     */
31
    const JSON_OBJECT = 2;
32
33
    /**
34
     * Encode a value as JSON string.
35
     */
36
    const JSON_STRING = 3;
37
38
    /**
39
     * Encode a value as JSON integer or float.
40
     */
41
    const JSON_NUMBER = 4;
42
43
    /**
44
     * @var JsonValidator
45
     */
46
    private $validator;
47
48
    /**
49
     * @var int
50
     */
51
    private $arrayEncoding = self::JSON_ARRAY;
52
53
    /**
54
     * @var int
55
     */
56
    private $numericEncoding = self::JSON_STRING;
57
58
    /**
59
     * @var bool
60
     */
61
    private $gtLtEscaped = false;
62
63
    /**
64
     * @var bool
65
     */
66
    private $ampersandEscaped = false;
67
68
    /**
69
     * @var bool
70
     */
71
    private $singleQuoteEscaped = false;
72
73
    /**
74
     * @var bool
75
     */
76
    private $doubleQuoteEscaped = false;
77
78
    /**
79
     * @var bool
80
     */
81
    private $slashEscaped = true;
82
83
    /**
84
     * @var bool
85
     */
86
    private $unicodeEscaped = true;
87
88
    /**
89
     * @var bool
90
     */
91
    private $prettyPrinting = false;
92
93
    /**
94
     * @var bool
95
     */
96
    private $terminatedWithLineFeed = false;
97
98
    /**
99
     * @var int
100
     */
101
    private $maxDepth = 512;
102
103
    /**
104
     * Creates a new encoder.
105
     *
106
     * @param null|JsonValidator $validator
107
     */
108 61
    public function __construct(JsonValidator $validator = null)
109
    {
110 61
        $this->validator = $validator ?: new JsonValidator();
111 61
    }
112
113
    /**
114
     * Encodes data as JSON.
115
     *
116
     * If a schema is passed, the value is validated against that schema before
117
     * encoding. The schema may be passed as file path or as object returned
118
     * from `JsonDecoder::decodeFile($schemaFile)`.
119
     *
120
     * You can adjust the decoding with the various setters in this class.
121
     *
122
     * @param mixed         $data   The data to encode
123
     * @param string|object $schema The schema file or object
0 ignored issues
show
Documentation introduced by
Should the type for parameter $schema not be string|object|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
124
     *
125
     * @return string The JSON string
126
     *
127
     * @throws EncodingFailedException   If the data could not be encoded
128
     * @throws ValidationFailedException If the data fails schema validation
129
     * @throws InvalidSchemaException    If the schema is invalid
130
     */
131 53
    public function encode($data, $schema = null)
132
    {
133 53
        if (null !== $schema) {
134 6
            $errors = $this->validator->validate($data, $schema);
135
136 6
            if (count($errors) > 0) {
137 4
                throw ValidationFailedException::fromErrors($errors);
138
            }
139
        }
140
141 49
        $options = 0;
142
143 49
        if (self::JSON_OBJECT === $this->arrayEncoding) {
144 1
            $options |= JSON_FORCE_OBJECT;
145
        }
146
147 49
        if (self::JSON_NUMBER === $this->numericEncoding) {
148 2
            $options |= JSON_NUMERIC_CHECK;
149
        }
150
151 49
        if ($this->gtLtEscaped) {
152 1
            $options |= JSON_HEX_TAG;
153
        }
154
155 49
        if ($this->ampersandEscaped) {
156 1
            $options |= JSON_HEX_AMP;
157
        }
158
159 49
        if ($this->singleQuoteEscaped) {
160 1
            $options |= JSON_HEX_APOS;
161
        }
162
163 49
        if ($this->doubleQuoteEscaped) {
164 1
            $options |= JSON_HEX_QUOT;
165
        }
166
167 49
        if (PHP_VERSION_ID >= 50400) {
168 49
            if (!$this->slashEscaped) {
169 1
                $options |= JSON_UNESCAPED_SLASHES;
170
            }
171
172 49
            if (!$this->unicodeEscaped) {
173 1
                $options |= JSON_UNESCAPED_UNICODE;
174
            }
175
176 49
            if ($this->prettyPrinting) {
177 1
                $options |= JSON_PRETTY_PRINT;
178
            }
179
        }
180
181 49
        if (PHP_VERSION_ID < 71000) {
182
            // PHP before 7.1 decodes empty properties as "_empty_". Make
183
            // sure the encoding of these properties works again.
184 49
            if (is_object($data) && isset($data->{'_empty_'})) {
185 1
                $data = (array) $data;
186
            }
187
188 49
            if (is_array($data) && isset($data['_empty_'])) {
189
                // Maintain key order
190 1
                $keys = array_keys($data);
191 1
                $keys[array_search('_empty_', $keys, true)] = '';
192 1
                $data = array_combine($keys, $data);
193
            }
194
        }
195
196 49
        if (PHP_VERSION_ID >= 50500) {
197 49
            $maxDepth = $this->maxDepth;
198
199
            // We subtract 1 from the max depth to make JsonDecoder and
200
            // JsonEncoder consistent. json_encode() and json_decode() behave
201
            // differently for their depth values. See the test cases for
202
            // examples.
203
            // HHVM does not have this inconsistency.
204 49
            if (!defined('HHVM_VERSION')) {
205 49
                --$maxDepth;
206
            }
207
208 49
            $encoded = json_encode($data, $options, $maxDepth);
209
        } else {
210
            $encoded = json_encode($data, $options);
211
        }
212
213 49
        if (PHP_VERSION_ID < 50400 && !$this->slashEscaped) {
214
            // PHP below 5.4 does not allow to turn off slash escaping. Let's
215
            // unescape slashes manually.
216
            $encoded = str_replace('\\/', '/', $encoded);
217
        }
218
219 49
        if (JSON_ERROR_NONE !== json_last_error()) {
220 5
            throw new EncodingFailedException(sprintf(
221 5
                'The data could not be encoded as JSON: %s',
222 5
                JsonError::getLastErrorMessage()
223
            ), json_last_error());
224
        }
225
226 44
        if ($this->terminatedWithLineFeed) {
227 1
            $encoded .= "\n";
228
        }
229
230 44
        return $encoded;
231
    }
232
233
    /**
234
     * Encodes data into a JSON file.
235
     *
236
     * @param mixed         $data   The data to encode
237
     * @param string        $path   The path where the JSON file will be stored
238
     * @param string|object $schema The schema file or object
0 ignored issues
show
Documentation introduced by
Should the type for parameter $schema not be string|object|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
239
     *
240
     * @throws EncodingFailedException   If the data could not be encoded
241
     * @throws ValidationFailedException If the data fails schema validation
242
     * @throws InvalidSchemaException    If the schema is invalid
243
     *
244
     * @see encode
245
     */
246 6
    public function encodeFile($data, $path, $schema = null)
247
    {
248 6
        if (!file_exists($dir = dirname($path))) {
249 1
            mkdir($dir, 0777, true);
250
        }
251
252
        try {
253
            // Right now, it's sufficient to just write the file. In the future,
254
            // this will diff existing files with the given data and only do
255
            // in-place modifications where necessary.
256 6
            $content = $this->encode($data, $schema);
257 3
        } catch (EncodingFailedException $e) {
258
            // Add the file name to the exception
259 1
            throw new EncodingFailedException(sprintf(
260 1
                'An error happened while encoding %s: %s',
261
                $path,
262 1
                $e->getMessage()
263 1
            ), $e->getCode(), $e);
264 2
        } catch (ValidationFailedException $e) {
265
            // Add the file name to the exception
266 2
            throw new ValidationFailedException(sprintf(
267 2
                "Validation failed while encoding %s:\n%s",
268
                $path,
269 2
                $e->getErrorsAsString()
270 2
            ), $e->getErrors(), $e->getCode(), $e);
271
        } catch (InvalidSchemaException $e) {
272
            // Add the file name to the exception
273
            throw new InvalidSchemaException(sprintf(
274
                'An error happened while encoding %s: %s',
275
                $path,
276
                $e->getMessage()
277
            ), $e->getCode(), $e);
278
        }
279
280 3
        $errorMessage = null;
281 3
        $errorCode = 0;
282
283 3
        set_error_handler(function ($errno, $errstr) use (&$errorMessage, &$errorCode) {
284 1
            $errorMessage = $errstr;
285 1
            $errorCode = $errno;
286 3
        });
287
288 3
        file_put_contents($path, $content);
289
290 3
        restore_error_handler();
291
292 3 View Code Duplication
        if (null !== $errorMessage) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
293 1
            if (false !== $pos = strpos($errorMessage, '): ')) {
294
                // cut "file_put_contents(%path%):" to make message more readable
295 1
                $errorMessage = substr($errorMessage, $pos + 3);
296
            }
297
298 1
            throw new IOException(sprintf(
299 1
                'Could not write %s: %s (%s)',
300
                $path,
301
                $errorMessage,
302
                $errorCode
303
            ), $errorCode);
304
        }
305 2
    }
306
307
    /**
308
     * Returns the encoding of non-associative arrays.
309
     *
310
     * @return int One of the constants {@link JSON_OBJECT} and {@link JSON_ARRAY}
311
     */
312
    public function getArrayEncoding()
313
    {
314
        return $this->arrayEncoding;
315
    }
316
317
    /**
318
     * Sets the encoding of non-associative arrays.
319
     *
320
     * By default, non-associative arrays are decoded as JSON arrays.
321
     *
322
     * @param int $encoding One of the constants {@link JSON_OBJECT} and {@link JSON_ARRAY}
323
     *
324
     * @throws \InvalidArgumentException If the passed encoding is invalid
325
     */
326 5 View Code Duplication
    public function setArrayEncoding($encoding)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
327
    {
328 5
        if (self::JSON_ARRAY !== $encoding && self::JSON_OBJECT !== $encoding) {
329 3
            throw new \InvalidArgumentException(sprintf(
330
                'Expected JsonEncoder::JSON_ARRAY or JsonEncoder::JSON_OBJECT. '.
331 3
                'Got: %s',
332
                $encoding
333
            ));
334
        }
335
336 2
        $this->arrayEncoding = $encoding;
337 2
    }
338
339
    /**
340
     * Returns the encoding of numeric strings.
341
     *
342
     * @return int One of the constants {@link JSON_STRING} and {@link JSON_NUMBER}
343
     */
344
    public function getNumericEncoding()
345
    {
346
        return $this->numericEncoding;
347
    }
348
349
    /**
350
     * Sets the encoding of numeric strings.
351
     *
352
     * By default, non-associative arrays are decoded as JSON strings.
353
     *
354
     * @param int $encoding One of the constants {@link JSON_STRING} and {@link JSON_NUMBER}
355
     *
356
     * @throws \InvalidArgumentException If the passed encoding is invalid
357
     */
358 6 View Code Duplication
    public function setNumericEncoding($encoding)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
359
    {
360 6
        if (self::JSON_NUMBER !== $encoding && self::JSON_STRING !== $encoding) {
361 3
            throw new \InvalidArgumentException(sprintf(
362
                'Expected JsonEncoder::JSON_NUMBER or JsonEncoder::JSON_STRING. '.
363 3
                'Got: %s',
364
                $encoding
365
            ));
366
        }
367
368 3
        $this->numericEncoding = $encoding;
369 3
    }
370
371
    /**
372
     * Returns whether ampersands (&) are escaped.
373
     *
374
     * If `true`, ampersands will be escaped as "\u0026".
375
     *
376
     * By default, ampersands are not escaped.
377
     *
378
     * @return bool Whether ampersands are escaped
379
     */
380
    public function isAmpersandEscaped()
381
    {
382
        return $this->ampersandEscaped;
383
    }
384
385
    /**
386
     * Sets whether ampersands (&) should be escaped.
387
     *
388
     * If `true`, ampersands will be escaped as "\u0026".
389
     *
390
     * By default, ampersands are not escaped.
391
     *
392
     * @param bool $enabled Whether ampersands should be escaped
393
     */
394 2
    public function setEscapeAmpersand($enabled)
395
    {
396 2
        $this->ampersandEscaped = $enabled;
397 2
    }
398
399
    /**
400
     * Returns whether double quotes (") are escaped.
401
     *
402
     * If `true`, double quotes will be escaped as "\u0022".
403
     *
404
     * By default, double quotes are not escaped.
405
     *
406
     * @return bool Whether double quotes are escaped
407
     */
408
    public function isDoubleQuoteEscaped()
409
    {
410
        return $this->doubleQuoteEscaped;
411
    }
412
413
    /**
414
     * Sets whether double quotes (") should be escaped.
415
     *
416
     * If `true`, double quotes will be escaped as "\u0022".
417
     *
418
     * By default, double quotes are not escaped.
419
     *
420
     * @param bool $enabled Whether double quotes should be escaped
421
     */
422 2
    public function setEscapeDoubleQuote($enabled)
423
    {
424 2
        $this->doubleQuoteEscaped = $enabled;
425 2
    }
426
427
    /**
428
     * Returns whether single quotes (') are escaped.
429
     *
430
     * If `true`, single quotes will be escaped as "\u0027".
431
     *
432
     * By default, single quotes are not escaped.
433
     *
434
     * @return bool Whether single quotes are escaped
435
     */
436
    public function isSingleQuoteEscaped()
437
    {
438
        return $this->singleQuoteEscaped;
439
    }
440
441
    /**
442
     * Sets whether single quotes (") should be escaped.
443
     *
444
     * If `true`, single quotes will be escaped as "\u0027".
445
     *
446
     * By default, single quotes are not escaped.
447
     *
448
     * @param bool $enabled Whether single quotes should be escaped
449
     */
450 2
    public function setEscapeSingleQuote($enabled)
451
    {
452 2
        $this->singleQuoteEscaped = $enabled;
453 2
    }
454
455
    /**
456
     * Returns whether forward slashes (/) are escaped.
457
     *
458
     * If `true`, forward slashes will be escaped as "\/".
459
     *
460
     * By default, forward slashes are not escaped.
461
     *
462
     * @return bool Whether forward slashes are escaped
463
     */
464
    public function isSlashEscaped()
465
    {
466
        return $this->slashEscaped;
467
    }
468
469
    /**
470
     * Sets whether forward slashes (") should be escaped.
471
     *
472
     * If `true`, forward slashes will be escaped as "\/".
473
     *
474
     * By default, forward slashes are not escaped.
475
     *
476
     * @param bool $enabled Whether forward slashes should be escaped
477
     */
478 2
    public function setEscapeSlash($enabled)
479
    {
480 2
        $this->slashEscaped = $enabled;
481 2
    }
482
483
    /**
484
     * Returns whether greater than/less than symbols (>, <) are escaped.
485
     *
486
     * If `true`, greater than will be escaped as "\u003E" and less than as
487
     * "\u003C".
488
     *
489
     * By default, greater than/less than symbols are not escaped.
490
     *
491
     * @return bool Whether greater than/less than symbols are escaped
492
     */
493
    public function isGtLtEscaped()
494
    {
495
        return $this->gtLtEscaped;
496
    }
497
498
    /**
499
     * Sets whether greater than/less than symbols (>, <) should be escaped.
500
     *
501
     * If `true`, greater than will be escaped as "\u003E" and less than as
502
     * "\u003C".
503
     *
504
     * By default, greater than/less than symbols are not escaped.
505
     *
506
     * @param bool $enabled Whether greater than/less than should be escaped
507
     */
508 2
    public function setEscapeGtLt($enabled)
509
    {
510 2
        $this->gtLtEscaped = $enabled;
511 2
    }
512
513
    /**
514
     * Returns whether unicode characters are escaped.
515
     *
516
     * If `true`, unicode characters will be escaped as hexadecimals strings.
517
     * For example, "ü" will be escaped as "\u00fc".
518
     *
519
     * By default, unicode characters are escaped.
520
     *
521
     * @return bool Whether unicode characters are escaped
522
     */
523
    public function isUnicodeEscaped()
524
    {
525
        return $this->unicodeEscaped;
526
    }
527
528
    /**
529
     * Sets whether unicode characters should be escaped.
530
     *
531
     * If `true`, unicode characters will be escaped as hexadecimals strings.
532
     * For example, "ü" will be escaped as "\u00fc".
533
     *
534
     * By default, unicode characters are escaped.
535
     *
536
     * @param bool $enabled Whether unicode characters should be escaped
537
     */
538 2
    public function setEscapeUnicode($enabled)
539
    {
540 2
        $this->unicodeEscaped = $enabled;
541 2
    }
542
543
    /**
544
     * Returns whether JSON strings are formatted for better readability.
545
     *
546
     * If `true`, line breaks will be added after object properties and array
547
     * entries. Each new nesting level will be indented by four spaces.
548
     *
549
     * By default, pretty printing is not enabled.
550
     *
551
     * @return bool Whether JSON strings are formatted
552
     */
553
    public function isPrettyPrinting()
554
    {
555
        return $this->prettyPrinting;
556
    }
557
558
    /**
559
     * Sets whether JSON strings should be formatted for better readability.
560
     *
561
     * If `true`, line breaks will be added after object properties and array
562
     * entries. Each new nesting level will be indented by four spaces.
563
     *
564
     * By default, pretty printing is not enabled.
565
     *
566
     * @param bool $prettyPrinting Whether JSON strings should be formatted
567
     */
568 2
    public function setPrettyPrinting($prettyPrinting)
569
    {
570 2
        $this->prettyPrinting = $prettyPrinting;
571 2
    }
572
573
    /**
574
     * Returns whether JSON strings are terminated with a line feed.
575
     *
576
     * By default, JSON strings are not terminated with a line feed.
577
     *
578
     * @return bool Whether JSON strings are terminated with a line feed
579
     */
580
    public function isTerminatedWithLineFeed()
581
    {
582
        return $this->terminatedWithLineFeed;
583
    }
584
585
    /**
586
     * Sets whether JSON strings should be terminated with a line feed.
587
     *
588
     * By default, JSON strings are not terminated with a line feed.
589
     *
590
     * @param bool $enabled Whether JSON strings should be terminated with a
591
     *                      line feed
592
     */
593 2
    public function setTerminateWithLineFeed($enabled)
594
    {
595 2
        $this->terminatedWithLineFeed = $enabled;
596 2
    }
597
598
    /**
599
     * Returns the maximum recursion depth.
600
     *
601
     * A depth of zero means that objects are not allowed. A depth of one means
602
     * only one level of objects or arrays is allowed.
603
     *
604
     * @return int The maximum recursion depth
605
     */
606
    public function getMaxDepth()
607
    {
608
        return $this->maxDepth;
609
    }
610
611
    /**
612
     * Sets the maximum recursion depth.
613
     *
614
     * If the depth is exceeded during encoding, an {@link EncodingFailedException}
615
     * will be thrown.
616
     *
617
     * A depth of zero means that objects are not allowed. A depth of one means
618
     * only one level of objects or arrays is allowed.
619
     *
620
     * @param int $maxDepth The maximum recursion depth
621
     *
622
     * @throws \InvalidArgumentException If the depth is not an integer greater
623
     *                                   than or equal to zero
624
     */
625 6 View Code Duplication
    public function setMaxDepth($maxDepth)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
626
    {
627 6
        if (!is_int($maxDepth)) {
628 1
            throw new \InvalidArgumentException(sprintf(
629 1
                'The maximum depth should be an integer. Got: %s',
630 1
                is_object($maxDepth) ? get_class($maxDepth) : gettype($maxDepth)
631
            ));
632
        }
633
634 5
        if ($maxDepth < 1) {
635 1
            throw new \InvalidArgumentException(sprintf(
636 1
                'The maximum depth should 1 or greater. Got: %s',
637
                $maxDepth
638
            ));
639
        }
640
641 4
        $this->maxDepth = $maxDepth;
642 4
    }
643
}
644