Skip to content

Commit

Permalink
Introduce array_values rule
Browse files Browse the repository at this point in the history
  • Loading branch information
kamil-zacek committed Feb 14, 2024
1 parent 0b78c55 commit 37f3c82
Show file tree
Hide file tree
Showing 10 changed files with 218 additions and 2 deletions.
4 changes: 4 additions & 0 deletions build/spl-autoload-functions-pre-php-7.neon
Expand Up @@ -4,3 +4,7 @@ parameters:
message: "#^PHPDoc tag @var with type array\\<callable\\(\\)\\: mixed\\>\\|false is not subtype of native type list\\<callable\\(string\\)\\: void\\>\\|false\\.$#"
count: 2
path: ../src/Command/CommandHelper.php

-
message: '#^Parameter \#1 \$array \(list<PHPStan\\Type\\Type>\) of array_values is already a list, call has no effect\.$#'
path: ../src/Type/TypeCombinator.php
1 change: 1 addition & 0 deletions conf/bleedingEdge.neon
Expand Up @@ -7,6 +7,7 @@ parameters:
explicitMixedViaIsArray: true
arrayFilter: true
arrayUnpacking: true
arrayValues: true
nodeConnectingVisitorCompatibility: false
nodeConnectingVisitorRule: true
disableCheckMissingIterableValueType: true
Expand Down
7 changes: 7 additions & 0 deletions conf/config.level5.neon
Expand Up @@ -8,6 +8,8 @@ parameters:
conditionalTags:
PHPStan\Rules\Functions\ArrayFilterRule:
phpstan.rules.rule: %featureToggles.arrayFilter%
PHPStan\Rules\Functions\ArrayValuesRule:
phpstan.rules.rule: %featureToggles.arrayValues%
PHPStan\Rules\Functions\CallUserFuncRule:
phpstan.rules.rule: %featureToggles.callUserFunc%

Expand All @@ -28,5 +30,10 @@ services:
arguments:
treatPhpDocTypesAsCertain: %treatPhpDocTypesAsCertain%

-
class: PHPStan\Rules\Functions\ArrayValuesRule
arguments:
treatPhpDocTypesAsCertain: %treatPhpDocTypesAsCertain%

-
class: PHPStan\Rules\Functions\CallUserFuncRule
1 change: 1 addition & 0 deletions conf/config.neon
Expand Up @@ -41,6 +41,7 @@ parameters:
explicitMixedViaIsArray: false
arrayFilter: false
arrayUnpacking: false
arrayValues: false
nodeConnectingVisitorCompatibility: true
nodeConnectingVisitorRule: false
illegalConstructorMethodCall: false
Expand Down
1 change: 1 addition & 0 deletions conf/parametersSchema.neon
Expand Up @@ -36,6 +36,7 @@ parametersSchema:
explicitMixedViaIsArray: bool(),
arrayFilter: bool(),
arrayUnpacking: bool(),
arrayValues: bool(),
nodeConnectingVisitorCompatibility: bool(),
nodeConnectingVisitorRule: bool(),
illegalConstructorMethodCall: bool(),
Expand Down
105 changes: 105 additions & 0 deletions src/Rules/Functions/ArrayValuesRule.php
@@ -0,0 +1,105 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Functions;

use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\VerbosityLevel;
use function count;
use function sprintf;
use function strtolower;

