Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

asNumeric() #5

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ composer require std-library/type-guard
## Usage

- [`as`](#as)
- [`asNumeric()`](#asnumeric)
- [`asInt()`](#asint)
- [`asFloat()`](#asfloat)
- [`asString()`](#asstring)
Expand All @@ -52,6 +53,14 @@ Asserts and narrows down the type of the given variable to a more specific type.
$variable = type($variable)->as(User::class);
```

### `asNumeric()`

Asserts and narrows down the type of the given variable to a numeric.

```php
$variable = type($variable)->asNumeric();
```

### `asInt()`

Asserts and narrows down the type of the given variable to an integer.
Expand Down
14 changes: 14 additions & 0 deletions src/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ public function asString(): string
return $this->variable;
}

/**
* Asserts and narrow down the type to numeric.
*
* @phpstan-assert-if-true int|float|numeric-string $this->variable
*/
public function asNumeric(): int|float|string
{
if (! is_numeric($this->variable)) {
throw new TypeError('Variable is not a numeric.');
}

return $this->variable;
}

/**
* Asserts and narrow down the type to integer.
*
Expand Down
26 changes: 26 additions & 0 deletions tests/AsNumericTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

test('numeric type', function ($variable): void {
$value = type($variable)->asNumeric();

expect($value)->toBeNumeric();
})->with([
7415541,
7415.541,
'7415541',
0b01100110,
0x66,
]);

test('not numeric type', function (): void {
$variable = 'string';

type($variable)->asNumeric();
})->with([
'',
'not numeric',
null,
[],
])->throws(TypeError::class, 'Variable is not a numeric.');
8 changes: 8 additions & 0 deletions types/AsNumericTest.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) !== 0 ? '7415541' : 'not numeric';
assertType('float|int|string', type($variable)->asNumeric());
Loading