Skip to content

Commit 5b2d7b6

Browse files
clxmstaabondrejmirtes
authored andcommitted
Support non-empty-array in InArrayFunctionTypeSpecifyingExtension
1 parent 82dfce1 commit 5b2d7b6

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PHPStan\Analyser\TypeSpecifierAwareExtension;
1010
use PHPStan\Analyser\TypeSpecifierContext;
1111
use PHPStan\Reflection\FunctionReflection;
12+
use PHPStan\Type\Accessory\NonEmptyArrayType;
1213
use PHPStan\Type\ArrayType;
1314
use PHPStan\Type\Constant\ConstantBooleanType;
1415
use PHPStan\Type\FunctionTypeSpecifyingExtension;
@@ -45,7 +46,8 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n
4546
}
4647

4748
$needleType = $scope->getType($node->getArgs()[0]->value);
48-
$arrayValueType = $scope->getType($node->getArgs()[1]->value)->getIterableValueType();
49+
$arrayType = $scope->getType($node->getArgs()[1]->value);
50+
$arrayValueType = $arrayType->getIterableValueType();
4951

5052
if (
5153
$context->truthy()
@@ -83,6 +85,19 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n
8385
));
8486
}
8587

88+
if (
89+
$context->truthy()
90+
&& $arrayType->isArray()->yes()
91+
) {
92+
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
93+
$node->getArgs()[1]->value,
94+
TypeCombinator::intersect($arrayType, new NonEmptyArrayType()),
95+
$context,
96+
false,
97+
$scope,
98+
));
99+
}
100+
86101
return $specifiedTypes;
87102
}
88103

tests/PHPStan/Analyser/NodeScopeResolverTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -914,6 +914,7 @@ public function dataFileAsserts(): iterable
914914
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7031.php');
915915
yield from $this->gatherAssertTypes(__DIR__ . '/data/constant-array-intersect.php');
916916
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7153.php');
917+
yield from $this->gatherAssertTypes(__DIR__ . '/data/in-array-non-empty.php');
917918
}
918919

919920
/**
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace InArrayNonEmpty;
6+
7+
use function PHPStan\Testing\assertType;
8+
9+
class HelloWorld
10+
{
11+
/**
12+
* @phpstan-param list<string> $array
13+
*/
14+
public function sayHello(array $array): void
15+
{
16+
if(in_array("thing", $array, true)){
17+
assertType('non-empty-array<int, string>', $array);
18+
}
19+
}
20+
}

0 commit comments

Comments
 (0)