From 192f16b542fb0b57135c88e2444d37b1fd6782d8 Mon Sep 17 00:00:00 2001 From: japatel Date: Tue, 27 Jan 2015 12:35:41 -0600 Subject: [PATCH] Fixes to Json conversion logic for empty objects - If the object is empty, an empty json object is generated on conversion - Fixes #223 --- lib/PayPal/Common/PayPalModel.php | 6 ++++++ tests/PayPal/Test/Common/NestedClass.php | 4 ++-- tests/PayPal/Test/Common/PayPalModelTest.php | 21 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/lib/PayPal/Common/PayPalModel.php b/lib/PayPal/Common/PayPalModel.php index ec1939a..39ab085 100644 --- a/lib/PayPal/Common/PayPalModel.php +++ b/lib/PayPal/Common/PayPalModel.php @@ -162,6 +162,12 @@ class PayPalModel $ret[$k] = $v; } } + // If the array is empty, which means an empty object, + // we need to convert array to StdClass object to properly + // represent JSON String + if (sizeof($ret) <= 0) { + $ret = new PayPalModel(); + } return $ret; } diff --git a/tests/PayPal/Test/Common/NestedClass.php b/tests/PayPal/Test/Common/NestedClass.php index 01be928..495a70f 100644 --- a/tests/PayPal/Test/Common/NestedClass.php +++ b/tests/PayPal/Test/Common/NestedClass.php @@ -18,7 +18,7 @@ class NestedClass extends PayPalModel /** * - * @param PayPal\Test\Common\ArrayClass $info + * @param \PayPal\Test\Common\ArrayClass $info */ public function setInfo($info) { @@ -27,7 +27,7 @@ class NestedClass extends PayPalModel /** * - * @return PayPal\Test\Common\ArrayClass + * @return \PayPal\Test\Common\ArrayClass */ public function getInfo() { diff --git a/tests/PayPal/Test/Common/PayPalModelTest.php b/tests/PayPal/Test/Common/PayPalModelTest.php index ccb20f6..b518cc5 100644 --- a/tests/PayPal/Test/Common/PayPalModelTest.php +++ b/tests/PayPal/Test/Common/PayPalModelTest.php @@ -184,6 +184,27 @@ class PayPalModelTest extends PHPUnit_Framework_TestCase } + /** + * @test + */ + public function testEmptyObject() + { + $child = new SimpleModelTestClass(); + $child->setField1(null); + + $parent = new ContainerModelTestClass(); + $parent->setField1("parent"); + $parent->setNested1($child); + + $this->assertEquals('{"field1":"parent","nested1":{}}', + $parent->toJSON()); + + $parentCopy = new ContainerModelTestClass(); + $parentCopy->fromJson($parent->toJSON()); + $this->assertEquals($parent, $parentCopy); + + } + /** * @test */