Skip to content

Commit

Permalink
Added asPositiveInt() method
Browse files Browse the repository at this point in the history
  • Loading branch information
pascalbaljet committed Mar 30, 2024
1 parent bfb637d commit 29ca1ce
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,26 @@ public function asInt(): int
return $this->variable;
}

/**
* Asserts and narrow down the type to positive integer.
*
* @phpstan-assert positive-int $this->variable
*
* @return (TVariable is positive-int ? TVariable : never)
*/
public function asPositiveInt(): int
{
if (! is_int($this->variable)) {
throw new TypeError('Variable is not an [integer].');
}

if ($this->variable <= 0) {
throw new TypeError('Variable is not a [positive integer].');
}

return $this->variable;
}

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

declare(strict_types=1);

test('positive int', function (): void {
$variable = 1;

$value = type($variable)->asPositiveInt();

expect($value)->toBeInt();
});

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

type($variable)->asPositiveInt();
})->throws(TypeError::class, 'Variable is not an [integer].');

test('not a positive int', function (int $variable): void {
type($variable)->asPositiveInt();
})
->with([-1, 0])
->throws(TypeError::class, 'Variable is not a [positive integer].');
8 changes: 8 additions & 0 deletions types/AsPositiveIntTest.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 ? 'string' : 1;
assertType('int<1, max>', $x = type($variable)->asPositiveInt());

0 comments on commit 29ca1ce

Please sign in to comment.