Skip to content

Commit 32e20fc

Browse files
committed
Add Type Factory fromJson() method
1 parent 45670fb commit 32e20fc

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

docs/index.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,22 @@ $note = Type::create($array);
114114

115115
```
116116

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+
117133
When a property does not exist, an Exception is thrown in strict mode.
118134
You can define 3 different behaviours:
119135

src/ActivityPhp/Type.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,27 @@ public static function create($type, array $attributes = [])
8888
return $class;
8989
}
9090

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+
91112
/**
92113
* Add a custom type definition
93114
* It overrides defined types

tests/ActivityPhp/Type/FactoryTest.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,4 +295,42 @@ public function testCopyChaining()
295295
$original->id
296296
);
297297
}
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+
}
298336
}

0 commit comments

Comments
 (0)