From eeba9a1ba76bde7d7338b7ef59aec32385892091 Mon Sep 17 00:00:00 2001 From: faissaloux Date: Sat, 30 Mar 2024 01:38:27 +0000 Subject: [PATCH 1/3] fix conflict --- src/Type.php | 15 +++++++++++++++ tests/AsFloatTest.php | 15 +++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tests/AsFloatTest.php diff --git a/src/Type.php b/src/Type.php index a7a8c79..4972462 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. */ @@ -61,5 +75,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 @@ +asFloat(); + + expect($value)->toBeFloat(); +}); + +test('not float type', function () { + $variable = 7415541; + + type($variable)->asFloat(); +})->throws(TypeError::class, 'Variable is not a float.'); From d30f9f52aeb3d320952f4154450578383fbb4c76 Mon Sep 17 00:00:00 2001 From: faissaloux Date: Sat, 30 Mar 2024 00:11:31 +0000 Subject: [PATCH 2/3] documentation --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) 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. From 673a3a6eda2ed378ab7cce6deb2662649d8e7c47 Mon Sep 17 00:00:00 2001 From: faissaloux Date: Sat, 30 Mar 2024 01:23:28 +0000 Subject: [PATCH 3/3] type test --- types/AsFloatTest.php | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 types/AsFloatTest.php 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 @@ +asFloat());