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 committed Apr 28, 2022
1 parent 6ebf236 commit f2b37e6
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php
Expand Up @@ -9,8 +9,10 @@
use PHPStan\Analyser\TypeSpecifierAwareExtension;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\FunctionTypeSpecifyingExtension;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
use function count;
use function strtolower;
Expand Down Expand Up @@ -41,22 +43,36 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n
return new SpecifiedTypes([], []);
}

$arrayValueType = $scope->getType($node->getArgs()[1]->value)->getIterableValueType();
$arrayType = $scope->getType($node->getArgs()[1]->value);
$arrayValueType = $arrayType->getIterableValueType();

$specifiedTypes = new SpecifiedTypes([], []);

if (
$context->truthy()
|| count(TypeUtils::getConstantScalars($arrayValueType)) > 0
) {
return $this->typeSpecifier->create(
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$node->getArgs()[0]->value,
$arrayValueType,
$context,
false,
$scope,
);
));
}

if ($context->true()
&& $arrayType->isArray()->yes()) {
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$node->getArgs()[1]->value,
TypeCombinator::intersect($arrayType, new NonEmptyArrayType()),
$context,
false,
$scope,
));
}

return new SpecifiedTypes([], []);
return $specifiedTypes;
}

}
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Expand Up @@ -903,6 +903,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7115.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/constant-array-type-identical.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/non-empty-string-str-containing-fns.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 f2b37e6

Please sign in to comment.