Completed
Pull Request — master (#31)
by
unknown
03:20
created

JsonEncoder::setEscapeDoubleQuote()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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 && isset($data->{'$schema'})) {
134
            $schema = $data->{'$schema'};
135
        }
136
137 53 View Code Duplication
        if (null !== $schema) {
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...
138 6
            $errors = $this->validator->validate($data, $schema);
139
140 6
            if (count($errors) > 0) {
141 4
                throw ValidationFailedException::fromErrors($errors);
142
            }
143
        }
144
145 49
        $options = 0;
146
147 49
        if (self::JSON_OBJECT === $this->arrayEncoding) {
148 1
            $options |= JSON_FORCE_OBJECT;
149
        }
150
151 49
        if (self::JSON_NUMBER === $this->numericEncoding) {
152 2
            $options |= JSON_NUMERIC_CHECK;
153
        }
154
155 49
        if ($this->gtLtEscaped) {
156 1
            $options |= JSON_HEX_TAG;
157
        }
158
159 49
        if ($this->ampersandEscaped) {
160 1
            $options |= JSON_HEX_AMP;
161
        }
162
163 49
        if ($this->singleQuoteEscaped) {
164 1
            $options |= JSON_HEX_APOS;
165
        }
166
167 49
        if ($this->doubleQuoteEscaped) {
168 1
            $options |= JSON_HEX_QUOT;
169
        }
170
171 49
        if (PHP_VERSION_ID >= 50400) {
172 49
            if (!$this->slashEscaped) {
173 1
                $options |= JSON_UNESCAPED_SLASHES;
174
            }
175
176 49
            if (!$this->unicodeEscaped) {
177 1
                $options |= JSON_UNESCAPED_UNICODE;
178
            }
179
180 49
            if ($this->prettyPrinting) {
181 1
                $options |= JSON_PRETTY_PRINT;
182
            }
183
        }
184
185 49
        if (PHP_VERSION_ID < 71000) {
186
            // PHP before 7.1 decodes empty properties as "_empty_". Make
187
            // sure the encoding of these properties works again.
188 49
            if (is_object($data) && isset($data->{'_empty_'})) {
189 1
                $data = (array) $data;
190
            }
191
192 49
            if (is_array($data) && isset($data['_empty_'])) {
193
                // Maintain key order
194 1
                $keys = array_keys($data);
195 1
                $keys[array_search('_empty_', $keys, true)] = '';
196 1
                $data = array_combine($keys, $data);
197
            }
198
        }
199
200 49
        if (PHP_VERSION_ID >= 50500) {
201 49
            $maxDepth = $this->maxDepth;
202
203
            // We subtract 1 from the max depth to make JsonDecoder and
204
            // JsonEncoder consistent. json_encode() and json_decode() behave
205
            // differently for their depth values. See the test cases for
206
            // examples.
207
            // HHVM does not have this inconsistency.
208 49
            if (!defined('HHVM_VERSION')) {
209 49
                --$maxDepth;
210
            }
211
212 49
            $encoded = json_encode($data, $options, $maxDepth);
213
        } else {
214
            $encoded = json_encode($data, $options);
215
        }
216
217 49
        if (PHP_VERSION_ID < 50400 && !$this->slashEscaped) {
218
            // PHP below 5.4 does not allow to turn off slash escaping. Let's
219
            // unescape slashes manually.
220
            $encoded = str_replace('\\/', '/', $encoded);
221
        }
222
223 49
        if (JSON_ERROR_NONE !== json_last_error()) {
224 5
            throw new EncodingFailedException(sprintf(
225 5
                'The data could not be encoded as JSON: %s',
226 5
                JsonError::getLastErrorMessage()
227
            ), json_last_error());
228
        }
229
230 44
        if ($this->terminatedWithLineFeed) {
231 1
            $encoded .= "\n";
232
        }
233
234 44
        return $encoded;
235
    }
236
237
    /**
238
     * Encodes data into a JSON file.
239
     *
240
     * @param mixed         $data   The data to encode
241
     * @param string        $path   The path where the JSON file will be stored
242
     * @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...
243
     *
244
     * @throws EncodingFailedException   If the data could not be encoded
245
     * @throws ValidationFailedException If the data fails schema validation
246
     * @throws InvalidSchemaException    If the schema is invalid
247
     *
248
     * @see encode
249
     */
250 6
    public function encodeFile($data, $path, $schema = null)
