diff --git a/CHANGELOG.md b/CHANGELOG.md index 8629248..5384291 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Changelog ## UNRELEASED +* Added `Assert::numericString()` + ## 1.10.0 ### Added diff --git a/README.md b/README.md index 3b2397a..a2d37a6 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ Method | Description -------------------------------------------------------- | -------------------------------------------------- `string($value, $message = '')` | Check that a value is a string `stringNotEmpty($value, $message = '')` | Check that a value is a non-empty string +`numericString($value, $message = '')` | Check that a value is a numeric-string `integer($value, $message = '')` | Check that a value is an integer `integerish($value, $message = '')` | Check that a value casts to an integer `positiveInteger($value, $message = '')` | Check that a value is a positive (non-zero) integer diff --git a/src/Assert.php b/src/Assert.php index 5451fe1..ea8586e 100644 --- a/src/Assert.php +++ b/src/Assert.php @@ -53,6 +53,26 @@ public static function string($value, $message = '') } } + /** + * @psalm-pure + * @psalm-assert numeric-string $value + * + * @param mixed $value + * + * @throws InvalidArgumentException + */ + public static function numericString($value, string $message = ''): void + { + static::string($value, $message ?? 'Expected a numeric string. Got: %s'); + + if (!\is_numeric($value)) { + static::reportInvalidArgument(\sprintf( + $message ?? 'Expected a numeric string. Got: %s', + static::typeToString($value) + )); + } + } + /** * @psalm-pure * @psalm-assert non-empty-string $value diff --git a/src/Mixin.php b/src/Mixin.php index 41ebf9b..adf4cb0 100644 --- a/src/Mixin.php +++ b/src/Mixin.php @@ -49,6 +49,40 @@ public static function allString($value, $message = '') } } + /** + * @psalm-pure + * @psalm-assert numeric-string|null $value + * + * @param mixed $value + * + * @throws InvalidArgumentException + * + * @return void + */ + public static function nullOrNumericString($value, $message = '') + { + null === $value || static::numericString($value, $message); + } + + /** + * @psalm-pure + * @psalm-assert iterable $value + * + * @param mixed $value + * + * @throws InvalidArgumentException + * + * @return void + */ + public static function allNumericString($value, $message = '') + { + static::isIterable($value); + + foreach ($value as $entry) { + static::numericString($entry, $message); + } + } + /** * @psalm-pure * @psalm-assert non-empty-string|null $value diff --git a/tests/static-analysis/assert-numericString.php b/tests/static-analysis/assert-numericString.php new file mode 100644 index 0000000..4f9315d --- /dev/null +++ b/tests/static-analysis/assert-numericString.php @@ -0,0 +1,47 @@ + + */ +function allNumericString($value): iterable +{ + Assert::allNumericString($value); + + return $value; +}