From 841d44a657ac199218711654a4e3d3528932d551 Mon Sep 17 00:00:00 2001 From: Gert de Pagter Date: Wed, 6 Nov 2019 09:31:45 +0100 Subject: [PATCH] Add more psalm assertions (#143) * Add annotation to valid array key This allows psalm to understand the method validates the input as correct array keys * Ass psalm annotation to is list This allows psalm to understand the output is a list. This does mean we bump the minimum version of psalm we are compatible with to 3.6. Otherwise it could interpet this as thinking the isList makes the value is the `list` class. --- ci/composer.json | 2 +- composer.json | 3 +++ src/Assert.php | 4 ++++ tests/static-analysis/assert-isList.php | 17 ++++++++++++++++ .../static-analysis/assert-validArrayKey.php | 20 +++++++++++++++++++ 5 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 tests/static-analysis/assert-isList.php create mode 100644 tests/static-analysis/assert-validArrayKey.php diff --git a/ci/composer.json b/ci/composer.json index b4989495..14a099d5 100644 --- a/ci/composer.json +++ b/ci/composer.json @@ -1,5 +1,5 @@ { "require": { - "vimeo/psalm": "^3.4" + "vimeo/psalm": "^3.6" } } diff --git a/composer.json b/composer.json index 5f985764..34350b29 100644 --- a/composer.json +++ b/composer.json @@ -20,6 +20,9 @@ "require-dev": { "phpunit/phpunit": "^4.8.36 || ^7.5.13" }, + "conflict": { + "vimeo/psalm": "<3.6.0" + }, "autoload": { "psr-4": { "Webmozart\\Assert\\": "src/" diff --git a/src/Assert.php b/src/Assert.php index f117d968..368897ac 100644 --- a/src/Assert.php +++ b/src/Assert.php @@ -1592,6 +1592,8 @@ public static function keyNotExists($array, $key, $message = '') /** * Checks if a value is a valid array key (int or string). * + * @psalm-assert array-key $value + * * @param mixed $value * @param string $message * @@ -1690,6 +1692,8 @@ public static function countBetween($array, $min, $max, $message = '') } /** + * @psalm-assert list $array + * * @param mixed $array * @param string $message * diff --git a/tests/static-analysis/assert-isList.php b/tests/static-analysis/assert-isList.php new file mode 100644 index 00000000..f83b2191 --- /dev/null +++ b/tests/static-analysis/assert-isList.php @@ -0,0 +1,17 @@ + + */ +function consume($value): array +{ + Assert::isList($value); + + return $value; +} diff --git a/tests/static-analysis/assert-validArrayKey.php b/tests/static-analysis/assert-validArrayKey.php new file mode 100644 index 00000000..b9fcf1d6 --- /dev/null +++ b/tests/static-analysis/assert-validArrayKey.php @@ -0,0 +1,20 @@ + $array + * + * @return array + */ +function consume($value, array $array): array +{ + Assert::validArrayKey($value); + + $array[$value] = 12; + + return $array; +}