1
+ <?php
2
+ namespace de \interaapps \jsonplus ;
3
+
4
+ use de \interaapps \jsonplus \serializationadapter \impl \phpjson \PHPJsonSerializationAdapter ;
5
+ use de \interaapps \jsonplus \serializationadapter \SerializationAdapter ;
6
+ use de \interaapps \jsonplus \typemapper \ObjectTypeMapper ;
7
+ use de \interaapps \jsonplus \typemapper \PassThroughTypeMapper ;
8
+ use de \interaapps \jsonplus \typemapper \TypeMapper ;
9
+ use ReflectionClass ;
10
+
11
+ class JSONPlus {
12
+ private bool $ prettyPrinting = false ;
13
+ private array $ typeMapper = [];
14
+ private TypeMapper $ defaultTypeMapper ;
15
+ private TypeMapper $ passThroughTypeMapper ;
16
+ public static JSONPlus $ default ;
17
+
18
+ public function __construct (
19
+ private SerializationAdapter $ serializationAdapter
20
+ ){
21
+ $ this ->defaultTypeMapper = new ObjectTypeMapper ($ this );
22
+ $ this ->passThroughTypeMapper = new PassThroughTypeMapper ();
23
+ $ this ->typeMapper = [
24
+ "object " => $ this ->passThroughTypeMapper ,
25
+ "string " => $ this ->passThroughTypeMapper ,
26
+ "float " => $ this ->passThroughTypeMapper ,
27
+ "int " => $ this ->passThroughTypeMapper ,
28
+ "double " => $ this ->passThroughTypeMapper ,
29
+ "bool " => $ this ->passThroughTypeMapper ,
30
+ "array " => $ this ->passThroughTypeMapper ,
31
+ "boolean " => $ this ->passThroughTypeMapper ,
32
+ ];
33
+ }
34
+
35
+ public function fromJson ($ json , $ type =null ){
36
+ return $ this ->map ($ this ->serializationAdapter ->fromJson ($ json ), $ type );
37
+ }
38
+
39
+ public function map ($ o , $ type = null ){
40
+ if ($ type == null )
41
+ $ type = get_class ($ o );
42
+
43
+ foreach ($ this ->typeMapper as $ typeName => $ typeMapper ) {
44
+ if ($ type == $ typeName )
45
+ return $ typeMapper ->map ($ o , $ type );
46
+ }
47
+ return $ this ->defaultTypeMapper ->map ($ o , $ type );
48
+ }
49
+
50
+ public function toJson ($ o , $ type = null ) : string {
51
+ return $ this ->serializationAdapter ->toJson ($ this ->mapToJson ($ o , $ type ), $ this ->prettyPrinting );
52
+ }
53
+
54
+ public function mapToJson ($ o , $ type = null ){
55
+ if ($ type == null )
56
+ $ type = get_class ($ o );
57
+ foreach ($ this ->typeMapper as $ typeName => $ typeMapper ) {
58
+ if ($ type == $ typeName )
59
+ return $ typeMapper ->mapToJson ($ o , $ type );
60
+ }
61
+ return $ this ->defaultTypeMapper ->mapToJson ($ o , $ type );
62
+ }
63
+
64
+ public function getSerializationAdapter (): SerializationAdapter {
65
+ return $ this ->serializationAdapter ;
66
+ }
67
+
68
+ public function setPrettyPrinting (bool $ prettyPrinting ): JSONPlus {
69
+ $ this ->prettyPrinting = $ prettyPrinting ;
70
+ return $ this ;
71
+ }
72
+
73
+ public static function createDefault () : JSONPlus {
74
+ return new JSONPlus (new PHPJsonSerializationAdapter ());
75
+ }
76
+ }
77
+ JSONPlus::$ default = JSONPlus::createDefault ();
0 commit comments