Utils jsonToArray

This commit is contained in:
sc0Vu 2017-12-26 11:59:16 +08:00
parent 0fc3e27651
commit 59c1876818
2 changed files with 51 additions and 0 deletions

View File

@ -295,4 +295,37 @@ class Utils
} }
return $json['name'] . '(' . implode(',', $typeName) . ')'; 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;
}
} }

View File

@ -261,4 +261,22 @@ class UtilsTest extends TestCase
$this->assertEquals($methodString, 'approve(address,uint256)'); $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);
}
} }