Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
11 changes: 9 additions & 2 deletions src/Rules/Api/GetTemplateTypeRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Reflection\ReflectionProvider;
Expand Down Expand Up @@ -43,6 +44,12 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

$classArg = ArgumentsNormalizer::getArgByPositionOrName($args, 0, 'ancestorClassName');
$templateArg = ArgumentsNormalizer::getArgByPositionOrName($args, 1, 'templateTypeName');
if ($classArg === null || $templateArg === null) {
return [];
}

$calledOnType = $scope->getType($node->var);
$methodReflection = $scope->getMethodReflection($calledOnType, $node->name->toString());
if ($methodReflection === null) {
Expand All @@ -53,8 +60,8 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

$classType = $scope->getType($args[0]->value);
$templateType = $scope->getType($args[1]->value);
$classType = $scope->getType($classArg->value);
$templateType = $scope->getType($templateArg->value);
$errors = [];
foreach ($classType->getConstantStrings() as $classNameType) {
if (!$this->reflectionProvider->hasClass($classNameType->getValue())) {
Expand Down
87 changes: 47 additions & 40 deletions src/Rules/Arrays/NonexistentOffsetInArrayDimFetchRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\NullsafeOperatorHelper;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredParameter;
Expand Down Expand Up @@ -117,17 +118,20 @@ public function processNode(Node $node, Scope $scope): array
&& in_array($node->dim->name->toLowerString(), ['array_key_first', 'array_key_last'], true)
&& count($node->dim->getArgs()) >= 1
) {
$arrayArg = $node->dim->getArgs()[0]->value;
$arrayType = $scope->getType($arrayArg);
if (
$arrayArg instanceof Node\Expr\Variable
&& $node->var instanceof Node\Expr\Variable
&& is_string($arrayArg->name)
&& $arrayArg->name === $node->var->name
&& $arrayType->isArray()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
) {
return [];
$arrayArg = ArgumentsNormalizer::getArgByPositionOrName($node->dim->getArgs(), 0, 'array');
if ($arrayArg !== null) {
$arrayArg = $arrayArg->value;
$arrayType = $scope->getType($arrayArg);
if (
$arrayArg instanceof Node\Expr\Variable
&& $node->var instanceof Node\Expr\Variable
&& is_string($arrayArg->name)
&& $arrayArg->name === $node->var->name
&& $arrayType->isArray()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
) {
return [];
}
}
}

Expand All @@ -137,24 +141,24 @@ public function processNode(Node $node, Scope $scope): array
&& $node->dim->name->toLowerString() === 'array_rand'
&& count($node->dim->getArgs()) >= 1
) {
$numArg = null;
$arrayArg = $node->dim->getArgs()[0]->value;
if (count($node->dim->getArgs()) > 1) {
$numArg = $node->dim->getArgs()[1]->value;
}
$one = new ConstantIntegerType(1);
$arrayType = $scope->getType($arrayArg);

if (
$arrayArg instanceof Node\Expr\Variable
&& $node->var instanceof Node\Expr\Variable
&& is_string($arrayArg->name)
&& $arrayArg->name === $node->var->name
&& $arrayType->isArray()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
&& ($numArg === null || $one->isSuperTypeOf($scope->getType($numArg))->yes())
) {
return [];
$arrayArg = ArgumentsNormalizer::getArgByPositionOrName($node->dim->getArgs(), 0, 'array');
if ($arrayArg !== null) {
$arrayArg = $arrayArg->value;
$numArg = ArgumentsNormalizer::getArgByPositionOrName($node->dim->getArgs(), 1, 'num');
$one = new ConstantIntegerType(1);
$arrayType = $scope->getType($arrayArg);

if (
$arrayArg instanceof Node\Expr\Variable
&& $node->var instanceof Node\Expr\Variable
&& is_string($arrayArg->name)
&& $arrayArg->name === $node->var->name
&& $arrayType->isArray()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
&& ($numArg === null || $one->isSuperTypeOf($scope->getType($numArg->value))->yes())
) {
return [];
}
}
}

Expand All @@ -167,17 +171,20 @@ public function processNode(Node $node, Scope $scope): array
&& $node->dim->right instanceof Node\Scalar\Int_
&& $node->dim->right->value === 1
) {
$arrayArg = $node->dim->left->getArgs()[0]->value;
$arrayType = $scope->getType($arrayArg);
if (
$arrayArg instanceof Node\Expr\Variable
&& $node->var instanceof Node\Expr\Variable
&& is_string($arrayArg->name)
&& $arrayArg->name === $node->var->name
&& $arrayType->isList()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
) {
return [];
$arrayArg = ArgumentsNormalizer::getArgByPositionOrName($node->dim->left->getArgs(), 0, 'value');
if ($arrayArg !== null) {
$arrayArg = $arrayArg->value;
$arrayType = $scope->getType($arrayArg);
if (
$arrayArg instanceof Node\Expr\Variable
&& $node->var instanceof Node\Expr\Variable
&& is_string($arrayArg->name)
&& $arrayArg->name === $node->var->name
&& $arrayType->isList()->yes()
&& $arrayType->isIterableAtLeastOnce()->yes()
) {
return [];
}
}
}

Expand Down
43 changes: 30 additions & 13 deletions src/Rules/Comparison/ImpossibleInArrayHaystackFiniteTypesRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\Scope;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\Conditional;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Php\PhpVersions;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
Expand All @@ -23,7 +24,6 @@
use function array_unique;
use function array_values;
use function count;
use function max;
use function sprintf;
use function strtolower;

Expand Down Expand Up @@ -51,8 +51,6 @@ final class ImpossibleInArrayHaystackFiniteTypesRule implements Rule

public function __construct(
private InitializerExprTypeResolver $initializerExprTypeResolver,
#[AutowiredParameter]
private bool $treatPhpDocTypesAsCertain,
private ReflectionProvider $reflectionProvider,
)
{
Expand All @@ -69,29 +67,48 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

$functionName = strtolower((string) $this->reflectionProvider->resolveFunctionName($node->name, $scope));
if (!array_key_exists($functionName, self::FUNCTIONS)) {
if (!$this->reflectionProvider->hasFunction($node->name, $scope)) {
return [];
}

$needleArg = self::FUNCTIONS[$functionName]['needle'];
$haystackArg = self::FUNCTIONS[$functionName]['haystack'];
$functionReflection = $this->reflectionProvider->getFunction($node->name, $scope);
$functionName = strtolower($functionReflection->getName());
if (!array_key_exists($functionName, self::FUNCTIONS)) {
return [];
}

$args = $node->getArgs();
if (count($args) <= max($needleArg, $haystackArg)) {
$parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
$scope,
$args,
$functionReflection->getVariants(),
$functionReflection->getNamedArgumentsVariants(),
);
$normalizedFuncCall = ArgumentsNormalizer::reorderFuncArguments($parametersAcceptor, $node);
if ($normalizedFuncCall === null) {
return [];
}

$normalizedArgs = $normalizedFuncCall->getArgs();
$needlePosition = self::FUNCTIONS[$functionName]['needle'];
$haystackPosition = self::FUNCTIONS[$functionName]['haystack'];
$needleArg = $normalizedArgs[$needlePosition] ?? null;
$haystackArg = $normalizedArgs[$haystackPosition] ?? null;
if ($needleArg === null || $haystackArg === null) {
return [];
}

$needleType = $this->treatPhpDocTypesAsCertain ? $scope->getType($args[$needleArg]->value) : $scope->getNativeType($args[$needleArg]->value);
$haystackType = $this->treatPhpDocTypesAsCertain ? $scope->getType($args[$haystackArg]->value) : $scope->getNativeType($args[$haystackArg]->value);
Comment thread
staabm marked this conversation as resolved.
Resolved
$needleType = $scope->getType($needleArg->value);
$haystackType = $scope->getType($haystackArg->value);

$constantArrays = $haystackType->getConstantArrays();
if (count($constantArrays) === 0) {
return [];
}

$isStrict = count($args) >= 3
? ($this->treatPhpDocTypesAsCertain ? $scope->getType($args[2]->value) : $scope->getNativeType($args[2]->value))->isTrue()
$strictArg = $normalizedArgs[2] ?? null;
$isStrict = $strictArg !== null
? $scope->getNativeType($strictArg->value)->isTrue()
: TrinaryLogic::createNo();

/** @var array<string, array{Type, list<string>, bool}> $deadValueTypes */
Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Rules/Api/GetTemplateTypeRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ public function testRule(): void
'Call to PHPStan\Type\ObjectType::getTemplateType() references unknown template type TSendd on class Generator.',
21,
],
[
'Call to PHPStan\Type\Type::getTemplateType() references unknown template type TSendd on class Generator.',
26,
],
]);
}

Expand Down
7 changes: 6 additions & 1 deletion tests/PHPStan/Rules/Api/data/get-template-type.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php // lint >= 8.0

namespace GetTemplateType;

Expand All @@ -21,4 +21,9 @@ public function doBar(ObjectType $type): void
$type->getTemplateType(Generator::class, 'TSendd');
}

