Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 15 additions & 25 deletions src/Type/Php/InArrayFunctionTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,15 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n
}
$strictNodeType = $scope->getType($node->getArgs()[2]->value);
if (!(new ConstantBooleanType(true))->isSuperTypeOf($strictNodeType)->yes()) {
return new SpecifiedTypes([], []);
return new SpecifiedTypes();
}

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

$specifiedTypes = new SpecifiedTypes();

if (
$context->truthy()
|| count(TypeUtils::getConstantScalars($arrayValueType)) > 0
Expand All @@ -61,8 +63,6 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n
false,
$scope,
);
} else {
$specifiedTypes = new SpecifiedTypes([], []);
}

if (
Expand All @@ -71,31 +71,21 @@ public function specifyTypes(FunctionReflection $functionReflection, FuncCall $n
|| count(TypeUtils::getEnumCaseObjects($needleType)) > 0
) {
if ($context->truthy()) {
$arrayValueType = TypeCombinator::union($arrayValueType, $needleType);
$arrayType = TypeCombinator::intersect(
new ArrayType(new MixedType(), TypeCombinator::union($arrayValueType, $needleType)),
new NonEmptyArrayType(),
);
} else {
$arrayValueType = TypeCombinator::remove($arrayValueType, $needleType);
$arrayType = new ArrayType(new MixedType(), TypeCombinator::remove($arrayValueType, $needleType));
}

$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$node->getArgs()[1]->value,
new ArrayType(new MixedType(), $arrayValueType),
TypeSpecifierContext::createTrue(),
false,
$scope,
));
}

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

return $specifiedTypes;
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Analyser/data/in-array-non-empty.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,12 @@ public function sayHello(array $array): void
assertType('non-empty-array<int, string>', $array);
}
}

/** @param array<int> $haystack */
public function nonConstantNeedle(int $needle, array $haystack): void
{
if (in_array($needle, $haystack, true)) {
assertType('non-empty-array<int>', $haystack);
}
}
}