From fceb2d6e2160a6dea24ce3eea09f6c5563104e22 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Wed, 9 Oct 2013 20:33:06 -0400 Subject: [PATCH] Fixes #957: Json::encode() doesn't handle empty object correctly. --- framework/yii/helpers/BaseJson.php | 34 +++++++++++++------------------ tests/unit/framework/helpers/JsonTest.php | 4 ++++ 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/framework/yii/helpers/BaseJson.php b/framework/yii/helpers/BaseJson.php index bd6ede5..80224d5 100644 --- a/framework/yii/helpers/BaseJson.php +++ b/framework/yii/helpers/BaseJson.php @@ -81,32 +81,26 @@ class BaseJson */ protected static function processData($data, &$expressions, $expPrefix) { - if (is_array($data)) { - foreach ($data as $key => $value) { - if (is_array($value) || is_object($value)) { - $data[$key] = static::processData($value, $expressions, $expPrefix); - } - } - return $data; - } elseif (is_object($data)) { + if (is_object($data)) { if ($data instanceof JsExpression) { $token = "!{[$expPrefix=" . count($expressions) . ']}!'; $expressions['"' . $token . '"'] = $data->expression; return $token; - } else { - $data = $data instanceof Arrayable ? $data->toArray() : get_object_vars($data); - $result = array(); - foreach ($data as $key => $value) { - if (is_array($value) || is_object($value)) { - $result[$key] = static::processData($value, $expressions, $expPrefix); - } else { - $result[$key] = $value; - } + } + $data = $data instanceof Arrayable ? $data->toArray() : get_object_vars($data); + if ($data === array() && !$data instanceof Arrayable) { + return new \stdClass(); + } + } + + if (is_array($data)) { + foreach ($data as $key => $value) { + if (is_array($value) || is_object($value)) { + $data[$key] = static::processData($value, $expressions, $expPrefix); } - return $result; } - } else { - return $data; } + + return $data; } } diff --git a/tests/unit/framework/helpers/JsonTest.php b/tests/unit/framework/helpers/JsonTest.php index df2ca5f..069fdc3 100644 --- a/tests/unit/framework/helpers/JsonTest.php +++ b/tests/unit/framework/helpers/JsonTest.php @@ -45,6 +45,10 @@ class JsonTest extends TestCase 'b' => new JsExpression($expression2), ); $this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::encode($data)); + + // https://github.com/yiisoft/yii2/issues/957 + $data = (object)null; + $this->assertSame('{}', Json::encode($data)); } public function testDecode()