From b61d90216e9e1f26279b6358075596c5cc78717c Mon Sep 17 00:00:00 2001 From: sc0Vu Date: Fri, 29 Dec 2017 16:39:17 +0800 Subject: [PATCH] json string to associative array --- src/Utils.php | 11 +++++++++-- test/unit/UtilsTest.php | 4 ++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Utils.php b/src/Utils.php index e1c34fd..44e309c 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -337,7 +337,7 @@ class Utils /** * jsonToArray * - * @param stdClass|array $json + * @param stdClass|array|string $json * @param int $depth * @return array */ @@ -374,8 +374,15 @@ class Utils } } } + } elseif (is_string($json)) { + $json = json_decode($json, true); + + if (JSON_ERROR_NONE !== json_last_error()) { + throw new InvalidArgumentException('json_decode error: ' . json_last_error_msg()); + } + return $json; } else { - throw new InvalidArgumentException('jsonToArray json must be array or stdClass.'); + throw new InvalidArgumentException('The json param to jsonToArray must be array or stdClass or string.'); } return $json; } diff --git a/test/unit/UtilsTest.php b/test/unit/UtilsTest.php index 18863c8..d496318 100644 --- a/test/unit/UtilsTest.php +++ b/test/unit/UtilsTest.php @@ -366,6 +366,10 @@ class UtilsTest extends TestCase $jsonArrayDepth2 = Utils::jsonToArray($jsonArrayDepth1, 2); $this->assertEquals($jsonArrayDepth2, $jsonAssoc); + + $jsonArray = Utils::jsonToArray($this->testJsonMethodString); + + $this->assertEquals($jsonArray, $jsonAssoc); } /**