Skip to content

Commit

Permalink
support for jsonclass objects
Browse files Browse the repository at this point in the history
  • Loading branch information
esler committed Feb 7, 2019
1 parent 9431ad4 commit fae92ad
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
vendor
composer.lock
.phpunit.result.cache
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"require": {
"php": "^7.2",
"ext-json": "*",
"guzzlehttp/guzzle": "^6.3"
"guzzlehttp/guzzle": "^6.3",
"phpunit/phpunit": "^8.0"
},
"autoload": {
"psr-4": {
Expand Down
7 changes: 7 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<phpunit colors="true">
<testsuites>
<testsuite name="unit tests">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>
14 changes: 14 additions & 0 deletions src/JsonRpc/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,23 @@ public static function fromJson(string $json): Response
if ($object = \json_decode($json)) {
$error = isset($object->error) ? Error::fromObject($object->error) : null;

self::convertJsonClass($object->result);

return new Response($object->result, $error, $object->id);
}

throw new Exception(\json_last_error_msg());
}

private static function convertJsonClass(object &$result): void {
foreach ($result as &$value) {
if (is_object($value) && isset($value->__jsonclass__)) {
switch ($value->__jsonclass__[0]) {
case 'datetime':
$value = new \DateTime($value->__jsonclass__[1], new \DateTimeZone('UTC'));
break;
}
}
}
}
}
25 changes: 25 additions & 0 deletions tests/JsonRpc/ResponseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Esler\JsonRpc;

use PHPUnit\Framework\TestCase;

class ResponseTest extends TestCase
{

function testExtendedJsonResult() {
$json = '{"id":123, "result": {"lastModified": {"__jsonclass__": ["datetime", "2018-09-11T07:50:32"]}}}';

$response = Response::fromJson($json);
$this->assertInstanceOf(Response::class, $response);

$result = $response->getResult();
$this->assertInstanceOf('stdClass', $result);
$this->assertObjectHasAttribute('lastModified', $result);

$lastModified = $result->lastModified;
$this->assertInstanceOf('DateTime', $lastModified);
$this->assertSame(1536652232, $lastModified->getTimestamp());
}

}

0 comments on commit fae92ad

Please sign in to comment.