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
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
40 changes: 30 additions & 10 deletions src/Rules/Comparison/ImpossibleInArrayHaystackFiniteTypesRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@

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 +25,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 @@ -69,29 +70,48 @@
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 = $this->treatPhpDocTypesAsCertain ? $scope->getType($needleArg->value) : $scope->getNativeType($needleArg->value);
$haystackType = $this->treatPhpDocTypesAsCertain ? $scope->getType($haystackArg->value) : $scope->getNativeType($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
? ($this->treatPhpDocTypesAsCertain ? $scope->getType($strictArg->value) : $scope->getNativeType($strictArg->value))->isTrue()

Check warning on line 114 in src/Rules/Comparison/ImpossibleInArrayHaystackFiniteTypesRule.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\LooseBooleanMutator": @@ @@ $strictArg = $normalizedArgs[2] ?? null; $isStrict = $strictArg !== null - ? ($this->treatPhpDocTypesAsCertain ? $scope->getType($strictArg->value) : $scope->getNativeType($strictArg->value))->isTrue() + ? (($this->treatPhpDocTypesAsCertain ? $scope->getType($strictArg->value) : $scope->getNativeType($strictArg->value))->toBoolean())->isTrue() : TrinaryLogic::createNo(); /** @var array<string, array{Type, list<string>, bool}> $deadValueTypes */

Check warning on line 114 in src/Rules/Comparison/ImpossibleInArrayHaystackFiniteTypesRule.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\LooseBooleanMutator": @@ @@ $strictArg = $normalizedArgs[2] ?? null; $isStrict = $strictArg !== null - ? ($this->treatPhpDocTypesAsCertain ? $scope->getType($strictArg->value) : $scope->getNativeType($strictArg->value))->isTrue() + ? (($this->treatPhpDocTypesAsCertain ? $scope->getType($strictArg->value) : $scope->getNativeType($strictArg->value))->toBoolean())->isTrue() : TrinaryLogic::createNo(); /** @var array<string, array{Type, list<string>, bool}> $deadValueTypes */
: 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
Expand Up @@ -856,6 +856,14 @@ public function testArrayDimFetchAfterArrayKeyFirstOrLast(): void
'Offset null does not exist on array{}.',
19,
],
[
'Offset mixed might not exist on array<string, string>|string.',
81,
],
[
'Offset int|string might not exist on array<string, string>|string.',
89,
],
]);
}

Expand All @@ -876,6 +884,14 @@ public function testArrayDimFetchAfterCount(): void
'Offset int<0, max> might not exist on non-empty-array<string>.',
42,
],
[
'Offset int<-1, max> might not exist on list<string>.',
50,
],
[
'Offset int<0, max> might not exist on non-empty-array<int, string>.',
58,
],
]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,20 @@ public function shape(array $hellos): int|bool
}
return $hellos[$last];
}

/**
* @param array<string, string>|string $hellos
*/
public function maybeFirst(array|string $hellos): string
{
return $hellos[array_key_first($hellos)];
}

/**
* @param array<string, string>|string $hellos
*/
public function maybeRandom(array|string $hellos): string
{
return $hellos[array_rand($hellos, 1)];
}
}
15 changes: 15 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/array-dim-after-count.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,19 @@ public function maybeInvalid(array $hellos): string
return $hellos[$count];
}

/**
* @param list<string> $hellos
*/
public function maybeEmptyList(array $hellos): string
{
return $hellos[count($hellos) - 1];
}

/**
* @param non-empty-array<int, string> $hellos
*/
public function maybeNonListWithIntKeys(array $hellos): string
{
return $hellos[count($hellos) - 1];
}
}
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 @@ -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 Expand Up @@ -71,6 +83,14 @@ public function testRule(): void
'Value ImpossibleInArrayFiniteTypes\HttpStatus::ServerError in the haystack passed to in_array() can never be identical to the needle type int.',
261,
],
[
"Value 'c' in the haystack passed to array_search() can never be identical to the needle type 'a'|'b'.",
291,
],
[
"Value '1' in the haystack passed to array_search() can never be identical to the needle type int.",
297,
],
]);
}

Expand Down
Loading
Loading