diff --git a/src/Utils.php b/src/Utils.php index 1792200..ebe959f 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -295,4 +295,37 @@ class Utils } return $json['name'] . '(' . implode(',', $typeName) . ')'; } + + /** + * jsonToArray + * + * @param stdClass|array $json + * @param int $depth + * @return array + */ + public static function jsonToArray($json, $depth=1) + { + if (!is_int($depth)) { + throw new InvalidArgumentException('jsonToArray depth must be int.'); + } + if ($depth <= 0) { + return []; + } + if ($json instanceof stdClass) { + $json = (array) $json; + $typeName = []; + + foreach ($json as $key => $param) { + if (is_array($param) && $depth > 1) { + foreach ($param as $subKey => $subParam) { + $json[$key][$subKey] = self::jsonToArray($subParam, $depth-1); + } + } + } + return $json; + } elseif (!is_array($json)) { + throw new InvalidArgumentException('jsonToArray json must be array or stdClass.'); + } + return $json; + } } \ No newline at end of file diff --git a/test/unit/UtilsTest.php b/test/unit/UtilsTest.php index 366d70d..1587cfb 100644 --- a/test/unit/UtilsTest.php +++ b/test/unit/UtilsTest.php @@ -261,4 +261,22 @@ class UtilsTest extends TestCase $this->assertEquals($methodString, 'approve(address,uint256)'); } + + /** + * testJsonToArray + * + * @return void + */ + public function testJsonToArray() + { + $json = json_decode($this->testJsonMethodString); + $jsonArray = Utils::jsonToArray($json); + + $this->assertEquals($jsonArray, (array) $json); + + $jsonAssoc = json_decode($this->testJsonMethodString, true); + $jsonArray = Utils::jsonToArray($json, 2); + + $this->assertEquals($jsonArray, $jsonAssoc); + } } \ No newline at end of file