/**
* @implements Rule<Node\Expr\FuncCall>
*/
class ArrayValuesRule implements Rule
{

public function __construct(
private readonly ReflectionProvider $reflectionProvider,
private readonly bool $treatPhpDocTypesAsCertain,
)
{
}

public function getNodeType(): string
{
return FuncCall::class;
}

public function processNode(Node $node, Scope $scope): array
{
if (!($node->name instanceof Node\Name)) {
return [];
}

if (AccessoryArrayListType::isListTypeEnabled() === false) {
return [];
}

$functionName = $this->reflectionProvider->resolveFunctionName($node->name, $scope);

if ($functionName === null || strtolower($functionName) !== 'array_values') {
return [];
}

$functionReflection = $this->reflectionProvider->getFunction($node->name, $scope);

$parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
$scope,
$node->getArgs(),
$functionReflection->getVariants(),
null,
);

$normalizedFuncCall = ArgumentsNormalizer::reorderFuncArguments($parametersAcceptor, $node);

if ($normalizedFuncCall === null) {
return [];
}

$args = $normalizedFuncCall->getArgs();

if (count($args) !== 1) {
return [];
}

if ($this->treatPhpDocTypesAsCertain === true) {
$arrayType = $scope->getType($args[0]->value);
} else {
$arrayType = $scope->getNativeType($args[0]->value);
}

if ($arrayType->isIterableAtLeastOnce()->no()) {
$message = 'Parameter #1 $array (%s) to function array_values is empty, call has no effect.';

return [
RuleErrorBuilder::message(sprintf(
$message,
$arrayType->describe(VerbosityLevel::value()),
))->build(),
];
}

if ($arrayType->isList()->yes()) {
$message = 'Parameter #1 $array (%s) of array_values is already a list, call has no effect.';

return [
RuleErrorBuilder::message(sprintf(
$message,
$arrayType->describe(VerbosityLevel::value()),
))->build(),
];
}

return [];
}

}
2 changes: 1 addition & 1 deletion src/Type/Constant/ConstantArrayType.php
Expand Up @@ -198,7 +198,7 @@ public function getAllArrays(): array
$keys = array_merge($requiredKeys, $combination);
sort($keys);

if ($this->isList->yes() && array_keys($keys) !== array_values($keys)) {
if ($this->isList->yes() && array_keys($keys) !== $keys) {
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Type/TypeCombinator.php
Expand Up @@ -1003,7 +1003,7 @@ public static function intersect(Type ...$types): Type

if ($hasOffsetValueTypeCount > 32) {
$newTypes[] = new OversizedArrayType();
$types = array_values($newTypes);
$types = $newTypes;
$typesCount = count($types);
}

Expand Down
73 changes: 73 additions & 0 deletions tests/PHPStan/Rules/Functions/ArrayValuesRuleTest.php
@@ -0,0 +1,73 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Functions;

use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;
use const PHP_VERSION_ID;

/**
* @extends RuleTestCase<ArrayValuesRule>
*/
class ArrayValuesRuleTest extends RuleTestCase
{

private bool $treatPhpDocTypesAsCertain = true;

protected function getRule(): Rule
{
return new ArrayValuesRule($this->createReflectionProvider(), $this->treatPhpDocTypesAsCertain);
}

public function testFile(): void
{
$expectedErrors = [
[
'Parameter #1 $array (array{0, 1, 3}) of array_values is already a list, call has no effect.',
8,
],
[
'Parameter #1 $array (array{1, 3}) of array_values is already a list, call has no effect.',
9,
],
[
'Parameter #1 $array (array{\'test\'}) of array_values is already a list, call has no effect.',
10,
],
[
'Parameter #1 $array (array{\'\', \'test\'}) of array_values is already a list, call has no effect.',
12,
],
[
'Parameter #1 $array (list<int>) of array_values is already a list, call has no effect.',
14,
],
[
'Parameter #1 $array (array{0}) of array_values is already a list, call has no effect.',
17,
],
[
'Parameter #1 $array (array{null, null}) of array_values is already a list, call has no effect.',
19,
],
[
'Parameter #1 $array (array{null, 0}) of array_values is already a list, call has no effect.',
20,
],
[
'Parameter #1 $array (array{}) to function array_values is empty, call has no effect.',
21,
],
];

if (PHP_VERSION_ID >= 80000) {
$expectedErrors[] = [
'Parameter #1 $array (list<int>) of array_values is already a list, call has no effect.',
24,
];
}

$this->analyse([__DIR__ . '/data/array_values_list.php'], $expectedErrors);
}

}
24 changes: 24 additions & 0 deletions tests/PHPStan/Rules/Functions/data/array_values_list.php
@@ -0,0 +1,24 @@
<?php

/** @var list<int> $list */
$list = [1, 2, 3];
/** @var list<int> $list */
$array = ['a' => 1, 'b' => 2, 'c' => 3];

array_values([0,1,3]);
array_values([1,3]);
array_values(['test']);
array_values(['a' => 'test']);
array_values(['', 'test']);
array_values(['a' => '', 'b' => 'test']);
array_values($list);
array_values($array);

array_values([0]);
array_values(['a' => null, 'b' => null]);
array_values([null, null]);
array_values([null, 0]);
array_values([]);

array_values(array: $array);
array_values(array: $list);

0 comments on commit 37f3c82

Please sign in to comment.