Skip to content

Commit 0502bed

Browse files
committed
add float validator to simple checker
1 parent 60eda52 commit 0502bed

File tree

4 files changed

+39
-1
lines changed

4 files changed

+39
-1
lines changed

src/Simple/ValidData.php

+32
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,38 @@ public static function getIntsBySplit(string $field, int $min = null, int $max =
133133
return $arr ? array_map('intval', $arr) : [];
134134
}
135135

136+
/**
137+
* @param string $field
138+
* @param float|null $min
139+
* @param float|null $max
140+
* @param float|null $default
141+
*
142+
* @return float
143+
*/
144+
public static function getFloat(string $field, float $min = null, float $max = null, float $default = null): float
145+
{
146+
if (!isset(self::$data[$field])) {
147+
if ($default === null) {
148+
throw self::newEx($field, 'is required and must be float');
149+
}
150+
return $default;
151+
}
152+
153+
$val = self::$data[$field];
154+
if (is_numeric($val)) {
155+
$val = (float)$val;
156+
157+
// check min and max
158+
if (!Validators::float($val, $min, $max)) {
159+
throw static::newEx($field, self::fmtMinMaxToMsg('must be float', $min, $max));
160+
}
161+
162+
return $val;
163+
}
164+
165+
throw self::newEx($field, 'required and must be float value');
166+
}
167+
136168
/**
137169
* @param string $field
138170
* @param int|null $minLen

src/Validators.php

+4
Original file line numberDiff line numberDiff line change
@@ -787,6 +787,10 @@ public static function email($val, $default = null): bool
787787
*/
788788
public static function ip($val, $default = null, $flags = 0): bool
789789
{
790+
if (!is_string($val)) {
791+
return false;
792+
}
793+
790794
$settings = (int)$flags !== 0 ? ['flags' => (int)$flags] : [];
791795

792796
if ($default !== null) {

test/IssuesTest.php

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
namespace Inhere\ValidateTest;
44

55
use Inhere\Validate\Validation;
6-
use function vdump;
76

87
/**
98
* class IssuesTest

test/Simple/ValidDataTest.php

+3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class ValidDataTest extends BaseValidateTestCase
1717
'num' => '23',
1818
'str' => 'abc',
1919
'str1' => ' abc ',
20+
'flt' => '2.33',
2021
'arr' => ['ab', 'cd'],
2122
'ints' => ['23', 25],
2223
'strs' => ['23', 'cd', 25],
@@ -37,6 +38,8 @@ public function testBasicOK(): void
3738
$data = $this->testData;
3839

3940
$this->assertSame(23, VData::getInt('int'));
41+
$this->assertSame(2.33, VData::getFloat('flt'));
42+
$this->assertSame(23.0, VData::getFloat('int'));
4043
$this->assertSame('abc', VData::getString('str'));
4144
$this->assertSame('abc', VData::getString('str1'));
4245
$this->assertSame($data['arr'], VData::getArray('arr'));

0 commit comments

Comments
 (0)