From a702e2e6155e9bb49e64eb728c5056aff5251fa9 Mon Sep 17 00:00:00 2001 From: Markus Staab Date: Wed, 27 Apr 2022 22:47:28 +0200 Subject: [PATCH] Support non-empty-array in InArrayFunctionTypeSpecifyingExtension --- ...InArrayFunctionTypeSpecifyingExtension.php | 17 +++++++++++++++- .../Analyser/NodeScopeResolverTest.php | 1 + .../Analyser/data/in-array-non-empty.php | 20 +++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/PHPStan/Analyser/data/in-array-non-empty.php diff --git a/src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php b/src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php index 65b38f234c..d0882cf6ce 100644 --- a/src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php +++ b/src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php @@ -9,6 +9,7 @@ use PHPStan\Analyser\TypeSpecifierAwareExtension; use PHPStan\Analyser\TypeSpecifierContext; use PHPStan\Reflection\FunctionReflection; +use PHPStan\Type\Accessory\NonEmptyArrayType; use PHPStan\Type\ArrayType; use PHPStan\Type\Constant\ConstantBooleanType; use PHPStan\Type\FunctionTypeSpecifyingExtension; @@ -45,7 +46,8 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n } $needleType = $scope->getType($node->getArgs()[0]->value); - $arrayValueType = $scope->getType($node->getArgs()[1]->value)->getIterableValueType(); + $arrayType = $scope->getType($node->getArgs()[1]->value); + $arrayValueType = $arrayType->getIterableValueType(); if ( $context->truthy() @@ -83,6 +85,19 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n )); } + if ( + $context->truthy() + && $arrayType->isArray()->yes() + ) { + $specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create( + $node->getArgs()[1]->value, + TypeCombinator::intersect($arrayType, new NonEmptyArrayType()), + $context, + false, + $scope, + )); + } + return $specifiedTypes; } diff --git a/tests/PHPStan/Analyser/NodeScopeResolverTest.php b/tests/PHPStan/Analyser/NodeScopeResolverTest.php index ae77180c18..5094afa198 100644 --- a/tests/PHPStan/Analyser/NodeScopeResolverTest.php +++ b/tests/PHPStan/Analyser/NodeScopeResolverTest.php @@ -914,6 +914,7 @@ public function dataFileAsserts(): iterable yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7031.php'); yield from $this->gatherAssertTypes(__DIR__ . '/data/constant-array-intersect.php'); yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7153.php'); + yield from $this->gatherAssertTypes(__DIR__ . '/data/in-array-non-empty.php'); } /** diff --git a/tests/PHPStan/Analyser/data/in-array-non-empty.php b/tests/PHPStan/Analyser/data/in-array-non-empty.php new file mode 100644 index 0000000000..abedc54538 --- /dev/null +++ b/tests/PHPStan/Analyser/data/in-array-non-empty.php @@ -0,0 +1,20 @@ + $array + */ + public function sayHello(array $array): void + { + if(in_array("thing", $array, true)){ + assertType('non-empty-array', $array); + } + } +}