Skip to content

Commit

Permalink
Add Type Factory fromJson() method
Browse files Browse the repository at this point in the history
  • Loading branch information
landrok committed Jan 30, 2021
1 parent 45670fb commit 32e20fc
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,22 @@ $note = Type::create($array);

```

You may create a type from a JSON string with the `fromJson()` method.
JSON must have a `type` key.

```php
use ActivityPhp\Type;

$json = '
{
"type": "Note",
"content": "A content for my note"
}';

$note = Type::fromJson($json);

```

When a property does not exist, an Exception is thrown in strict mode.
You can define 3 different behaviours:

Expand Down
21 changes: 21 additions & 0 deletions src/ActivityPhp/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,27 @@ public static function create($type, array $attributes = [])
return $class;
}

/**
* Create an activitystream type from a JSON string
*/
public static function fromJson(string $json): AbstractObject
{
$data = json_decode($json, true);

if (json_last_error() === JSON_ERROR_NONE
&& is_array($data)
) {
return self::create($data);
}

throw new Exception(
sprintf(
"An error occurred during the JSON decoding.\n '%s'",
$json
)
);
}

/**
* Add a custom type definition
* It overrides defined types
Expand Down
38 changes: 38 additions & 0 deletions tests/ActivityPhp/Type/FactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -295,4 +295,42 @@ public function testCopyChaining()
$original->id
);
}

/**
* Test creating a type from a JSON string
*/
public function testFromJson()
{
$json = '{"type":"Note","content":"A content for my note"}';

$note = Type::fromJson($json);

$this->assertEquals(
$json,
$note->toJson()
);
}

/**
* Test creating a type from a malformed JSON string
*/
public function testFromJsonMalformedJsonString()
{
$this->expectException(Exception::class);

$json = '{';
$note = Type::fromJson($json);
}

/**
* Test creating a type from a JSON string which does not contains
* an array.
*/
public function testFromJsonNotAnArray()
{
$this->expectException(Exception::class);

$json = '"OK"';
$note = Type::fromJson($json);
}
}

0 comments on commit 32e20fc

Please sign in to comment.