This repository has been archived by the owner on Jan 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathJsonTest.php
1093 lines (953 loc) · 32 KB
/
JsonTest.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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link http://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Json;
use ArrayIterator;
use PHPUnit_Framework_TestCase as TestCase;
use Zend\Json;
use stdClass;
class JsonTest extends TestCase
{
private $originalUseBuiltinEncoderDecoderValue;
public function setUp()
{
$this->originalUseBuiltinEncoderDecoderValue = Json\Json::$useBuiltinEncoderDecoder;
}
public function tearDown()
{
Json\Json::$useBuiltinEncoderDecoder = $this->originalUseBuiltinEncoderDecoderValue;
}
/**
* Test encoding and decoding in a single step
*
* @param scalar|array $values array of values to test against encode/decode
* @param $message
*/
public function assertEncodesToDecodable($values, $message = null)
{
$message = $message ?: 'One or more values could not be decoded after encoding';
$values = is_null($values) ? [null] : $values;
$values = is_scalar($values) ? [$values] : $values;
foreach ($values as $value) {
$encoded = Json\Encoder::encode($value);
if (is_array($value) || is_object($value)) {
$message = $message ?: sprintf(
'Value could not be decoded after encoding: %s',
var_export($value, true)
);
$this->assertEquals(
$this->toArray($value),
Json\Decoder::decode($encoded, Json\Json::TYPE_ARRAY),
$message
);
continue;
}
$message = $message ?: sprintf(
'Value could not be decoded after encoding: %s',
$value
);
$this->assertEquals($value, Json\Decoder::decode($encoded), $message);
}
}
public function testJSONWithPhpJSONExtension()
{
if (! extension_loaded('json')) {
$this->markTestSkipped('JSON extension is not loaded');
}
Json\Json::$useBuiltinEncoderDecoder = false;
$this->assertEncodesToDecodable(['string', 327, true, null]);
}
public function testJSONWithBuiltins()
{
Json\Json::$useBuiltinEncoderDecoder = true;
$this->assertEncodesToDecodable(['string', 327, true, null]);
}
/**
* test null encoding/decoding
*/
public function testNull()
{
$this->assertEncodesToDecodable(null, 'Null could not be decoded after encoding');
}
/**
* test boolean encoding/decoding
*/
public function testBoolean()
{
$this->assertTrue(Json\Decoder::decode(Json\Encoder::encode(true)));
$this->assertFalse(Json\Decoder::decode(Json\Encoder::encode(false)));
}
public function integerProvider()
{
return [
'negative' => [-1],
'zero' => [0],
'positive' => [1],
];
}
/**
* test integer encoding/decoding
* @dataProvider integerProvider
*/
public function testInteger($int)
{
$this->assertEncodesToDecodable($int);
}
public function floatProvider()
{
return [
'negative' => [-1.1],
'zero' => [0.0],
'positive' => [1.1],
];
}
/**
* test float encoding/decoding
* @dataProvider floatProvider
*/
public function testFloat($float)
{
$this->assertEncodesToDecodable($float);
}
public function stringProvider()
{
return [
'empty' => [''],
'string' => ['string'],
];
}
/**
* test string encoding/decoding
* @dataProvider stringProvider
*/
public function testString($string)
{
$this->assertEncodesToDecodable($string);
}
/**
* Test backslash escaping of string
*/
public function testString2()
{
$string = 'INFO: Path \\\\test\\123\\abc';
$expected = '"INFO: Path \\\\\\\\test\\\\123\\\\abc"';
$encoded = Json\Encoder::encode($string);
$this->assertEquals(
$expected,
$encoded,
sprintf(
'Backslash encoding incorrect: expected: %s; received: %s',
serialize($expected),
serialize($encoded)
)
);
$this->assertEncodesToDecodable($string);
}
/**
* Test newline escaping of string
*/
public function testString3()
{
$expected = '"INFO: Path\nSome more"';
$string = "INFO: Path\nSome more";
$encoded = Json\Encoder::encode($string);
$this->assertEquals(
$expected,
$encoded,
sprintf(
'Newline encoding incorrect: expected %s; received: %s',
serialize($expected),
serialize($encoded)
)
);
$this->assertEncodesToDecodable($string);
}
/**
* Test tab/non-tab escaping of string
*/
public function testString4()
{
$expected = '"INFO: Path\\t\\\\tSome more"';
$string = "INFO: Path\t\\tSome more";
$encoded = Json\Encoder::encode($string);
$this->assertEquals(
$expected,
$encoded,
sprintf(
'Tab encoding incorrect: expected %s; received: %s',
serialize($expected),
serialize($encoded)
)
);
$this->assertEncodesToDecodable($string);
}
/**
* Test double-quote escaping of string
*/
public function testString5()
{
$expected = '"INFO: Path \\u0022Some more\\u0022"';
$string = 'INFO: Path "Some more"';
$encoded = Json\Encoder::encode($string);
$this->assertEquals(
$expected,
$encoded,
'Quote encoding incorrect: expected ' . serialize($expected) . '; received: ' . serialize($encoded) . "\n"
);
$this->assertEncodesToDecodable($string); // Bug: does not accept \u0022 as token!
}
/**
* Test decoding of unicode escaped special characters
*/
public function testStringOfHtmlSpecialCharsEncodedToUnicodeEscapes()
{
Json\Json::$useBuiltinEncoderDecoder = false;
$expected = '"\\u003C\\u003E\\u0026\\u0027\\u0022"';
$string = '<>&\'"';
$encoded = Json\Encoder::encode($string);
$this->assertEquals(
$expected,
$encoded,
'Encoding error: expected ' . serialize($expected) . '; received: ' . serialize($encoded) . "\n"
);
$this->assertEncodesToDecodable($string);
}
/**
* Test decoding of unicode escaped ASCII (non-HTML special) characters
*
* Note: covers chars that MUST be escaped. Does not test any other non-printables.
*/
public function testStringOfOtherSpecialCharsEncodedToUnicodeEscapes()
{
Json\Json::$useBuiltinEncoderDecoder = false;
$string = "\\ - \n - \t - \r - " . chr(0x08) . " - " . chr(0x0C) . " - / - \v";
$encoded = '"\u005C - \u000A - \u0009 - \u000D - \u0008 - \u000C - \u002F - \u000B"';
$this->assertEquals($string, Json\Decoder::decode($encoded));
}
/**
* test indexed array encoding/decoding
*/
public function testArray()
{
$this->assertEncodesToDecodable([[1, 'one', 2, 'two']]);
}
/**
* test associative array encoding/decoding
*/
public function testAssocArray()
{
$this->assertEncodesToDecodable([['one' => 1, 'two' => 2]]);
}
/**
* test associative array encoding/decoding, with mixed key types
*/
public function testAssocArray2()
{
$this->assertEncodesToDecodable([['one' => 1, 2 => 2]]);
}
/**
* test associative array encoding/decoding, with integer keys not starting at 0
*/
public function testAssocArray3()
{
$this->assertEncodesToDecodable([[1 => 'one', 2 => 'two']]);
}
/**
* test object encoding/decoding (decoding to array)
*/
public function testObject()
{
$value = new stdClass();
$value->one = 1;
$value->two = 2;
$array = ['__className' => 'stdClass', 'one' => 1, 'two' => 2];
$encoded = Json\Encoder::encode($value);
$this->assertSame($array, Json\Decoder::decode($encoded, Json\Json::TYPE_ARRAY));
}
/**
* test object encoding/decoding (decoding to stdClass)
*/
public function testObjectAsObject()
{
$value = new stdClass();
$value->one = 1;
$value->two = 2;
$encoded = Json\Encoder::encode($value);
$decoded = Json\Decoder::decode($encoded, Json\Json::TYPE_OBJECT);
$this->assertInstanceOf('stdClass', $decoded);
$this->assertObjectHasAttribute('one', $decoded);
$this->assertEquals($value->one, $decoded->one, 'Unexpected value');
}
/**
* Test that arrays of objects decode properly; see issue #144
*/
public function testDecodeArrayOfObjects()
{
$value = '[{"id":1},{"foo":2}]';
$expect = [['id' => 1], ['foo' => 2]];
$this->assertEquals($expect, Json\Decoder::decode($value, Json\Json::TYPE_ARRAY));
}
/**
* Test that objects of arrays decode properly; see issue #107
*/
public function testDecodeObjectOfArrays()
{
// @codingStandardsIgnoreStart
$value = '{"codeDbVar" : {"age" : ["int", 5], "prenom" : ["varchar", 50]}, "234" : [22, "jb"], "346" : [64, "francois"], "21" : [12, "paul"]}';
// @codingStandardsIgnoreEnd
$expect = [
'codeDbVar' => [
'age' => ['int', 5],
'prenom' => ['varchar', 50],
],
234 => [22, 'jb'],
346 => [64, 'francois'],
21 => [12, 'paul']
];
$this->assertEquals($expect, Json\Decoder::decode($value, Json\Json::TYPE_ARRAY));
}
/**
* Cast a value to an array, if possible.
*
* Casts objects to arrays for expectation comparisons.
*
* @param mixed $value
* @return mixed
*/
protected function toArray($value)
{
if (! is_array($value) || ! is_object($value)) {
return $value;
}
$array = [];
foreach ((array) $value as $k => $v) {
$array[$k] = $this->toArray($v);
}
return $array;
}
/**
* Test that version numbers such as 4.10 are encoded and decoded properly;
* See ZF-377
*/
public function testEncodeReleaseNumber()
{
$value = '4.10';
$this->assertEncodesToDecodable($value);
}
/**
* Tests that spaces/linebreaks prior to a closing right bracket don't throw
* exceptions. See ZF-283.
*/
public function testEarlyLineBreak()
{
$expected = ['data' => [1, 2, 3, 4]];
$json = '{"data":[1,2,3,4' . "\n]}";
$this->assertEquals($expected, Json\Decoder::decode($json, Json\Json::TYPE_ARRAY));
$json = '{"data":[1,2,3,4 ]}';
$this->assertEquals($expected, Json\Decoder::decode($json, Json\Json::TYPE_ARRAY));
}
/**
* @group ZF-504
*/
public function testEncodeEmptyArrayAsStruct()
{
$this->assertSame('[]', Json\Encoder::encode([]));
}
/**
* @group ZF-504
*/
public function testDecodeBorkedJsonShouldThrowException1()
{
$this->setExpectedException(Json\Exception\RuntimeException::class);
Json\Decoder::decode('[a"],["a],[][]');
}
/**
* @group ZF-504
*/
public function testDecodeBorkedJsonShouldThrowException2()
{
$this->setExpectedException(Json\Exception\RuntimeException::class);
Json\Decoder::decode('[a"],["a]');
}
/**
* @group ZF-504
*/
public function testOctalValuesAreNotSupportedInJsonNotation()
{
$this->setExpectedException(Json\Exception\RuntimeException::class);
Json\Decoder::decode('010');
}
/**
* Tests for ZF-461
*
* Check to see that cycling detection works properly
*/
public function testZf461()
{
$item1 = new TestAsset\Item();
$item2 = new TestAsset\Item();
$everything = [];
$everything['allItems'] = [$item1, $item2];
$everything['currentItem'] = $item1;
// should not fail
$encoded = Json\Encoder::encode($everything);
// should fail
$this->setExpectedException(Json\Exception\RecursionException::class);
Json\Encoder::encode($everything, true);
}
/**
* Test for ZF-4053
*
* Check to see that cyclical exceptions are silenced when
* $option['silenceCyclicalExceptions'] = true is used
*/
public function testZf4053()
{
$item1 = new TestAsset\Item();
$item2 = new TestAsset\Item();
$everything = [];
$everything['allItems'] = [$item1, $item2];
$everything['currentItem'] = $item1;
$options = ['silenceCyclicalExceptions'=>true];
Json\Json::$useBuiltinEncoderDecoder = true;
$encoded = Json\Json::encode($everything, true, $options);
// @codingStandardsIgnoreStart
$json = '{"allItems":[{"__className":"ZendTest\\\\Json\\\\TestAsset\\\\Item"},{"__className":"ZendTest\\\\Json\\\\TestAsset\\\\Item"}],"currentItem":"* RECURSION (ZendTest\\\\Json\\\\TestAsset\\\\Item) *"}';
// @codingStandardsIgnoreEnd
$this->assertEquals($json, $encoded);
}
public function testEncodeObject()
{
$actual = new TestAsset\Object();
$encoded = Json\Encoder::encode($actual);
$decoded = Json\Decoder::decode($encoded, Json\Json::TYPE_OBJECT);
$this->assertAttributeEquals(TestAsset\Object::class, '__className', $decoded);
$this->assertAttributeEquals('bar', 'foo', $decoded);
$this->assertAttributeEquals('baz', 'bar', $decoded);
$this->assertFalse(isset($decoded->_foo));
}
public function testEncodeClass()
{
$encoded = Json\Encoder::encodeClass(TestAsset\Object::class);
$this->assertContains("Class.create('ZendTest\\Json\\TestAsset\\Object'", $encoded);
$this->assertContains("ZAjaxEngine.invokeRemoteMethod(this, 'foo'", $encoded);
$this->assertContains("ZAjaxEngine.invokeRemoteMethod(this, 'bar'", $encoded);
$this->assertNotContains("ZAjaxEngine.invokeRemoteMethod(this, 'baz'", $encoded);
$this->assertContains('variables:{foo:"bar",bar:"baz"}', $encoded);
$this->assertContains('constants:{FOO: "bar"}', $encoded);
}
public function testEncodeClasses()
{
$encoded = Json\Encoder::encodeClasses(['ZendTest\Json\TestAsset\Object', 'Zend\Json\Json']);
$this->assertContains("Class.create('ZendTest\\Json\\TestAsset\\Object'", $encoded);
$this->assertContains("Class.create('Zend\\Json\\Json'", $encoded);
}
public function testToJSONSerialization()
{
$toJSONObject = new TestAsset\ToJSONClass();
$result = Json\Json::encode($toJSONObject);
$this->assertEquals('{"firstName":"John","lastName":"Doe","email":"john@doe.com"}', $result);
}
public function testJsonSerializableWithBuiltinImplementation()
{
$encoded = Json\Encoder::encode(
new TestAsset\JsonSerializableBuiltinImpl()
);
$this->assertEquals('["jsonSerialize"]', $encoded);
}
public function testJsonSerializableWithZFImplementation()
{
$encoded = Json\Encoder::encode(
new TestAsset\JsonSerializableZFImpl()
);
$this->assertEquals('["jsonSerialize"]', $encoded);
}
/**
* test encoding array with Zend_JSON_Expr
*
* @group ZF-4946
*/
public function testEncodingArrayWithExpr()
{
$expr = new Json\Expr('window.alert("Zend JSON Expr")');
$array = ['expr' => $expr, 'int' => 9, 'string' => 'text'];
$result = Json\Json::encode($array, false, ['enableJsonExprFinder' => true]);
$expected = '{"expr":window.alert("Zend JSON Expr"),"int":9,"string":"text"}';
$this->assertEquals($expected, $result);
}
/**
* test encoding object with Zend_JSON_Expr
*
* @group ZF-4946
*/
public function testEncodingObjectWithExprAndInternalEncoder()
{
Json\Json::$useBuiltinEncoderDecoder = true;
$expr = new Json\Expr('window.alert("Zend JSON Expr")');
$obj = new stdClass();
$obj->expr = $expr;
$obj->int = 9;
$obj->string = 'text';
$result = Json\Json::encode($obj, false, ['enableJsonExprFinder' => true]);
$expected = '{"__className":"stdClass","expr":window.alert("Zend JSON Expr"),"int":9,"string":"text"}';
$this->assertEquals($expected, $result);
}
/**
* Test encoding object with Zend\Json\Expr
*
* @group ZF-4946
*/
public function testEncodingObjectWithExprAndExtJSON()
{
if (!function_exists('json_encode')) {
$this->markTestSkipped('Test only works with ext/json enabled!');
}
Json\Json::$useBuiltinEncoderDecoder = false;
$expr = new Json\Expr('window.alert("Zend JSON Expr")');
$obj = new stdClass();
$obj->expr = $expr;
$obj->int = 9;
$obj->string = 'text';
$result = Json\Json::encode($obj, false, ['enableJsonExprFinder' => true]);
$expected = '{"expr":window.alert("Zend JSON Expr"),"int":9,"string":"text"}';
$this->assertEquals($expected, $result);
}
/**
* test encoding object with toJson and Zend\Json\Expr
*
* @group ZF-4946
*/
public function testToJSONWithExpr()
{
Json\Json::$useBuiltinEncoderDecoder = true;
$obj = new TestAsset\ToJSONWithExpr();
$result = Json\Json::encode($obj, false, ['enableJsonExprFinder' => true]);
$expected = '{"expr":window.alert("Zend JSON Expr"),"int":9,"string":"text"}';
$this->assertEquals($expected, $result);
}
/**
* Regression tests for Zend\Json\Expr and multiple keys with the same name.
*
* @group ZF-4946
*/
public function testEncodingMultipleNestedSwitchingSameNameKeysWithDifferentJSONExprSettings()
{
$data = [
0 => [
"alpha" => new Json\Expr("function () {}"),
"beta" => "gamma",
],
1 => [
"alpha" => "gamma",
"beta" => new Json\Expr("function () {}"),
],
2 => [
"alpha" => "gamma",
"beta" => "gamma",
]
];
$result = Json\Json::encode($data, false, ['enableJsonExprFinder' => true]);
// @codingStandardsIgnoreStart
$this->assertEquals(
'[{"alpha":function () {},"beta":"gamma"},{"alpha":"gamma","beta":function () {}},{"alpha":"gamma","beta":"gamma"}]',
$result
);
// @codingStandardsIgnoreEnd
}
/**
* Regression tests for Zend\Json\Expr and multiple keys with the same name.
*
* @group ZF-4946
*/
public function testEncodingMultipleNestedIteratedSameNameKeysWithDifferentJSONExprSettings()
{
$data = [
0 => [
"alpha" => "alpha"
],
1 => [
"alpha" => "beta",
],
2 => [
"alpha" => new Json\Expr("gamma"),
],
3 => [
"alpha" => "delta",
],
4 => [
"alpha" => new Json\Expr("epsilon"),
]
];
$result = Json\Json::encode($data, false, ['enableJsonExprFinder' => true]);
// @codingStandardsIgnoreStart
$this->assertEquals('[{"alpha":"alpha"},{"alpha":"beta"},{"alpha":gamma},{"alpha":"delta"},{"alpha":epsilon}]', $result);
// @codingStandardsIgnoreEnd
}
public function testDisabledJSONExprFinder()
{
Json\Json::$useBuiltinEncoderDecoder = true;
$data = [
0 => [
"alpha" => new Json\Expr("function () {}"),
"beta" => "gamma",
],
];
$result = Json\Json::encode($data);
$this->assertEquals(
'[{"alpha":{"__className":"Zend\\\\Json\\\\Expr"},"beta":"gamma"}]',
$result
);
}
/**
* @group ZF-4054
*/
public function testEncodeWithUtf8IsTransformedToPackedSyntax()
{
$data = ["Отмена"];
$result = Json\Encoder::encode($data);
$this->assertEquals('["\u041e\u0442\u043c\u0435\u043d\u0430"]', $result);
}
/**
* @group ZF-4054
*
* This test contains assertions from the Solar Framework by Paul M. Jones
* @link http://solarphp.com
*/
public function testEncodeWithUtf8IsTransformedSolarRegression()
{
$expect = '"h\u00c3\u00a9ll\u00c3\u00b6 w\u00c3\u00b8r\u00c5\u201ad"';
$this->assertEquals($expect, Json\Encoder::encode('héllö wørłd'));
$this->assertEquals('héllö wørłd', Json\Decoder::decode($expect));
$expect = '"\u0440\u0443\u0441\u0441\u0438\u0448"';
$this->assertEquals($expect, Json\Encoder::encode("руссиш"));
$this->assertEquals("руссиш", Json\Decoder::decode($expect));
}
/**
* @group ZF-4054
*/
public function testEncodeUnicodeStringSolarRegression()
{
$value = 'héllö wørłd';
$expected = 'h\u00c3\u00a9ll\u00c3\u00b6 w\u00c3\u00b8r\u00c5\u201ad';
$this->assertEquals($expected, Json\Encoder::encodeUnicodeString($value));
$value = "\xC3\xA4";
$expected = '\u00e4';
$this->assertEquals($expected, Json\Encoder::encodeUnicodeString($value));
$value = "\xE1\x82\xA0\xE1\x82\xA8";
$expected = '\u10a0\u10a8';
$this->assertEquals($expected, Json\Encoder::encodeUnicodeString($value));
}
/**
* @group ZF-4054
*/
public function testDecodeUnicodeStringSolarRegression()
{
$expected = 'héllö wørłd';
$value = 'h\u00c3\u00a9ll\u00c3\u00b6 w\u00c3\u00b8r\u00c5\u201ad';
$this->assertEquals($expected, Json\Decoder::decodeUnicodeString($value));
$expected = "\xC3\xA4";
$value = '\u00e4';
$this->assertEquals($expected, Json\Decoder::decodeUnicodeString($value));
$value = '\u10a0';
$expected = "\xE1\x82\xA0";
$this->assertEquals($expected, Json\Decoder::decodeUnicodeString($value));
}
/**
* @group ZF-4054
*
* This test contains assertions from the Solar Framework by Paul M. Jones
* @link http://solarphp.com
*/
public function testEncodeWithUtf8IsTransformedSolarRegressionEqualsJSONExt()
{
if (function_exists('json_encode') == false) {
$this->markTestSkipped('Test can only be run, when ext/json is installed.');
}
$this->assertEquals(
json_encode('héllö wørłd'),
Json\Encoder::encode('héllö wørłd')
);
$this->assertEquals(
json_encode("руссиш"),
Json\Encoder::encode("руссиш")
);
}
/**
* @group ZF-4946
*/
public function testUtf8JSONExprFinder()
{
$data = ["Отмена" => new Json\Expr("foo")];
Json\Json::$useBuiltinEncoderDecoder = true;
$result = Json\Json::encode($data, false, ['enableJsonExprFinder' => true]);
$this->assertEquals('{"\u041e\u0442\u043c\u0435\u043d\u0430":foo}', $result);
Json\Json::$useBuiltinEncoderDecoder = false;
$result = Json\Json::encode($data, false, ['enableJsonExprFinder' => true]);
$this->assertEquals('{"\u041e\u0442\u043c\u0435\u043d\u0430":foo}', $result);
}
/**
* @group ZF-4437
*/
public function testCommaDecimalIsConvertedToCorrectJSONWithDot()
{
setlocale(LC_ALL, 'Spanish_Spain', 'es_ES', 'es_ES.utf-8');
if (strcmp('1,2', (string) floatval(1.20)) !== 0) {
$this->markTestSkipped('This test only works for platforms where "," is the decimal point separator.');
}
Json\Json::$useBuiltinEncoderDecoder = true;
$actual = Json\Encoder::encode([floatval(1.20), floatval(1.68)]);
$this->assertEquals('[1.2,1.68]', $actual);
}
public function testEncodeObjectImplementingIterator()
{
$iterator = new ArrayIterator([
'foo' => 'bar',
'baz' => 5
]);
$target = '{"__className":"ArrayIterator","foo":"bar","baz":5}';
Json\Json::$useBuiltinEncoderDecoder = true;
$this->assertEquals($target, Json\Json::encode($iterator));
}
/**
* @group ZF-12347
*/
public function testEncodeObjectImplementingIteratorAggregate()
{
$iterator = new TestAsset\TestIteratorAggregate();
$target = '{"__className":"ZendTest\\\\Json\\\\TestAsset\\\\TestIteratorAggregate","foo":"bar","baz":5}';
Json\Json::$useBuiltinEncoderDecoder = true;
$this->assertEquals($target, Json\Json::encode($iterator));
}
/**
* @group ZF-8663
*/
public function testNativeJSONEncoderWillProperlyEncodeSolidusInStringValues()
{
$source = "</foo><foo>bar</foo>";
$target = '"\u003C\/foo\u003E\u003Cfoo\u003Ebar\u003C\/foo\u003E"';
// first test ext/json
Json\Json::$useBuiltinEncoderDecoder = false;
$this->assertEquals($target, Json\Json::encode($source));
}
public function testNativeJSONEncoderWillProperlyEncodeHtmlSpecialCharsInStringValues()
{
$source = "<>&'\"";
$target = '"\u003C\u003E\u0026\u0027\u0022"';
// first test ext/json
Json\Json::$useBuiltinEncoderDecoder = false;
$this->assertEquals($target, Json\Json::encode($source));
}
/**
* @group ZF-8663
*/
public function testBuiltinJSONEncoderWillProperlyEncodeSolidusInStringValues()
{
$source = "</foo><foo>bar</foo>";
$target = '"\u003C\/foo\u003E\u003Cfoo\u003Ebar\u003C\/foo\u003E"';
// first test ext/json
Json\Json::$useBuiltinEncoderDecoder = true;
$this->assertEquals($target, Json\Json::encode($source));
}
public function testBuiltinJSONEncoderWillProperlyEncodeHtmlSpecialCharsInStringValues()
{
$source = "<>&'\"";
$target = '"\u003C\u003E\u0026\u0027\u0022"';
// first test ext/json
Json\Json::$useBuiltinEncoderDecoder = true;
$this->assertEquals($target, Json\Json::encode($source));
}
/**
* @group ZF-8918
*/
public function testDecodingInvalidJSONShouldRaiseAnException()
{
$this->setExpectedException(Json\Exception\RuntimeException::class);
Json\Json::decode(' some string ');
}
/**
* Encoding an iterator using the internal encoder should handle undefined keys
*
* @group ZF-9416
*/
public function testIteratorWithoutDefinedKey()
{
$inputValue = new ArrayIterator(['foo']);
$encoded = Json\Encoder::encode($inputValue);
$expectedDecoding = '{"__className":"ArrayIterator",0:"foo"}';
$this->assertEquals($expectedDecoding, $encoded);
}
/**
* The default json decode type should be TYPE_OBJECT
*
* @group ZF-8618
*/
public function testDefaultTypeObject()
{
$this->assertInstanceOf(stdClass::class, Json\Decoder::decode('{"var":"value"}'));
}
/**
* @group ZF-10185
*/
public function testJsonPrettyPrintWorksWithArrayNotationInStringLiteral()
{
$o = new stdClass();
$o->test = 1;
$o->faz = 'fubar';
// The escaped double-quote in item 'stringwithjsonchars' ensures that
// escaped double-quotes do not throw off string literal detection in
// prettyPrint
$test = [
'simple' => 'simple test string',
'stringwithjsonchars' => '\"[1,2]',
'complex' => [
'foo' => 'bar',
'far' => 'boo',
'faz' => [
'obj' => $o,
],
'fay' => ['foo', 'bar'],
],
];
$pretty = Json\Json::prettyPrint(Json\Json::encode($test), ['indent' => ' ']);
$expected = <<<EOB
{
"simple": "simple test string",
"stringwithjsonchars": "\\\\\\u0022[1,2]",
"complex": {
"foo": "bar",
"far": "boo",
"faz": {
"obj": {
"test": 1,
"faz": "fubar"
}
},
"fay": [
"foo",
"bar"
]
}
}
EOB;
$this->assertSame($expected, $pretty);
}
public function testPrettyPrintDoublequoteFollowingEscapedBackslashShouldNotBeTreatedAsEscaped()
{
$this->assertEquals(
"[\n 1,\n \"\\\\\",\n 3\n]",
Json\Json::prettyPrint(Json\Json::encode([1, '\\', 3]))
);
$this->assertEquals(
"{\n \"a\": \"\\\\\"\n}",
Json\Json::prettyPrint(Json\Json::encode(['a' => '\\']))
);
}
public function testPrettyPrintRePrettyPrint()
{
$expected = <<<EOB
{
"simple": "simple test string",
"stringwithjsonchars": "\\\\\\u0022[1,2]",
"complex": {
"foo": "bar",
"far": "boo",
"faz": {
"obj": {
"test": 1,
"faz": "fubar"
}
}
}
}
EOB;
$this->assertSame(
$expected,
Json\Json::prettyPrint($expected, ['indent' => ' '])
);
}