jsonMethodToString

This commit is contained in:
sc0Vu 2017-12-25 11:19:14 +08:00
parent afb0225721
commit e25e0cc3f1
2 changed files with 92 additions and 0 deletions

View File

@ -12,6 +12,7 @@
namespace Web3;
use InvalidArgumentException;
use stdClass;
use kornrunner\Keccak;
use phpseclib\Math\BigInteger as BigNumber;
@ -251,4 +252,47 @@ class Utils
return $bn->divide($bnt);
}
/**
* jsonMethodToString
*
* @param stdClass|array $json
* @return string
*/
public static function jsonMethodToString($json)
{
if ($json instanceof stdClass) {
// one way to change whole json stdClass to array type
// $jsonString = json_encode($json);
// if (JSON_ERROR_NONE !== json_last_error()) {
// throw new InvalidArgumentException('json_decode error: ' . json_last_error_msg());
// }
// $json = json_decode($jsonString, true);
// another way to change json to array type but not whole json stdClass
$json = (array) $json;
$typeName = [];
foreach ($json['inputs'] as $param) {
if (isset($param->type)) {
$typeName[] = $param->type;
}
}
return $json['name'] . '(' . implode(',', $typeName) . ')';
} elseif (!is_array($json)) {
throw new InvalidArgumentException('jsonMethodToString json must be array or stdClass.');
}
if (isset($json['name']) && (bool) strpos('(', $json['name']) === true) {
return $json['name'];
}
$typeName = [];
foreach ($json['inputs'] as $param) {
if (isset($param['type'])) {
$typeName[] = $param['type'];
}
}
return $json['name'] . '(' . implode(',', $typeName) . ')';
}
}

View File

@ -17,6 +17,36 @@ class UtilsTest extends TestCase
*/
protected $testHex = '68656c6c6f20776f726c64';
/**
* testJsonMethodString
* from GameToken approve function
*
* @var string
*/
protected $testJsonMethodString = '{
"constant": false,
"inputs": [
{
"name": "_spender",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}';
/**
* setUp
*
@ -213,4 +243,22 @@ class UtilsTest extends TestCase
$this->assertEquals($bnq->toString(), '21');
$this->assertEquals($bnr->toString(), '16');
}
/**
* testJsonMethodToString
*
* @return void
*/
public function testJsonMethodToString()
{
$json = json_decode($this->testJsonMethodString);
$methodString = Utils::jsonMethodToString($json);
$this->assertEquals($methodString, 'approve(address,uint256)');
$json = json_decode($this->testJsonMethodString, true);
$methodString = Utils::jsonMethodToString($json);
$this->assertEquals($methodString, 'approve(address,uint256)');
}
}