251
    {
252 6
        if (!file_exists($dir = dirname($path))) {
253 1
            mkdir($dir, 0777, true);
254
        }
255
256
        try {
257
            // Right now, it's sufficient to just write the file. In the future,
258
            // this will diff existing files with the given data and only do
259
            // in-place modifications where necessary.
260 6
            $content = $this->encode($data, $schema);
261 3
        } catch (EncodingFailedException $e) {
262
            // Add the file name to the exception
263 1
            throw new EncodingFailedException(sprintf(
264 1
                'An error happened while encoding %s: %s',
265
                $path,
266 1
                $e->getMessage()
267 1
            ), $e->getCode(), $e);
268 2
        } catch (ValidationFailedException $e) {
269
            // Add the file name to the exception
270 2
            throw new ValidationFailedException(sprintf(
271 2
                "Validation failed while encoding %s:\n%s",
272
                $path,
273 2
                $e->getErrorsAsString()
274 2
            ), $e->getErrors(), $e->getCode(), $e);
275
        } catch (InvalidSchemaException $e) {
276
            // Add the file name to the exception
277
            throw new InvalidSchemaException(sprintf(
278
                'An error happened while encoding %s: %s',
279
                $path,
280
                $e->getMessage()
281
            ), $e->getCode(), $e);
282
        }
283
284 3
        $errorMessage = null;
285 3
        $errorCode = 0;
286
287 3
        set_error_handler(function ($errno, $errstr) use (&$errorMessage, &$errorCode) {
288 1
            $errorMessage = $errstr;
289 1
            $errorCode = $errno;
290 3
        });
291
292 3
        file_put_contents($path, $content);
293
294 3
        restore_error_handler();
295
296 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...
297 1
            if (false !== $pos = strpos($errorMessage, '): ')) {
298
                // cut "file_put_contents(%path%):" to make message more readable
299 1
                $errorMessage = substr($errorMessage, $pos + 3);
300
            }
301
302 1
            throw new IOException(sprintf(
303 1
                'Could not write %s: %s (%s)',
304
                $path,
305
                $errorMessage,
306
                $errorCode
307
            ), $errorCode);
308
        }
309 2
    }
310
311
    /**
312
     * Returns the encoding of non-associative arrays.
313
     *
314
     * @return int One of the constants {@link JSON_OBJECT} and {@link JSON_ARRAY}
315
     */
316
    public function getArrayEncoding()
317
    {
318
        return $this->arrayEncoding;
319
    }
320
321
    /**
322
     * Sets the encoding of non-associative arrays.
323
     *
324
     * By default, non-associative arrays are decoded as JSON arrays.
325
     *
326
     * @param int $encoding One of the constants {@link JSON_OBJECT} and {@link JSON_ARRAY}
327
     *
328
     * @throws \InvalidArgumentException If the passed encoding is invalid
329
     */
330 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...
331
    {
332 5
        if (self::JSON_ARRAY !== $encoding && self::JSON_OBJECT !== $encoding) {
333 3
            throw new \InvalidArgumentException(sprintf(
334
                'Expected JsonEncoder::JSON_ARRAY or JsonEncoder::JSON_OBJECT. '.
335 3
                'Got: %s',
336
                $encoding
337
            ));
338
        }
339
340 2
        $this->arrayEncoding = $encoding;
341 2
    }
342
343
    /**
344
     * Returns the encoding of numeric strings.
345
     *
346
     * @return int One of the constants {@link JSON_STRING} and {@link JSON_NUMBER}
347
     */
348
    public function getNumericEncoding()
349
    {
350
        return $this->numericEncoding;
351
    }
352
353
    /**
354
     * Sets the encoding of numeric strings.
355
     *
356
     * By default, non-associative arrays are decoded as JSON strings.
357
     *
358
     * @param int $encoding One of the constants {@link JSON_STRING} and {@link JSON_NUMBER}
359
     *
360
     * @throws \InvalidArgumentException If the passed encoding is invalid
361
     */
362 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...
363
    {
364 6
        if (self::JSON_NUMBER !== $encoding && self::JSON_STRING !== $encoding) {
365 3
            throw new \InvalidArgumentException(sprintf(
366
                'Expected JsonEncoder::JSON_NUMBER or JsonEncoder::JSON_STRING. '.
367 3
                'Got: %s',
368
                $encoding
369
            ));
370
        }
371
372 3
        $this->numericEncoding = $encoding;
373 3
    }
