From 29ca1ce692662a9debd01475454b7189b924d789 Mon Sep 17 00:00:00 2001 From: Pascal Baljet Date: Sat, 30 Mar 2024 20:58:12 +0100 Subject: [PATCH] Added `asPositiveInt()` method --- src/Type.php | 20 ++++++++++++++++++++ tests/AsPositiveIntTest.php | 23 +++++++++++++++++++++++ types/AsPositiveIntTest.php | 8 ++++++++ 3 files changed, 51 insertions(+) create mode 100644 tests/AsPositiveIntTest.php create mode 100644 types/AsPositiveIntTest.php diff --git a/src/Type.php b/src/Type.php index 0748f3f..1222f24 100644 --- a/src/Type.php +++ b/src/Type.php @@ -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. * diff --git a/tests/AsPositiveIntTest.php b/tests/AsPositiveIntTest.php new file mode 100644 index 0000000..8a2d47f --- /dev/null +++ b/tests/AsPositiveIntTest.php @@ -0,0 +1,23 @@ +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].'); diff --git a/types/AsPositiveIntTest.php b/types/AsPositiveIntTest.php new file mode 100644 index 0000000..37dbaca --- /dev/null +++ b/types/AsPositiveIntTest.php @@ -0,0 +1,8 @@ +', $x = type($variable)->asPositiveInt());