From 0502bedb3797d673bfaeccf779c55541a108104f Mon Sep 17 00:00:00 2001 From: inhere Date: Thu, 9 Sep 2021 10:51:44 +0800 Subject: [PATCH] add float validator to simple checker --- src/Simple/ValidData.php | 32 ++++++++++++++++++++++++++++++++ src/Validators.php | 4 ++++ test/IssuesTest.php | 1 - test/Simple/ValidDataTest.php | 3 +++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Simple/ValidData.php b/src/Simple/ValidData.php index a050bfd..f4640ee 100644 --- a/src/Simple/ValidData.php +++ b/src/Simple/ValidData.php @@ -133,6 +133,38 @@ public static function getIntsBySplit(string $field, int $min = null, int $max = return $arr ? array_map('intval', $arr) : []; } + /** + * @param string $field + * @param float|null $min + * @param float|null $max + * @param float|null $default + * + * @return float + */ + public static function getFloat(string $field, float $min = null, float $max = null, float $default = null): float + { + if (!isset(self::$data[$field])) { + if ($default === null) { + throw self::newEx($field, 'is required and must be float'); + } + return $default; + } + + $val = self::$data[$field]; + if (is_numeric($val)) { + $val = (float)$val; + + // check min and max + if (!Validators::float($val, $min, $max)) { + throw static::newEx($field, self::fmtMinMaxToMsg('must be float', $min, $max)); + } + + return $val; + } + + throw self::newEx($field, 'required and must be float value'); + } + /** * @param string $field * @param int|null $minLen diff --git a/src/Validators.php b/src/Validators.php index 4874cee..8ae5aac 100644 --- a/src/Validators.php +++ b/src/Validators.php @@ -787,6 +787,10 @@ public static function email($val, $default = null): bool */ public static function ip($val, $default = null, $flags = 0): bool { + if (!is_string($val)) { + return false; + } + $settings = (int)$flags !== 0 ? ['flags' => (int)$flags] : []; if ($default !== null) { diff --git a/test/IssuesTest.php b/test/IssuesTest.php index b5bb9e2..50b19ec 100644 --- a/test/IssuesTest.php +++ b/test/IssuesTest.php @@ -3,7 +3,6 @@ namespace Inhere\ValidateTest; use Inhere\Validate\Validation; -use function vdump; /** * class IssuesTest diff --git a/test/Simple/ValidDataTest.php b/test/Simple/ValidDataTest.php index 2c3e31d..e0a2d6b 100644 --- a/test/Simple/ValidDataTest.php +++ b/test/Simple/ValidDataTest.php @@ -17,6 +17,7 @@ class ValidDataTest extends BaseValidateTestCase 'num' => '23', 'str' => 'abc', 'str1' => ' abc ', + 'flt' => '2.33', 'arr' => ['ab', 'cd'], 'ints' => ['23', 25], 'strs' => ['23', 'cd', 25], @@ -37,6 +38,8 @@ public function testBasicOK(): void $data = $this->testData; $this->assertSame(23, VData::getInt('int')); + $this->assertSame(2.33, VData::getFloat('flt')); + $this->assertSame(23.0, VData::getFloat('int')); $this->assertSame('abc', VData::getString('str')); $this->assertSame('abc', VData::getString('str1')); $this->assertSame($data['arr'], VData::getArray('arr'));