File tree Expand file tree Collapse file tree 3 files changed +75
-0
lines changed Expand file tree Collapse file tree 3 files changed +75
-0
lines changed Original file line number Diff line number Diff line change @@ -114,6 +114,22 @@ $note = Type::create($array);
114
114
115
115
```
116
116
117
+ You may create a type from a JSON string with the ` fromJson() ` method.
118
+ JSON must have a ` type ` key.
119
+
120
+ ``` php
121
+ use ActivityPhp\Type;
122
+
123
+ $json = '
124
+ {
125
+ "type": "Note",
126
+ "content": "A content for my note"
127
+ }';
128
+
129
+ $note = Type::fromJson($json);
130
+
131
+ ```
132
+
117
133
When a property does not exist, an Exception is thrown in strict mode.
118
134
You can define 3 different behaviours:
119
135
Original file line number Diff line number Diff line change @@ -88,6 +88,27 @@ public static function create($type, array $attributes = [])
88
88
return $ class ;
89
89
}
90
90
91
+ /**
92
+ * Create an activitystream type from a JSON string
93
+ */
94
+ public static function fromJson (string $ json ): AbstractObject
95
+ {
96
+ $ data = json_decode ($ json , true );
97
+
98
+ if (json_last_error () === JSON_ERROR_NONE
99
+ && is_array ($ data )
100
+ ) {
101
+ return self ::create ($ data );
102
+ }
103
+
104
+ throw new Exception (
105
+ sprintf (
106
+ "An error occurred during the JSON decoding. \n '%s' " ,
107
+ $ json
108
+ )
109
+ );
110
+ }
111
+
91
112
/**
92
113
* Add a custom type definition
93
114
* It overrides defined types
Original file line number Diff line number Diff line change @@ -295,4 +295,42 @@ public function testCopyChaining()
295
295
$ original ->id
296
296
);
297
297
}
298
+
299
+ /**
300
+ * Test creating a type from a JSON string
301
+ */
302
+ public function testFromJson ()
303
+ {
304
+ $ json = '{"type":"Note","content":"A content for my note"} ' ;
305
+
306
+ $ note = Type::fromJson ($ json );
307
+
308
+ $ this ->assertEquals (
309
+ $ json ,
310
+ $ note ->toJson ()
311
+ );
312
+ }
313
+
314
+ /**
315
+ * Test creating a type from a malformed JSON string
316
+ */
317
+ public function testFromJsonMalformedJsonString ()
318
+ {
319
+ $ this ->expectException (Exception::class);
320
+
321
+ $ json = '{ ' ;
322
+ $ note = Type::fromJson ($ json );
323
+ }
324
+
325
+ /**
326
+ * Test creating a type from a JSON string which does not contains
327
+ * an array.
328
+ */
329
+ public function testFromJsonNotAnArray ()
330
+ {
331
+ $ this ->expectException (Exception::class);
332
+
333
+ $ json = '"OK" ' ;
334
+ $ note = Type::fromJson ($ json );
335
+ }
298
336
}
You can’t perform that action at this time.
0 commit comments