374
375
    /**
376
     * Returns whether ampersands (&) are escaped.
377
     *
378
     * If `true`, ampersands will be escaped as "\u0026".
379
     *
380
     * By default, ampersands are not escaped.
381
     *
382
     * @return bool Whether ampersands are escaped
383
     */
384
    public function isAmpersandEscaped()
385
    {
386
        return $this->ampersandEscaped;
387
    }
388
389
    /**
390
     * Sets whether ampersands (&) should be escaped.
391
     *
392
     * If `true`, ampersands will be escaped as "\u0026".
393
     *
394
     * By default, ampersands are not escaped.
395
     *
396
     * @param bool $enabled Whether ampersands should be escaped
397
     */
398 2
    public function setEscapeAmpersand($enabled)
399
    {
400 2
        $this->ampersandEscaped = $enabled;
401 2
    }
402
403
    /**
404
     * Returns whether double quotes (") are escaped.
405
     *
406
     * If `true`, double quotes will be escaped as "\u0022".
407
     *
408
     * By default, double quotes are not escaped.
409
     *
410
     * @return bool Whether double quotes are escaped
411
     */
412
    public function isDoubleQuoteEscaped()
413
    {
414
        return $this->doubleQuoteEscaped;
415
    }
416
417
    /**
418
     * Sets whether double quotes (") should be escaped.
419
     *
420
     * If `true`, double quotes will be escaped as "\u0022".
421
     *
422
     * By default, double quotes are not escaped.
423
     *
424
     * @param bool $enabled Whether double quotes should be escaped
425
     */
426 2
    public function setEscapeDoubleQuote($enabled)
427
    {
428 2
        $this->doubleQuoteEscaped = $enabled;
429 2
    }
430
431
    /**
432
     * Returns whether single quotes (') are escaped.
433
     *
434
     * If `true`, single quotes will be escaped as "\u0027".
435
     *
436
     * By default, single quotes are not escaped.
437
     *
438
     * @return bool Whether single quotes are escaped
439
     */
440
    public function isSingleQuoteEscaped()
441
    {
442
        return $this->singleQuoteEscaped;
443
    }
444
445
    /**
446
     * Sets whether single quotes (") should be escaped.
447
     *
448
     * If `true`, single quotes will be escaped as "\u0027".
449
     *
450
     * By default, single quotes are not escaped.
451
     *
452
     * @param bool $enabled Whether single quotes should be escaped
453
     */
454 2
    public function setEscapeSingleQuote($enabled)
455
    {
456 2
        $this->singleQuoteEscaped = $enabled;
457 2
    }
458
459
    /**
460
     * Returns whether forward slashes (/) are escaped.
461
     *
462
     * If `true`, forward slashes will be escaped as "\/".
463
     *
464
     * By default, forward slashes are not escaped.
465
     *
466
     * @return bool Whether forward slashes are escaped
467
     */
468
    public function isSlashEscaped()
469
    {
470
        return $this->slashEscaped;
471
    }
472
473
    /**
474
     * Sets whether forward slashes (") should be escaped.
475
     *
476
     * If `true`, forward slashes will be escaped as "\/".
477
     *
478
     * By default, forward slashes are not escaped.
479
     *
480
     * @param bool $enabled Whether forward slashes should be escaped
481
     */
482 2
    public function setEscapeSlash($enabled)
483
    {
484 2
        $this->slashEscaped = $enabled;
485 2
    }
486
487
    /**
488
     * Returns whether greater than/less than symbols (>, <) are escaped.
489
     *
490
     * If `true`, greater than will be escaped as "\u003E" and less than as
491
     * "\u003C".
492
     *
493
     * By default, greater than/less than symbols are not escaped.
494
     *
495
     * @return bool Whether greater than/less than symbols are escaped
496
     */
497
    public function isGtLtEscaped()
498
    {
499
        return $this->gtLtEscaped;
500
    }
501
502
    /**
503
     * Sets whether greater than/less than symbols (>, <) should be escaped.
504
     *
505
     * If `true`, greater than will be escaped as "\u003E" and less than as
506
     * "\u003C".
507
     *
508
     * By default, greater than/less than symbols are not escaped.
509
     *
510
     * @param bool $enabled Whether greater than/less than should be escaped
511
     */
512 2
    public function setEscapeGtLt($enabled)
