Skip to content

Commit

Permalink
add float validator to simple checker
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 9, 2021
1 parent 60eda52 commit 0502bed
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
32 changes: 32 additions & 0 deletions src/Simple/ValidData.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/Validators.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
1 change: 0 additions & 1 deletion test/IssuesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Inhere\ValidateTest;

use Inhere\Validate\Validation;
use function vdump;

/**
* class IssuesTest
Expand Down
3 changes: 3 additions & 0 deletions test/Simple/ValidDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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'));
Expand Down

0 comments on commit 0502bed

Please sign in to comment.