public function doNamed(Type $type): void
{
$type->getTemplateType(templateTypeName: 'TSendd', ancestorClassName: Generator::class);
}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
<?php // lint >= 8.0

namespace ArrayDimFetchOnArrayKeyFirstOrLast;

Expand Down Expand Up @@ -47,4 +47,12 @@ public function countOnArray(array $hellos, array $anotherArray): string

return $hellos[count($hellos) - 1];
}

/**
* @param non-empty-array<string> $hellos
*/
public function namedRandom(array $hellos): string
{
return $hellos[array_rand(num: 1, array: $hellos)];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PHPStan\Rules\Comparison;

use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;
use PHPUnit\Framework\Attributes\RequiresPhp;
Expand All @@ -17,8 +18,7 @@ protected function getRule(): Rule
{
return new ImpossibleInArrayHaystackFiniteTypesRule(
self::getContainer()->getByType(InitializerExprTypeResolver::class),
true,
self::createReflectionProvider(),
self::getContainer()->getByType(ReflectionProvider::class),
);
}

Expand All @@ -42,6 +42,18 @@ public function testRule(): void
'Value ImpossibleInArrayFiniteTypes\Foo::ONE in the haystack passed to array_keys() can never be identical to the needle type int.',
38,
],
[
'Value ImpossibleInArrayFiniteTypes\Foo::ONE in the haystack passed to in_array() can never be identical to the needle type int.',
278,
],
[
'Value ImpossibleInArrayFiniteTypes\Foo::ONE in the haystack passed to array_search() can never be identical to the needle type int.',
279,
],
[
'Value ImpossibleInArrayFiniteTypes\Foo::ONE in the haystack passed to array_keys() can never be identical to the needle type int.',
280,
],
[
'Value \'installed\' in the haystack passed to in_array() can never be identical to the needle type mixed.',
99,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,3 +272,15 @@ function noErrorIntegerRangeNeedle(int $i): void
echo 'yes';
}
}

function reportedNamedInArray(int $i): void
{
in_array(haystack: [Foo::ONE, 1, 2], strict: true, needle: $i);
array_search(haystack: [Foo::ONE, 1, 2], strict: true, needle: $i);
array_keys(strict: true, filter_value: $i, array: [Foo::ONE, 1, 2]);
}

function noErrorNamedArrayKeysWithoutFilterValue(): void
{
array_keys(array: [Foo::ONE], strict: true);
}
Loading