Skip to content

Commit

Permalink
asNumeric
Browse files Browse the repository at this point in the history
  • Loading branch information
faissaloux committed Mar 30, 2024
1 parent 1d30315 commit cd86cbc
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ public function asString(): string
return $this->variable;
}

/**
* Asserts and narrow down the type to numeric.
*/
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
24 changes: 24 additions & 0 deletions tests/AsNumericTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

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

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

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

type($variable)->asNumeric();
})->with([
"",
"not numeric",
null,
[]
])->throws(TypeError::class, 'Variable is not a numeric.');

0 comments on commit cd86cbc

Please sign in to comment.