xref: /PHP-7.2/ext/json/tests/serialize.phpt (revision f1d7e3ca)
1--TEST--
2json_encode() Serialization tests
3--INI--
4serialize_precision=-1
5--SKIPIF--
6<?php if (!extension_loaded("json")) print "skip"; ?>
7--FILE--
8<?php
9
10class NonSerializingTest
11{
12	public $data;
13
14	public function __construct($data)
15	{
16		$this->data = $data;
17	}
18}
19
20class SerializingTest extends NonSerializingTest implements JsonSerializable
21{
22	public function jsonSerialize()
23	{
24		return $this->data;
25	}
26}
27
28class ValueSerializingTest extends SerializingTest
29{
30	public function jsonSerialize()
31	{
32		return array_values(is_array($this->data) ? $this->data : get_object_vars($this->data));
33	}
34}
35
36class SelfSerializingTest extends SerializingTest
37{
38	public function jsonSerialize()
39	{
40		return $this;
41	}
42}
43
44$adata = array(
45	'str'	=> 'foo',
46	'int'	=> 1,
47	'float'	=> 2.3,
48	'bool'	=> false,
49	'nil'	=> null,
50	'arr'	=> array(1,2,3),
51	'obj'	=> new StdClass,
52);
53
54$ndata = array_values($adata);
55
56$odata = (object)$adata;
57
58foreach(array('NonSerializingTest','SerializingTest','ValueSerializingTest','SelfSerializingTest') as $class) {
59	echo "==$class==\n";
60	echo json_encode(new $class($adata)), "\n";
61	echo json_encode(new $class($ndata)), "\n";
62	echo json_encode(new $class($odata)), "\n";
63}
64--EXPECT--
65==NonSerializingTest==
66{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
67{"data":["foo",1,2.3,false,null,[1,2,3],{}]}
68{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
69==SerializingTest==
70{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}
71["foo",1,2.3,false,null,[1,2,3],{}]
72{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}
73==ValueSerializingTest==
74["foo",1,2.3,false,null,[1,2,3],{}]
75["foo",1,2.3,false,null,[1,2,3],{}]
76["foo",1,2.3,false,null,[1,2,3],{}]
77==SelfSerializingTest==
78{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
79{"data":["foo",1,2.3,false,null,[1,2,3],{}]}
80{"data":{"str":"foo","int":1,"float":2.3,"bool":false,"nil":null,"arr":[1,2,3],"obj":{}}}
81