Skip to content

Commit

Permalink
Support non-empty-array in InArrayFunctionTypeSpecifyingExtension
Browse files Browse the repository at this point in the history
  • Loading branch information
clxmstaab authored and ondrejmirtes committed Jun 17, 2022
1 parent 82dfce1 commit 5b2d7b6
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php
Expand Up @@ -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;
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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;
}

Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Expand Up @@ -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');
}

/**
Expand Down
20 changes: 20 additions & 0 deletions tests/PHPStan/Analyser/data/in-array-non-empty.php
@@ -0,0 +1,20 @@
<?php

declare(strict_types = 1);

namespace InArrayNonEmpty;

use function PHPStan\Testing\assertType;

class HelloWorld
{
/**
* @phpstan-param list<string> $array
*/
public function sayHello(array $array): void
{
if(in_array("thing", $array, true)){
assertType('non-empty-array<int, string>', $array);
}
}
}

0 comments on commit 5b2d7b6

Please sign in to comment.