513
    {
514 2
        $this->gtLtEscaped = $enabled;
515 2
    }
516
517
    /**
518
     * Returns whether unicode characters are escaped.
519
     *
520
     * If `true`, unicode characters will be escaped as hexadecimals strings.
521
     * For example, "ü" will be escaped as "\u00fc".
522
     *
523
     * By default, unicode characters are escaped.
524
     *
525
     * @return bool Whether unicode characters are escaped
526
     */
527
    public function isUnicodeEscaped()
528
    {
529
        return $this->unicodeEscaped;
530
    }
531
532
    /**
533
     * Sets whether unicode characters should be escaped.
534
     *
535
     * If `true`, unicode characters will be escaped as hexadecimals strings.
536
     * For example, "ü" will be escaped as "\u00fc".
537
     *
538
     * By default, unicode characters are escaped.
539
     *
540
     * @param bool $enabled Whether unicode characters should be escaped
541
     */
542 2
    public function setEscapeUnicode($enabled)
543
    {
544 2
        $this->unicodeEscaped = $enabled;
545 2
    }
546
547
    /**
548
     * Returns whether JSON strings are formatted for better readability.
549
     *
550
     * If `true`, line breaks will be added after object properties and array
551
     * entries. Each new nesting level will be indented by four spaces.
552
     *
553
     * By default, pretty printing is not enabled.
554
     *
555
     * @return bool Whether JSON strings are formatted
556
     */
557
    public function isPrettyPrinting()
558
    {
559
        return $this->prettyPrinting;
560
    }
561
562
    /**
563
     * Sets whether JSON strings should be formatted for better readability.
564
     *
565
     * If `true`, line breaks will be added after object properties and array
566
     * entries. Each new nesting level will be indented by four spaces.
567
     *
568
     * By default, pretty printing is not enabled.
569
     *
570
     * @param bool $prettyPrinting Whether JSON strings should be formatted
571
     */
572 2
    public function setPrettyPrinting($prettyPrinting)
573
    {
574 2
        $this->prettyPrinting = $prettyPrinting;
575 2
    }
576
577
    /**
578
     * Returns whether JSON strings are terminated with a line feed.
579
     *
580
     * By default, JSON strings are not terminated with a line feed.
581
     *
582
     * @return bool Whether JSON strings are terminated with a line feed
583
     */
584
    public function isTerminatedWithLineFeed()
585
    {
586
        return $this->terminatedWithLineFeed;
587
    }
588
589
    /**
590
     * Sets whether JSON strings should be terminated with a line feed.
591
     *
592
     * By default, JSON strings are not terminated with a line feed.
593
     *
594
     * @param bool $enabled Whether JSON strings should be terminated with a
595
     *                      line feed
596
     */
597 2
    public function setTerminateWithLineFeed($enabled)
598
    {
599 2
        $this->terminatedWithLineFeed = $enabled;
600 2
    }
601
602
    /**
603
     * Returns the maximum recursion depth.
604
     *
605
     * A depth of zero means that objects are not allowed. A depth of one means
606
     * only one level of objects or arrays is allowed.
607
     *
608
     * @return int The maximum recursion depth
609
     */
610
    public function getMaxDepth()
611
    {
612
        return $this->maxDepth;
613
    }
614
615
    /**
616
     * Sets the maximum recursion depth.
617
     *
618
     * If the depth is exceeded during encoding, an {@link EncodingFailedException}
619
     * will be thrown.
620
     *
621
     * A depth of zero means that objects are not allowed. A depth of one means
622
     * only one level of objects or arrays is allowed.
623
     *
624
     * @param int $maxDepth The maximum recursion depth
625
     *
626
     * @throws \InvalidArgumentException If the depth is not an integer greater
627
     *                                   than or equal to zero
628
     */
629 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...
630
    {
631 6
        if (!is_int($maxDepth)) {
632 1
            throw new \InvalidArgumentException(sprintf(
633 1
                'The maximum depth should be an integer. Got: %s',
634 1
                is_object($maxDepth) ? get_class($maxDepth) : gettype($maxDepth)
635
            ));
636
        }
637
638 5
        if ($maxDepth < 1) {
639 1
            throw new \InvalidArgumentException(sprintf(
640 1
                'The maximum depth should 1 or greater. Got: %s',
641
                $maxDepth
642
            ));
643
        }
644
645 4
        $this->maxDepth = $maxDepth;
646 4
    }
647
}
648