Skip to content

Commit

Permalink
Merge pull request #3 from faissaloux/asFloat
Browse files Browse the repository at this point in the history
`asFloat()`
  • Loading branch information
nunomaduro authored Mar 30, 2024
2 parents b2608c4 + 673a3a6 commit 4dabfb2
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ composer require std-library/type-guard
## Usage

- [`asInt()`](#asint)
- [`asFloat()`](#asfloat)
- [`asString()`](#asstring)
- [`asBool()`](#asbool)

Expand All @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions src/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -63,5 +77,6 @@ public function asBool(): bool
}

return $this->variable;

}
}
15 changes: 15 additions & 0 deletions tests/AsFloatTest.php
Original file line number Diff line number Diff line change
@@ -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.');
8 changes: 8 additions & 0 deletions types/AsFloatTest.php
Original file line number Diff line number Diff line change
@@ -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());

0 comments on commit 4dabfb2

Please sign in to comment.