From 2eefb14b6460775419566b0196926deb0d910b96 Mon Sep 17 00:00:00 2001 From: sc0Vu Date: Fri, 12 Jan 2018 10:49:52 +0800 Subject: [PATCH] Validators. --- src/Methods/EthMethod.php | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/Methods/EthMethod.php b/src/Methods/EthMethod.php index e73e589..82ad760 100644 --- a/src/Methods/EthMethod.php +++ b/src/Methods/EthMethod.php @@ -12,11 +12,19 @@ namespace Web3\Methods; use InvalidArgumentException; +use RuntimeException; use Web3\Methods\IMethod; use Web3\Methods\JSONRPC; class EthMethod extends JSONRPC implements IMethod { + /** + * validators + * + * @var array + */ + protected $validators = []; + /** * inputFormatters * @@ -70,6 +78,46 @@ class EthMethod extends JSONRPC implements IMethod return $this->outputFormatters; } + /** + * validate + * + * @param array $params + * @return bool + */ + public function validate($params) + { + if (!is_array($params)) { + throw new InvalidArgumentException('Please use array params when call validate.'); + } + $rules = $this->validators; + + if (count($params) < count($rules)) { + if (!isset($this->defaultValues) || empty($this->defaultValues)) { + throw new InvalidArgumentException('The params are less than validators.'); + } + $defaultValues = $this->defaultValues; + + foreach ($defaultValues as $key => $value) { + if (!isset($params[$key])) { + $params[$key] = $value; + } + + } + } elseif (count($params) > count($rules)) { + throw new InvalidArgumentException('The params are more than validators.'); + } + foreach ($rules as $key => $rule) { + if (isset($params[$key])) { + if (call_user_func([$rule, 'validate'], $params[$key]) === false) { + throw new RuntimeException('Wrong type of ' . $this->method . ' method argument ' . $key . '.'); + } + } else { + throw new RuntimeException($this->method . ' method argument ' . $key . ' doesn\'t have default value.'); + } + } + return true; + } + /** * transform *