diff --git a/README.md b/README.md index 717426c..3a7900e 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ composer require std-library/type-guard ## Usage - [`asInt()`](#asint) +- [`asFloat()`](#asfloat) - [`asString()`](#asstring) - [`asBool()`](#asbool) @@ -48,6 +49,14 @@ Asserts and narrows down the type of the given variable to an integer. $variable = type($variable)->asInt(); ``` +### `asFloat()` + +Asserts and narrows down the type of the given variable to a float. + +```php +$variable = type($variable)->asFloat(); +``` + ### `asString()` Asserts and narrows down the type of the given variable to a string. diff --git a/src/Type.php b/src/Type.php index 05048a0..b57f694 100644 --- a/src/Type.php +++ b/src/Type.php @@ -51,6 +51,20 @@ public function asInt(): int return $this->variable; } + /** + * Asserts and narrow down the type to float. + * + * @phpstan-assert-if-true float $this->variable + */ + public function asFloat(): float + { + if (! is_float($this->variable)) { + throw new TypeError('Variable is not a float.'); + } + + return $this->variable; + } + /** * Asserts and narrow down the type to boolean. * @@ -63,5 +77,6 @@ public function asBool(): bool } return $this->variable; + } } diff --git a/tests/AsFloatTest.php b/tests/AsFloatTest.php new file mode 100644 index 0000000..bee27aa --- /dev/null +++ b/tests/AsFloatTest.php @@ -0,0 +1,15 @@ +<?php + +test('float type', function () { + $variable = 7415.541; + + $value = type($variable)->asFloat(); + + expect($value)->toBeFloat(); +}); + +test('not float type', function () { + $variable = 7415541; + + type($variable)->asFloat(); +})->throws(TypeError::class, 'Variable is not a float.'); diff --git a/types/AsFloatTest.php b/types/AsFloatTest.php new file mode 100644 index 0000000..8a2cf08 --- /dev/null +++ b/types/AsFloatTest.php @@ -0,0 +1,8 @@ +<?php + +declare(strict_types=1); + +use function PHPStan\Testing\assertType; + +$variable = random_int(0, 1) ? 7415.541 : 7415541; +assertType('float', type($variable)->asFloat());